-
Notifications
You must be signed in to change notification settings - Fork 41
/
router.ts
937 lines (888 loc) · 29.4 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
// Copyright Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache 2.0
/* eslint-disable */
import {
AbstractMessageRouter,
AbstractModule,
BOOT_STATUS,
CacheNamespace,
Call,
CallAction,
CallError,
CallResult,
ErrorCode,
EventGroup,
ICache,
IMessage,
IMessageConfirmation,
IMessageContext,
IMessageHandler,
IMessageRouter,
IMessageSender,
MessageOrigin,
MessageState,
MessageTriggerEnumType,
MessageTypeId,
OcppError,
OcppRequest,
OcppResponse,
RegistrationStatusEnumType,
RequestBuilder,
RetryMessageError,
SystemConfig,
TriggerMessageRequest,
} from '@citrineos/base';
import Ajv from 'ajv';
import { v4 as uuidv4 } from 'uuid';
import { ILogObj, Logger } from 'tslog';
import { ISubscriptionRepository, sequelize } from '@citrineos/data';
/**
* Implementation of the ocpp router
*/
export class MessageRouterImpl
extends AbstractMessageRouter
implements IMessageRouter
{
/**
* Fields
*/
protected _cache: ICache;
protected _sender: IMessageSender;
protected _handler: IMessageHandler;
protected _networkHook: (
identifier: string,
message: string,
) => Promise<boolean>;
// Structure of the maps: key = identifier, value = array of callbacks
private _onConnectionCallbacks: Map<
string,
((info?: Map<string, string>) => Promise<boolean>)[]
> = new Map();
private _onCloseCallbacks: Map<
string,
((info?: Map<string, string>) => Promise<boolean>)[]
> = new Map();
private _onMessageCallbacks: Map<
string,
((message: string, info?: Map<string, string>) => Promise<boolean>)[]
> = new Map();
private _sentMessageCallbacks: Map<
string,
((
message: string,
error?: any,
info?: Map<string, string>,
) => Promise<boolean>)[]
> = new Map();
public subscriptionRepository: ISubscriptionRepository;
/**
* Constructor for the class.
*
* @param {SystemConfig} config - the system configuration
* @param {ICache} cache - the cache object
* @param {IMessageSender} [sender] - the message sender
* @param {IMessageHandler} [handler] - the message handler
* @param {Function} networkHook - the network hook needed to send messages to chargers
* @param {ISubscriptionRepository} [subscriptionRepository] - the subscription repository
* @param {Logger<ILogObj>} [logger] - the logger object (optional)
* @param {Ajv} [ajv] - the Ajv object, for message validation (optional)
*/
constructor(
config: SystemConfig,
cache: ICache,
sender: IMessageSender,
handler: IMessageHandler,
networkHook: (identifier: string, message: string) => Promise<boolean>,
logger?: Logger<ILogObj>,
ajv?: Ajv,
subscriptionRepository?: ISubscriptionRepository,
) {
super(config, cache, handler, sender, networkHook, logger, ajv);
this._cache = cache;
this._sender = sender;
this._handler = handler;
this._networkHook = networkHook;
this.subscriptionRepository =
subscriptionRepository ||
new sequelize.SequelizeSubscriptionRepository(config, this._logger);
}
addOnConnectionCallback(
identifier: string,
onConnectionCallback: (info?: Map<string, string>) => Promise<boolean>,
): void {
this._onConnectionCallbacks.has(identifier)
? this._onConnectionCallbacks.get(identifier)!.push(onConnectionCallback)
: this._onConnectionCallbacks.set(identifier, [onConnectionCallback]);
}
addOnCloseCallback(
identifier: string,
onCloseCallback: (info?: Map<string, string>) => Promise<boolean>,
): void {
this._onCloseCallbacks.has(identifier)
? this._onCloseCallbacks.get(identifier)!.push(onCloseCallback)
: this._onCloseCallbacks.set(identifier, [onCloseCallback]);
}
addOnMessageCallback(
identifier: string,
onMessageCallback: (
message: string,
info?: Map<string, string>,
) => Promise<boolean>,
): void {
this._onMessageCallbacks.has(identifier)
? this._onMessageCallbacks.get(identifier)!.push(onMessageCallback)
: this._onMessageCallbacks.set(identifier, [onMessageCallback]);
}
addSentMessageCallback(
identifier: string,
sentMessageCallback: (
message: string,
error: any,
info?: Map<string, string>,
) => Promise<boolean>,
): void {
this._sentMessageCallbacks.has(identifier)
? this._sentMessageCallbacks.get(identifier)!.push(sentMessageCallback)
: this._sentMessageCallbacks.set(identifier, [sentMessageCallback]);
}
async registerConnection(connectionIdentifier: string): Promise<boolean> {
const loadConnectionCallbackSubscriptions =
this._loadSubscriptionsForConnection(connectionIdentifier).then(() => {
this._onConnectionCallbacks
.get(connectionIdentifier)
?.forEach(async (callback) => {
callback();
});
});
const requestSubscription = this._handler.subscribe(
connectionIdentifier,
undefined,
{
stationId: connectionIdentifier,
state: MessageState.Request.toString(),
origin: MessageOrigin.CentralSystem.toString(),
},
);
const responseSubscription = this._handler.subscribe(
connectionIdentifier,
undefined,
{
stationId: connectionIdentifier,
state: MessageState.Response.toString(),
origin: MessageOrigin.ChargingStation.toString(),
},
);
return Promise.all([
loadConnectionCallbackSubscriptions,
requestSubscription,
responseSubscription,
])
.then((resolvedArray) => resolvedArray[1] && resolvedArray[2])
.catch((error) => {
this._logger.error(
`Error registering connection for ${connectionIdentifier}: ${error}`,
);
return false;
});
}
async deregisterConnection(connectionIdentifier: string): Promise<boolean> {
this._onCloseCallbacks.get(connectionIdentifier)?.forEach((callback) => {
callback();
});
// TODO: ensure that all queue implementations in 02_Util only unsubscribe 1 queue per call
// ...which will require refactoring this method to unsubscribe request and response queues separately
return await this._handler.unsubscribe(connectionIdentifier);
}
// TODO: identifier may not be unique, may require combination of tenantId and identifier.
// find way to include tenantId here
async onMessage(identifier: string, message: string): Promise<boolean> {
this._onMessageCallbacks.get(identifier)?.forEach((callback) => {
callback(message);
});
let rpcMessage: any;
let messageTypeId: MessageTypeId | undefined = undefined;
let messageId: string = '-1'; // OCPP 2.0.1 part 4, section 4.2.3, "When also the MessageId cannot be read, the CALLERROR SHALL contain "-1" as MessageId."
try {
try {
rpcMessage = JSON.parse(message);
messageTypeId = rpcMessage[0];
messageId = rpcMessage[1];
} catch (error) {
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Invalid message format',
{ error: error },
);
}
switch (messageTypeId) {
case MessageTypeId.Call:
this._onCall(identifier, rpcMessage as Call);
break;
case MessageTypeId.CallResult:
this._onCallResult(identifier, rpcMessage as CallResult);
break;
case MessageTypeId.CallError:
this._onCallError(identifier, rpcMessage as CallError);
break;
default:
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Unknown message type id: ' + messageTypeId,
{},
);
}
return true;
} catch (error) {
this._logger.error('Error processing message:', message, error);
if (
messageTypeId != MessageTypeId.CallResult &&
messageTypeId != MessageTypeId.CallError
) {
const callError =
error instanceof OcppError
? error.asCallError()
: [
MessageTypeId.CallError,
messageId,
ErrorCode.InternalError,
'Unable to process message',
{ error: error },
];
const rawMessage = JSON.stringify(callError, (k, v) => v ?? undefined);
this._sendMessage(identifier, rawMessage);
}
// TODO: Publish raw payload for error reporting
return false;
}
}
/**
* Sends a Call message to a charging station with given identifier.
*
* @param {string} identifier - The identifier of the charging station.
* @param {Call} message - The Call message to send.
* @return {Promise<boolean>} A promise that resolves to a boolean indicating if the call was sent successfully.
*/
async sendCall(
identifier: string,
tenantId: string,
action: CallAction,
payload: OcppRequest,
correlationId = uuidv4(),
origin?: MessageOrigin,
): Promise<IMessageConfirmation> {
const message: Call = [MessageTypeId.Call, correlationId, action, payload];
if (await this._sendCallIsAllowed(identifier, message)) {
if (
await this._cache.setIfNotExist(
identifier,
`${action}:${correlationId}`,
CacheNamespace.Transactions,
this._config.maxCallLengthSeconds,
)
) {
// Intentionally removing NULL values from object for OCPP conformity
const rawMessage = JSON.stringify(message, (k, v) => v ?? undefined);
const success = await this._sendMessage(identifier, rawMessage);
return { success };
} else {
this._logger.info(
'Call already in progress, throwing retry exception',
identifier,
message,
);
throw new RetryMessageError('Call already in progress');
}
} else {
this._logger.info(
'RegistrationStatus Rejected, unable to send',
identifier,
message,
);
return { success: false };
}
}
/**
* Sends the CallResult to a charging station with given identifier.
*
* @param {string} identifier - The identifier of the charging station.
* @param {CallResult} message - The CallResult message to send.
* @return {Promise<boolean>} A promise that resolves to true if the call result was sent successfully, or false otherwise.
*/
async sendCallResult(
correlationId: string,
identifier: string,
tenantId: string,
action: CallAction,
payload: OcppResponse,
origin?: MessageOrigin,
): Promise<IMessageConfirmation> {
const message: CallResult = [
MessageTypeId.CallResult,
correlationId,
payload,
];
const cachedActionMessageId = await this._cache.get<string>(
identifier,
CacheNamespace.Transactions,
);
if (!cachedActionMessageId) {
this._logger.error(
'Failed to send callResult due to missing message id',
identifier,
message,
);
return { success: false };
}
let [cachedAction, cachedMessageId] = cachedActionMessageId?.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (cachedAction === action && cachedMessageId === correlationId) {
// Intentionally removing NULL values from object for OCPP conformity
const rawMessage = JSON.stringify(message, (k, v) => v ?? undefined);
const success = await Promise.all([
this._sendMessage(identifier, rawMessage),
this._cache.remove(identifier, CacheNamespace.Transactions),
]).then((successes) => successes.every(Boolean));
return { success };
} else {
this._logger.error(
'Failed to send callResult due to mismatch in message id',
identifier,
cachedActionMessageId,
message,
);
return { success: false };
}
}
/**
* Sends a CallError message to a charging station with given identifier.
*
* @param {string} identifier - The identifier of the charging station.
* @param {CallError} message - The CallError message to send.
* @return {Promise<boolean>} - A promise that resolves to true if the message was sent successfully.
*/
async sendCallError(
correlationId: string,
identifier: string,
tenantId: string,
action: CallAction,
error: OcppError,
origin?: MessageOrigin | undefined,
): Promise<IMessageConfirmation> {
const message: CallError = error.asCallError();
const cachedActionMessageId = await this._cache.get<string>(
identifier,
CacheNamespace.Transactions,
);
if (!cachedActionMessageId) {
this._logger.error(
'Failed to send callError due to missing message id',
identifier,
message,
);
return { success: false };
}
let [cachedAction, cachedMessageId] = cachedActionMessageId?.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (cachedMessageId === correlationId) {
// Intentionally removing NULL values from object for OCPP conformity
const rawMessage = JSON.stringify(message, (k, v) => v ?? undefined);
const success = await Promise.all([
this._sendMessage(identifier, rawMessage),
this._cache.remove(identifier, CacheNamespace.Transactions),
]).then((successes) => successes.every(Boolean));
return { success };
} else {
this._logger.error(
'Failed to send callError due to mismatch in message id',
identifier,
cachedActionMessageId,
message,
);
return { success: false };
}
}
shutdown(): void {
this._sender.shutdown();
this._handler.shutdown();
}
/**
* Private Methods
*/
/**
* Loads all subscriptions for a given connection into memory
*
* @param {string} connectionIdentifier - the identifier of the connection
* @return {Promise<void>} a promise that resolves once all subscriptions are loaded
*/
private async _loadSubscriptionsForConnection(connectionIdentifier: string) {
this._onConnectionCallbacks.set(connectionIdentifier, []);
this._onCloseCallbacks.set(connectionIdentifier, []);
this._onMessageCallbacks.set(connectionIdentifier, []);
this._sentMessageCallbacks.set(connectionIdentifier, []);
const subscriptions =
await this.subscriptionRepository.readAllByStationId(
connectionIdentifier,
);
for (const subscription of subscriptions) {
if (subscription.onConnect) {
this._onConnectionCallbacks
.get(connectionIdentifier)!
.push((info?: Map<string, string>) =>
this._subscriptionCallback(
{
stationId: connectionIdentifier,
event: 'connected',
info: info,
},
subscription.url,
),
);
this._logger.debug(
`Added onConnect callback to ${subscription.url} for station ${connectionIdentifier}`,
);
}
if (subscription.onClose) {
this._onCloseCallbacks
.get(connectionIdentifier)!
.push((info?: Map<string, string>) =>
this._subscriptionCallback(
{ stationId: connectionIdentifier, event: 'closed', info: info },
subscription.url,
),
);
this._logger.debug(
`Added onClose callback to ${subscription.url} for station ${connectionIdentifier}`,
);
}
if (subscription.onMessage) {
this._onMessageCallbacks
.get(connectionIdentifier)!
.push(async (message: string, info?: Map<string, string>) => {
if (
!subscription.messageRegexFilter ||
new RegExp(subscription.messageRegexFilter).test(message)
) {
return this._subscriptionCallback(
{
stationId: connectionIdentifier,
event: 'message',
origin: MessageOrigin.ChargingStation,
message: message,
info: info,
},
subscription.url,
);
} else {
// Ignore
return true;
}
});
this._logger.debug(
`Added onMessage callback to ${subscription.url} for station ${connectionIdentifier}`,
);
}
if (subscription.sentMessage) {
this._sentMessageCallbacks
.get(connectionIdentifier)!
.push(
async (
message: string,
error?: any,
info?: Map<string, string>,
) => {
if (
!subscription.messageRegexFilter ||
new RegExp(subscription.messageRegexFilter).test(message)
) {
return this._subscriptionCallback(
{
stationId: connectionIdentifier,
event: 'message',
origin: MessageOrigin.CentralSystem,
message: message,
error: error,
info: info,
},
subscription.url,
);
} else {
// Ignore
return true;
}
},
);
this._logger.debug(
`Added sentMessage callback to ${subscription.url} for station ${connectionIdentifier}`,
);
}
}
}
/**
* Sends a message to a given URL that has been subscribed to a station connection event
*
* @param {Object} requestBody - request body containing stationId, event, origin, message, error, and info
* @param {string} url - the URL to fetch data from
* @return {Promise<boolean>} a Promise that resolves to a boolean indicating success
*/
private _subscriptionCallback(
requestBody: {
stationId: string;
event: string;
origin?: MessageOrigin;
message?: string;
error?: any;
info?: Map<string, string>;
},
url: string,
): Promise<boolean> {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
})
.then((res) => res.status === 200)
.catch((error) => {
this._logger.error(error);
return false;
});
}
/**
* Handles an incoming Call message from a client connection.
*
* @param {string} identifier - The client identifier.
* @param {Call} message - The Call message received.
* @return {void}
*/
_onCall(identifier: string, message: Call): void {
const messageId = message[1];
const action = message[2] as CallAction;
const payload = message[3];
this._onCallIsAllowed(action, identifier)
.then((isAllowed: boolean) => {
if (!isAllowed) {
throw new OcppError(
messageId,
ErrorCode.SecurityError,
`Action ${action} not allowed`,
);
} else {
// Run schema validation for incoming Call message
return this._validateCall(identifier, message);
}
})
.then(({ isValid, errors }) => {
if (!isValid || errors) {
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Invalid message format',
{ errors: errors },
);
}
// Ensure only one call is processed at a time
return this._cache.setIfNotExist(
identifier,
`${action}:${messageId}`,
CacheNamespace.Transactions,
this._config.maxCallLengthSeconds,
);
})
.catch((error) => {
if (error instanceof OcppError) {
// TODO: identifier may not be unique, may require combination of tenantId and identifier.
// find way to include actual tenantId.
this.sendCallError(messageId, identifier, 'undefined', action, error);
}
})
.then((successfullySet) => {
if (!successfullySet) {
throw new OcppError(
messageId,
ErrorCode.RpcFrameworkError,
'Call already in progress',
{},
);
}
// Route call
return this._routeCall(identifier, message);
})
.then((confirmation) => {
if (!confirmation.success) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'Call failed',
{ details: confirmation.payload },
);
}
})
.catch((error) => {
if (error instanceof OcppError) {
// TODO: identifier may not be unique, may require combination of tenantId and identifier.
// find way to include tenantId here
this.sendCallError(messageId, identifier, 'undefined', action, error);
this._cache.remove(identifier, CacheNamespace.Transactions);
}
});
}
/**
* Handles a CallResult made by the client.
*
* @param {string} identifier - The client identifier that made the call.
* @param {CallResult} message - The OCPP CallResult message.
* @return {void}
*/
_onCallResult(identifier: string, message: CallResult): void {
const messageId = message[1];
const payload = message[2];
this._logger.debug('Process CallResult', identifier, messageId, payload);
this._cache
.get<string>(identifier, CacheNamespace.Transactions)
.then((cachedActionMessageId) => {
this._cache.remove(identifier, CacheNamespace.Transactions); // Always remove pending call transaction
if (!cachedActionMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'MessageId not found, call may have timed out',
{ maxCallLengthSeconds: this._config.maxCallLengthSeconds },
);
}
const [actionString, cachedMessageId] =
cachedActionMessageId.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (messageId !== cachedMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
"MessageId doesn't match",
{ expectedMessageId: cachedMessageId },
);
}
const action: CallAction =
CallAction[actionString as keyof typeof CallAction]; // Parse CallAction
return {
action,
...this._validateCallResult(identifier, action, message),
}; // Run schema validation for incoming CallResult message
})
.then(({ action, isValid, errors }) => {
if (!isValid || errors) {
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Invalid message format',
{ errors: errors },
);
}
// Route call result
return this._routeCallResult(identifier, message, action);
})
.then((confirmation) => {
if (!confirmation.success) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'CallResult failed',
{ details: confirmation.payload },
);
}
})
.catch((error) => {
// TODO: Ideally the error log is also stored in the database in a failed invocations table to ensure these are visible outside of a log file.
this._logger.error('Failed processing call result: ', error);
});
}
/**
* Handles the CallError that may have occured during a Call exchange.
*
* @param {string} identifier - The client identifier.
* @param {CallError} message - The error message.
* @return {void} This function doesn't return anything.
*/
_onCallError(identifier: string, message: CallError): void {
const messageId = message[1];
this._logger.debug('Process CallError', identifier, message);
this._cache
.get<string>(identifier, CacheNamespace.Transactions)
.then((cachedActionMessageId) => {
this._cache.remove(identifier, CacheNamespace.Transactions); // Always remove pending call transaction
if (!cachedActionMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'MessageId not found, call may have timed out',
{ maxCallLengthSeconds: this._config.maxCallLengthSeconds },
);
}
const [actionString, cachedMessageId] =
cachedActionMessageId.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (messageId !== cachedMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
"MessageId doesn't match",
{ expectedMessageId: cachedMessageId },
);
}
const action: CallAction =
CallAction[actionString as keyof typeof CallAction]; // Parse CallAction
return this._routeCallError(identifier, message, action);
})
.then((confirmation) => {
if (!confirmation.success) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'CallError failed',
{ details: confirmation.payload },
);
}
})
.catch((error) => {
// TODO: Ideally the error log is also stored in the database in a failed invocations table to ensure these are visible outside of a log file.
this._logger.error('Failed processing call error: ', error);
});
}
/**
* Determine if the given action for identifier is allowed.
*
* @param {CallAction} action - The action to be checked.
* @param {string} identifier - The identifier to be checked.
* @return {Promise<boolean>} A promise that resolves to a boolean indicating if the action and identifier are allowed.
*/
private _onCallIsAllowed(
action: CallAction,
identifier: string,
): Promise<boolean> {
return this._cache
.exists(action, identifier)
.then((blacklisted) => !blacklisted);
}
private async _sendMessage(
identifier: string,
rawMessage: string,
): Promise<boolean> {
try {
const success = await this._networkHook(identifier, rawMessage);
this._sentMessageCallbacks.get(identifier)?.forEach((callback) => {
callback(rawMessage);
});
return success;
} catch (error) {
this._sentMessageCallbacks.get(identifier)?.forEach((callback) => {
callback(rawMessage, error);
});
return false;
}
}
private async _sendCallIsAllowed(
identifier: string,
message: Call,
): Promise<boolean> {
const status = await this._cache.get<string>(BOOT_STATUS, identifier);
if (
status === RegistrationStatusEnumType.Rejected &&
// TriggerMessage<BootNotification> is the only message allowed to be sent during Rejected BootStatus B03.FR.08
!(
(message[2] as CallAction) === CallAction.TriggerMessage &&
(message[3] as TriggerMessageRequest).requestedMessage ==
MessageTriggerEnumType.BootNotification
)
) {
return false;
}
return true;
}
private async _routeCall(
connectionIdentifier: string,
message: Call,
): Promise<IMessageConfirmation> {
const messageId = message[1];
const action = message[2] as CallAction;
const payload = message[3] as OcppRequest;
const _message: IMessage<OcppRequest> = RequestBuilder.buildCall(
connectionIdentifier,
messageId,
'', // TODO: Add tenantId to method
action,
payload,
EventGroup.General, // TODO: Change to appropriate event group
MessageOrigin.ChargingStation,
);
return this._sender.send(_message);
}
private async _routeCallResult(
connectionIdentifier: string,
message: CallResult,
action: CallAction,
): Promise<IMessageConfirmation> {
const messageId = message[1];
const payload = message[2] as OcppResponse;
// TODO: Add tenantId to context
const context: IMessageContext = {
correlationId: messageId,
stationId: connectionIdentifier,
tenantId: '',
};
const _message: IMessage<OcppRequest> = {
origin: MessageOrigin.CentralSystem,
eventGroup: EventGroup.General,
action,
state: MessageState.Response,
context,
payload,
};
return this._sender.send(_message);
}
private async _routeCallError(
connectionIdentifier: string,
message: CallError,
action: CallAction,
): Promise<IMessageConfirmation> {
const messageId = message[1];
const payload = new OcppError(
messageId,
message[2],
message[3],
message[4],
);
// TODO: Add tenantId to context
const context: IMessageContext = {
correlationId: messageId,
stationId: connectionIdentifier,
tenantId: '',
};
const _message: IMessage<OcppError> = {
origin: MessageOrigin.CentralSystem,
eventGroup: EventGroup.General,
action,
state: MessageState.Response,
context,
payload,
};
// Fulfill callback for api, if needed
this._handleMessageApiCallback(_message);
// No error routing currently done
throw new Error('Method not implemented.');
}
private async _handleMessageApiCallback(
message: IMessage<OcppError>,
): Promise<void> {
const url: string | null = await this._cache.get(
message.context.correlationId,
AbstractModule.CALLBACK_URL_CACHE_PREFIX + message.context.stationId,
);
if (url) {
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(message.payload),
});
}
}
}