09cfa74f42e4d13d13245981b55e7a80d31d4921
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import {
4 AvailabilityType,
5 BootNotificationRequest,
6 CachedRequest,
7 IncomingRequest,
8 IncomingRequestCommand,
9 RequestCommand,
10 } from '../types/ocpp/Requests';
11 import {
12 BootNotificationResponse,
13 HeartbeatResponse,
14 MeterValuesResponse,
15 RegistrationStatus,
16 StatusNotificationResponse,
17 } from '../types/ocpp/Responses';
18 import ChargingStationConfiguration, {
19 ConfigurationKey,
20 } from '../types/ChargingStationConfiguration';
21 import ChargingStationTemplate, {
22 CurrentType,
23 PowerUnits,
24 Voltage,
25 } from '../types/ChargingStationTemplate';
26 import {
27 ConnectorPhaseRotation,
28 StandardParametersKey,
29 SupportedFeatureProfiles,
30 VendorDefaultParametersKey,
31 } from '../types/ocpp/Configuration';
32 import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
33 import { StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction';
34 import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
35 import WebSocket, { ClientOptions, Data, OPEN, RawData } from 'ws';
36
37 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
38 import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
39 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
40 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
41 import ChargingStationInfo from '../types/ChargingStationInfo';
42 import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
43 import { ClientRequestArgs } from 'http';
44 import Configuration from '../utils/Configuration';
45 import { ConnectorStatus } from '../types/ConnectorStatus';
46 import Constants from '../utils/Constants';
47 import { ErrorType } from '../types/ocpp/ErrorType';
48 import { FileType } from '../types/FileType';
49 import FileUtils from '../utils/FileUtils';
50 import { JsonType } from '../types/JsonType';
51 import { MessageType } from '../types/ocpp/MessageType';
52 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
53 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
54 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
55 import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
56 import OCPPError from '../exception/OCPPError';
57 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
58 import OCPPRequestService from './ocpp/OCPPRequestService';
59 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
60 import PerformanceStatistics from '../performance/PerformanceStatistics';
61 import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
62 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
63 import { URL } from 'url';
64 import Utils from '../utils/Utils';
65 import crypto from 'crypto';
66 import fs from 'fs';
67 import logger from '../utils/Logger';
68 import { parentPort } from 'worker_threads';
69 import path from 'path';
70
71 export default class ChargingStation {
72 public hashId!: string;
73 public readonly stationTemplateFile: string;
74 public authorizedTags: string[];
75 public stationInfo!: ChargingStationInfo;
76 public readonly connectors: Map<number, ConnectorStatus>;
77 public configuration!: ChargingStationConfiguration;
78 public wsConnection!: WebSocket;
79 public readonly requests: Map<string, CachedRequest>;
80 public performanceStatistics!: PerformanceStatistics;
81 public heartbeatSetInterval!: NodeJS.Timeout;
82 public ocppRequestService!: OCPPRequestService;
83 public bootNotificationResponse!: BootNotificationResponse | null;
84 private readonly index: number;
85 private configurationFile!: string;
86 private bootNotificationRequest!: BootNotificationRequest;
87 private connectorsConfigurationHash!: string;
88 private ocppIncomingRequestService!: OCPPIncomingRequestService;
89 private readonly messageBuffer: Set<string>;
90 private wsConfiguredConnectionUrl!: URL;
91 private wsConnectionRestarted: boolean;
92 private stopped: boolean;
93 private autoReconnectRetryCount: number;
94 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
95 private webSocketPingSetInterval!: NodeJS.Timeout;
96
97 constructor(index: number, stationTemplateFile: string) {
98 this.index = index;
99 this.stationTemplateFile = stationTemplateFile;
100 this.stopped = false;
101 this.wsConnectionRestarted = false;
102 this.autoReconnectRetryCount = 0;
103 this.connectors = new Map<number, ConnectorStatus>();
104 this.requests = new Map<string, CachedRequest>();
105 this.messageBuffer = new Set<string>();
106 this.initialize();
107 this.authorizedTags = this.getAuthorizedTags();
108 }
109
110 private get wsConnectionUrl(): URL {
111 return this.getSupervisionUrlOcppConfiguration()
112 ? new URL(
113 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value +
114 '/' +
115 this.stationInfo.chargingStationId
116 )
117 : this.wsConfiguredConnectionUrl;
118 }
119
120 public logPrefix(): string {
121 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
122 }
123
124 public getBootNotificationRequest(): BootNotificationRequest {
125 return this.bootNotificationRequest;
126 }
127
128 public getRandomIdTag(): string {
129 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
130 return this.authorizedTags[index];
131 }
132
133 public hasAuthorizedTags(): boolean {
134 return !Utils.isEmptyArray(this.authorizedTags);
135 }
136
137 public getEnableStatistics(): boolean | undefined {
138 return !Utils.isUndefined(this.stationInfo.enableStatistics)
139 ? this.stationInfo.enableStatistics
140 : true;
141 }
142
143 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
144 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
145 }
146
147 public getNumberOfPhases(): number | undefined {
148 switch (this.getCurrentOutType()) {
149 case CurrentType.AC:
150 return !Utils.isUndefined(this.stationInfo.numberOfPhases)
151 ? this.stationInfo.numberOfPhases
152 : 3;
153 case CurrentType.DC:
154 return 0;
155 }
156 }
157
158 public isWebSocketConnectionOpened(): boolean {
159 return this?.wsConnection?.readyState === OPEN;
160 }
161
162 public getRegistrationStatus(): RegistrationStatus {
163 return this?.bootNotificationResponse?.status;
164 }
165
166 public isInUnknownState(): boolean {
167 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
168 }
169
170 public isInPendingState(): boolean {
171 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
172 }
173
174 public isInAcceptedState(): boolean {
175 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
176 }
177
178 public isInRejectedState(): boolean {
179 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
180 }
181
182 public isRegistered(): boolean {
183 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
184 }
185
186 public isChargingStationAvailable(): boolean {
187 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
188 }
189
190 public isConnectorAvailable(id: number): boolean {
191 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
192 }
193
194 public getNumberOfConnectors(): number {
195 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
196 }
197
198 public getConnectorStatus(id: number): ConnectorStatus {
199 return this.connectors.get(id);
200 }
201
202 public getCurrentOutType(): CurrentType | undefined {
203 return this.stationInfo.currentOutType ?? CurrentType.AC;
204 }
205
206 public getOcppStrictCompliance(): boolean {
207 return this.stationInfo.ocppStrictCompliance ?? false;
208 }
209
210 public getVoltageOut(): number | undefined {
211 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
212 this.stationTemplateFile
213 }, cannot define default voltage out`;
214 let defaultVoltageOut: number;
215 switch (this.getCurrentOutType()) {
216 case CurrentType.AC:
217 defaultVoltageOut = Voltage.VOLTAGE_230;
218 break;
219 case CurrentType.DC:
220 defaultVoltageOut = Voltage.VOLTAGE_400;
221 break;
222 default:
223 logger.error(errMsg);
224 throw new Error(errMsg);
225 }
226 return !Utils.isUndefined(this.stationInfo.voltageOut)
227 ? this.stationInfo.voltageOut
228 : defaultVoltageOut;
229 }
230
231 public getTransactionIdTag(transactionId: number): string | undefined {
232 for (const connectorId of this.connectors.keys()) {
233 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
234 return this.getConnectorStatus(connectorId).transactionIdTag;
235 }
236 }
237 }
238
239 public getOutOfOrderEndMeterValues(): boolean {
240 return this.stationInfo.outOfOrderEndMeterValues ?? false;
241 }
242
243 public getBeginEndMeterValues(): boolean {
244 return this.stationInfo.beginEndMeterValues ?? false;
245 }
246
247 public getMeteringPerTransaction(): boolean {
248 return this.stationInfo.meteringPerTransaction ?? true;
249 }
250
251 public getTransactionDataMeterValues(): boolean {
252 return this.stationInfo.transactionDataMeterValues ?? false;
253 }
254
255 public getMainVoltageMeterValues(): boolean {
256 return this.stationInfo.mainVoltageMeterValues ?? true;
257 }
258
259 public getPhaseLineToLineVoltageMeterValues(): boolean {
260 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
261 }
262
263 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
264 for (const connectorId of this.connectors.keys()) {
265 if (
266 connectorId > 0 &&
267 this.getConnectorStatus(connectorId)?.transactionId === transactionId
268 ) {
269 return connectorId;
270 }
271 }
272 }
273
274 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
275 const transactionConnectorStatus = this.getConnectorStatus(
276 this.getConnectorIdByTransactionId(transactionId)
277 );
278 if (this.getMeteringPerTransaction()) {
279 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
280 }
281 return transactionConnectorStatus?.energyActiveImportRegisterValue;
282 }
283
284 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
285 const connectorStatus = this.getConnectorStatus(connectorId);
286 if (this.getMeteringPerTransaction()) {
287 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
288 }
289 return connectorStatus?.energyActiveImportRegisterValue;
290 }
291
292 public getAuthorizeRemoteTxRequests(): boolean {
293 const authorizeRemoteTxRequests = this.getConfigurationKey(
294 StandardParametersKey.AuthorizeRemoteTxRequests
295 );
296 return authorizeRemoteTxRequests
297 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
298 : false;
299 }
300
301 public getLocalAuthListEnabled(): boolean {
302 const localAuthListEnabled = this.getConfigurationKey(
303 StandardParametersKey.LocalAuthListEnabled
304 );
305 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
306 }
307
308 public restartWebSocketPing(): void {
309 // Stop WebSocket ping
310 this.stopWebSocketPing();
311 // Start WebSocket ping
312 this.startWebSocketPing();
313 }
314
315 public getSampledValueTemplate(
316 connectorId: number,
317 measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
318 phase?: MeterValuePhase
319 ): SampledValueTemplate | undefined {
320 const onPhaseStr = phase ? `on phase ${phase} ` : '';
321 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
322 logger.warn(
323 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
324 );
325 return;
326 }
327 if (
328 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
329 !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
330 measurand
331 )
332 ) {
333 logger.debug(
334 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
335 StandardParametersKey.MeterValuesSampledData
336 }' OCPP parameter`
337 );
338 return;
339 }
340 const sampledValueTemplates: SampledValueTemplate[] =
341 this.getConnectorStatus(connectorId).MeterValues;
342 for (
343 let index = 0;
344 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
345 index++
346 ) {
347 if (
348 !Constants.SUPPORTED_MEASURANDS.includes(
349 sampledValueTemplates[index]?.measurand ??
350 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
351 )
352 ) {
353 logger.warn(
354 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
355 );
356 } else if (
357 phase &&
358 sampledValueTemplates[index]?.phase === phase &&
359 sampledValueTemplates[index]?.measurand === measurand &&
360 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
361 measurand
362 )
363 ) {
364 return sampledValueTemplates[index];
365 } else if (
366 !phase &&
367 !sampledValueTemplates[index].phase &&
368 sampledValueTemplates[index]?.measurand === measurand &&
369 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
370 measurand
371 )
372 ) {
373 return sampledValueTemplates[index];
374 } else if (
375 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
376 (!sampledValueTemplates[index].measurand ||
377 sampledValueTemplates[index].measurand === measurand)
378 ) {
379 return sampledValueTemplates[index];
380 }
381 }
382 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
383 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
384 logger.error(errorMsg);
385 throw new Error(errorMsg);
386 }
387 logger.debug(
388 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
389 );
390 }
391
392 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
393 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
394 }
395
396 public startHeartbeat(): void {
397 if (
398 this.getHeartbeatInterval() &&
399 this.getHeartbeatInterval() > 0 &&
400 !this.heartbeatSetInterval
401 ) {
402 // eslint-disable-next-line @typescript-eslint/no-misused-promises
403 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
404 await this.ocppRequestService.sendMessageHandler<HeartbeatResponse>(
405 RequestCommand.HEARTBEAT
406 );
407 }, this.getHeartbeatInterval());
408 logger.info(
409 this.logPrefix() +
410 ' Heartbeat started every ' +
411 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
412 );
413 } else if (this.heartbeatSetInterval) {
414 logger.info(
415 this.logPrefix() +
416 ' Heartbeat already started every ' +
417 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
418 );
419 } else {
420 logger.error(
421 `${this.logPrefix()} Heartbeat interval set to ${
422 this.getHeartbeatInterval()
423 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
424 : this.getHeartbeatInterval()
425 }, not starting the heartbeat`
426 );
427 }
428 }
429
430 public restartHeartbeat(): void {
431 // Stop heartbeat
432 this.stopHeartbeat();
433 // Start heartbeat
434 this.startHeartbeat();
435 }
436
437 public startMeterValues(connectorId: number, interval: number): void {
438 if (connectorId === 0) {
439 logger.error(
440 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
441 );
442 return;
443 }
444 if (!this.getConnectorStatus(connectorId)) {
445 logger.error(
446 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
447 );
448 return;
449 }
450 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
451 logger.error(
452 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
453 );
454 return;
455 } else if (
456 this.getConnectorStatus(connectorId)?.transactionStarted &&
457 !this.getConnectorStatus(connectorId)?.transactionId
458 ) {
459 logger.error(
460 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
461 );
462 return;
463 }
464 if (interval > 0) {
465 // eslint-disable-next-line @typescript-eslint/no-misused-promises
466 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
467 // eslint-disable-next-line @typescript-eslint/no-misused-promises
468 async (): Promise<void> => {
469 // FIXME: Implement OCPP version agnostic helpers
470 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
471 this,
472 connectorId,
473 this.getConnectorStatus(connectorId).transactionId,
474 interval
475 );
476 await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
477 RequestCommand.METER_VALUES,
478 {
479 connectorId,
480 transactionId: this.getConnectorStatus(connectorId).transactionId,
481 meterValue: [meterValue],
482 }
483 );
484 },
485 interval
486 );
487 } else {
488 logger.error(
489 `${this.logPrefix()} Charging station ${
490 StandardParametersKey.MeterValueSampleInterval
491 } configuration set to ${
492 interval ? Utils.formatDurationMilliSeconds(interval) : interval
493 }, not sending MeterValues`
494 );
495 }
496 }
497
498 public start(): void {
499 if (this.getEnableStatistics()) {
500 this.performanceStatistics.start();
501 }
502 this.openWSConnection();
503 // Monitor authorization file
504 FileUtils.watchJsonFile<string[]>(
505 this.logPrefix(),
506 FileType.Authorization,
507 this.getAuthorizationFile(),
508 this.authorizedTags
509 );
510 // Monitor charging station template file
511 FileUtils.watchJsonFile(
512 this.logPrefix(),
513 FileType.ChargingStationTemplate,
514 this.stationTemplateFile,
515 null,
516 (event, filename): void => {
517 if (filename && event === 'change') {
518 try {
519 logger.debug(
520 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
521 this.stationTemplateFile
522 } file have changed, reload`
523 );
524 // Initialize
525 this.initialize();
526 // Restart the ATG
527 if (
528 !this.stationInfo.AutomaticTransactionGenerator.enable &&
529 this.automaticTransactionGenerator
530 ) {
531 this.automaticTransactionGenerator.stop();
532 }
533 this.startAutomaticTransactionGenerator();
534 if (this.getEnableStatistics()) {
535 this.performanceStatistics.restart();
536 } else {
537 this.performanceStatistics.stop();
538 }
539 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
540 } catch (error) {
541 logger.error(
542 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
543 error
544 );
545 }
546 }
547 }
548 );
549 // Handle WebSocket message
550 this.wsConnection.on(
551 'message',
552 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
553 );
554 // Handle WebSocket error
555 this.wsConnection.on(
556 'error',
557 this.onError.bind(this) as (this: WebSocket, error: Error) => void
558 );
559 // Handle WebSocket close
560 this.wsConnection.on(
561 'close',
562 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
563 );
564 // Handle WebSocket open
565 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
566 // Handle WebSocket ping
567 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
568 // Handle WebSocket pong
569 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
570 parentPort.postMessage({
571 id: ChargingStationWorkerMessageEvents.STARTED,
572 data: { id: this.stationInfo.chargingStationId },
573 });
574 }
575
576 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
577 // Stop message sequence
578 await this.stopMessageSequence(reason);
579 for (const connectorId of this.connectors.keys()) {
580 if (connectorId > 0) {
581 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
582 RequestCommand.STATUS_NOTIFICATION,
583 {
584 connectorId,
585 status: ChargePointStatus.UNAVAILABLE,
586 errorCode: ChargePointErrorCode.NO_ERROR,
587 }
588 );
589 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
590 }
591 }
592 if (this.isWebSocketConnectionOpened()) {
593 this.wsConnection.close();
594 }
595 if (this.getEnableStatistics()) {
596 this.performanceStatistics.stop();
597 }
598 this.bootNotificationResponse = null;
599 parentPort.postMessage({
600 id: ChargingStationWorkerMessageEvents.STOPPED,
601 data: { id: this.stationInfo.chargingStationId },
602 });
603 this.stopped = true;
604 }
605
606 public getConfigurationKey(
607 key: string | StandardParametersKey,
608 caseInsensitive = false
609 ): ConfigurationKey | undefined {
610 return this.configuration.configurationKey.find((configElement) => {
611 if (caseInsensitive) {
612 return configElement.key.toLowerCase() === key.toLowerCase();
613 }
614 return configElement.key === key;
615 });
616 }
617
618 public addConfigurationKey(
619 key: string | StandardParametersKey,
620 value: string,
621 options: { readonly?: boolean; visible?: boolean; reboot?: boolean } = {
622 readonly: false,
623 visible: true,
624 reboot: false,
625 },
626 params: { overwrite?: boolean; save?: boolean } = { overwrite: false, save: false }
627 ): void {
628 if (!options || Utils.isEmptyObject(options)) {
629 options = {
630 readonly: false,
631 visible: true,
632 reboot: false,
633 };
634 }
635 const readonly = options.readonly;
636 const visible = options.visible;
637 const reboot = options.reboot;
638 let keyFound = this.getConfigurationKey(key);
639 if (keyFound && params?.overwrite) {
640 this.deleteConfigurationKey(keyFound.key, { save: false });
641 keyFound = undefined;
642 }
643 if (!keyFound) {
644 this.configuration.configurationKey.push({
645 key,
646 readonly,
647 value,
648 visible,
649 reboot,
650 });
651 params?.save && this.saveConfiguration();
652 } else {
653 logger.error(
654 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
655 keyFound
656 );
657 }
658 }
659
660 public setConfigurationKeyValue(
661 key: string | StandardParametersKey,
662 value: string,
663 caseInsensitive = false
664 ): void {
665 const keyFound = this.getConfigurationKey(key, caseInsensitive);
666 if (keyFound) {
667 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
668 this.configuration.configurationKey[keyIndex].value = value;
669 this.saveConfiguration();
670 } else {
671 logger.error(
672 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
673 { key, value }
674 );
675 }
676 }
677
678 public deleteConfigurationKey(
679 key: string | StandardParametersKey,
680 params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false }
681 ): ConfigurationKey[] {
682 const keyFound = this.getConfigurationKey(key, params?.caseInsensitive);
683 if (keyFound) {
684 const deletedConfigurationKey = this.configuration.configurationKey.splice(
685 this.configuration.configurationKey.indexOf(keyFound),
686 1
687 );
688 params?.save && this.saveConfiguration();
689 return deletedConfigurationKey;
690 }
691 }
692
693 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
694 let cpReplaced = false;
695 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
696 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
697 (chargingProfile: ChargingProfile, index: number) => {
698 if (
699 chargingProfile.chargingProfileId === cp.chargingProfileId ||
700 (chargingProfile.stackLevel === cp.stackLevel &&
701 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
702 ) {
703 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
704 cpReplaced = true;
705 }
706 }
707 );
708 }
709 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
710 }
711
712 public resetConnectorStatus(connectorId: number): void {
713 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
714 this.getConnectorStatus(connectorId).idTagAuthorized = false;
715 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
716 this.getConnectorStatus(connectorId).transactionStarted = false;
717 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
718 delete this.getConnectorStatus(connectorId).authorizeIdTag;
719 delete this.getConnectorStatus(connectorId).transactionId;
720 delete this.getConnectorStatus(connectorId).transactionIdTag;
721 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
722 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
723 this.stopMeterValues(connectorId);
724 }
725
726 public bufferMessage(message: string): void {
727 this.messageBuffer.add(message);
728 }
729
730 private flushMessageBuffer() {
731 if (this.messageBuffer.size > 0) {
732 this.messageBuffer.forEach((message) => {
733 // TODO: evaluate the need to track performance
734 this.wsConnection.send(message);
735 this.messageBuffer.delete(message);
736 });
737 }
738 }
739
740 private getSupervisionUrlOcppConfiguration(): boolean {
741 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
742 }
743
744 private getSupervisionUrlOcppKey(): string {
745 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
746 }
747
748 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
749 // In case of multiple instances: add instance index to charging station id
750 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
751 const idSuffix = stationTemplate.nameSuffix ?? '';
752 const idStr = '000000000' + this.index.toString();
753 return stationTemplate.fixedName
754 ? stationTemplate.baseName
755 : stationTemplate.baseName +
756 '-' +
757 instanceIndex.toString() +
758 idStr.substring(idStr.length - 4) +
759 idSuffix;
760 }
761
762 private buildStationInfo(): ChargingStationInfo {
763 let stationTemplateFromFile: ChargingStationTemplate;
764 try {
765 // Load template file
766 stationTemplateFromFile = JSON.parse(
767 fs.readFileSync(this.stationTemplateFile, 'utf8')
768 ) as ChargingStationTemplate;
769 } catch (error) {
770 FileUtils.handleFileException(
771 this.logPrefix(),
772 FileType.ChargingStationTemplate,
773 this.stationTemplateFile,
774 error as NodeJS.ErrnoException
775 );
776 }
777 const chargingStationId = this.getChargingStationId(stationTemplateFromFile);
778 // Deprecation template keys section
779 this.warnDeprecatedTemplateKey(
780 stationTemplateFromFile,
781 'supervisionUrl',
782 chargingStationId,
783 "Use 'supervisionUrls' instead"
784 );
785 this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
786 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? ({} as ChargingStationInfo);
787 stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
788 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
789 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
790 const powerArrayRandomIndex = Math.floor(
791 Utils.secureRandom() * stationTemplateFromFile.power.length
792 );
793 stationInfo.maxPower =
794 stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
795 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
796 : stationTemplateFromFile.power[powerArrayRandomIndex];
797 } else {
798 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
799 stationInfo.maxPower =
800 stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
801 ? stationTemplateFromFile.power * 1000
802 : stationTemplateFromFile.power;
803 }
804 delete stationInfo.power;
805 delete stationInfo.powerUnit;
806 stationInfo.chargingStationId = chargingStationId;
807 stationInfo.resetTime = stationTemplateFromFile.resetTime
808 ? stationTemplateFromFile.resetTime * 1000
809 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
810 return stationInfo;
811 }
812
813 private getOcppVersion(): OCPPVersion {
814 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
815 }
816
817 private getOcppPersistentConfiguration(): boolean {
818 return this.stationInfo.ocppPersistentConfiguration ?? true;
819 }
820
821 private handleUnsupportedVersion(version: OCPPVersion) {
822 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
823 this.stationTemplateFile
824 }`;
825 logger.error(errMsg);
826 throw new Error(errMsg);
827 }
828
829 private initialize(): void {
830 this.stationInfo = this.buildStationInfo();
831 this.bootNotificationRequest = {
832 chargePointModel: this.stationInfo.chargePointModel,
833 chargePointVendor: this.stationInfo.chargePointVendor,
834 ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && {
835 chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix,
836 }),
837 ...(!Utils.isUndefined(this.stationInfo.firmwareVersion) && {
838 firmwareVersion: this.stationInfo.firmwareVersion,
839 }),
840 ...(!Utils.isUndefined(this.stationInfo.iccid) && { iccid: this.stationInfo.iccid }),
841 ...(!Utils.isUndefined(this.stationInfo.imsi) && { imsi: this.stationInfo.imsi }),
842 ...(!Utils.isUndefined(this.stationInfo.meterSerialNumber) && {
843 meterSerialNumber: this.stationInfo.meterSerialNumber,
844 }),
845 ...(!Utils.isUndefined(this.stationInfo.meterType) && {
846 meterType: this.stationInfo.meterType,
847 }),
848 };
849
850 this.hashId = crypto
851 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
852 .update(JSON.stringify(this.bootNotificationRequest) + this.stationInfo.chargingStationId)
853 .digest('hex');
854 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
855 this.configurationFile = path.join(
856 path.resolve(__dirname, '../'),
857 'assets',
858 'configurations',
859 this.hashId + '.json'
860 );
861 this.configuration = this.getConfiguration();
862 delete this.stationInfo.Configuration;
863 // Build connectors if needed
864 const maxConnectors = this.getMaxNumberOfConnectors();
865 if (maxConnectors <= 0) {
866 logger.warn(
867 `${this.logPrefix()} Charging station template ${
868 this.stationTemplateFile
869 } with ${maxConnectors} connectors`
870 );
871 }
872 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
873 if (templateMaxConnectors <= 0) {
874 logger.warn(
875 `${this.logPrefix()} Charging station template ${
876 this.stationTemplateFile
877 } with no connector configuration`
878 );
879 }
880 if (!this.stationInfo.Connectors[0]) {
881 logger.warn(
882 `${this.logPrefix()} Charging station template ${
883 this.stationTemplateFile
884 } with no connector Id 0 configuration`
885 );
886 }
887 // Sanity check
888 if (
889 maxConnectors >
890 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
891 !this.stationInfo.randomConnectors
892 ) {
893 logger.warn(
894 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
895 this.stationTemplateFile
896 }, forcing random connector configurations affectation`
897 );
898 this.stationInfo.randomConnectors = true;
899 }
900 const connectorsConfigHash = crypto
901 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
902 .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
903 .digest('hex');
904 const connectorsConfigChanged =
905 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
906 if (this.connectors?.size === 0 || connectorsConfigChanged) {
907 connectorsConfigChanged && this.connectors.clear();
908 this.connectorsConfigurationHash = connectorsConfigHash;
909 // Add connector Id 0
910 let lastConnector = '0';
911 for (lastConnector in this.stationInfo.Connectors) {
912 const lastConnectorId = Utils.convertToInt(lastConnector);
913 if (
914 lastConnectorId === 0 &&
915 this.getUseConnectorId0() &&
916 this.stationInfo.Connectors[lastConnector]
917 ) {
918 this.connectors.set(
919 lastConnectorId,
920 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])
921 );
922 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
923 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
924 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
925 }
926 }
927 }
928 // Generate all connectors
929 if (
930 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
931 ) {
932 for (let index = 1; index <= maxConnectors; index++) {
933 const randConnectorId = this.stationInfo.randomConnectors
934 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
935 : index;
936 this.connectors.set(
937 index,
938 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])
939 );
940 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
941 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
942 this.getConnectorStatus(index).chargingProfiles = [];
943 }
944 }
945 }
946 }
947 // Avoid duplication of connectors related information
948 delete this.stationInfo.Connectors;
949 // Initialize transaction attributes on connectors
950 for (const connectorId of this.connectors.keys()) {
951 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
952 this.initializeConnectorStatus(connectorId);
953 }
954 }
955 this.wsConfiguredConnectionUrl = new URL(
956 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
957 );
958 // OCPP parameters
959 this.initOcppParameters();
960 switch (this.getOcppVersion()) {
961 case OCPPVersion.VERSION_16:
962 this.ocppIncomingRequestService =
963 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
964 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
965 this,
966 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
967 );
968 break;
969 default:
970 this.handleUnsupportedVersion(this.getOcppVersion());
971 break;
972 }
973 if (this.stationInfo.autoRegister) {
974 this.bootNotificationResponse = {
975 currentTime: new Date().toISOString(),
976 interval: this.getHeartbeatInterval() / 1000,
977 status: RegistrationStatus.ACCEPTED,
978 };
979 }
980 this.stationInfo.powerDivider = this.getPowerDivider();
981 if (this.getEnableStatistics()) {
982 this.performanceStatistics = PerformanceStatistics.getInstance(
983 this.hashId,
984 this.stationInfo.chargingStationId,
985 this.wsConnectionUrl
986 );
987 }
988 }
989
990 private initOcppParameters(): void {
991 if (
992 this.getSupervisionUrlOcppConfiguration() &&
993 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
994 ) {
995 this.addConfigurationKey(
996 this.getSupervisionUrlOcppKey(),
997 this.getConfiguredSupervisionUrl().href,
998 { reboot: true }
999 );
1000 } else if (
1001 !this.getSupervisionUrlOcppConfiguration() &&
1002 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1003 ) {
1004 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
1005 }
1006 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
1007 this.addConfigurationKey(
1008 StandardParametersKey.SupportedFeatureProfiles,
1009 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
1010 );
1011 }
1012 this.addConfigurationKey(
1013 StandardParametersKey.NumberOfConnectors,
1014 this.getNumberOfConnectors().toString(),
1015 { readonly: true },
1016 { overwrite: true }
1017 );
1018 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
1019 this.addConfigurationKey(
1020 StandardParametersKey.MeterValuesSampledData,
1021 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1022 );
1023 }
1024 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
1025 const connectorPhaseRotation = [];
1026 for (const connectorId of this.connectors.keys()) {
1027 // AC/DC
1028 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1029 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1030 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1031 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1032 // AC
1033 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1034 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1035 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1036 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1037 }
1038 }
1039 this.addConfigurationKey(
1040 StandardParametersKey.ConnectorPhaseRotation,
1041 connectorPhaseRotation.toString()
1042 );
1043 }
1044 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
1045 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
1046 }
1047 if (
1048 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
1049 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(
1050 SupportedFeatureProfiles.Local_Auth_List_Management
1051 )
1052 ) {
1053 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
1054 }
1055 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1056 this.addConfigurationKey(
1057 StandardParametersKey.ConnectionTimeOut,
1058 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1059 );
1060 }
1061 this.saveConfiguration();
1062 }
1063
1064 private getConfigurationFromTemplate(): ChargingStationConfiguration {
1065 return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration);
1066 }
1067
1068 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1069 let configuration: ChargingStationConfiguration = null;
1070 if (
1071 this.getOcppPersistentConfiguration() &&
1072 this.configurationFile &&
1073 fs.existsSync(this.configurationFile)
1074 ) {
1075 try {
1076 configuration = JSON.parse(
1077 fs.readFileSync(this.configurationFile, 'utf8')
1078 ) as ChargingStationConfiguration;
1079 } catch (error) {
1080 FileUtils.handleFileException(
1081 this.logPrefix(),
1082 FileType.ChargingStationConfiguration,
1083 this.configurationFile,
1084 error as NodeJS.ErrnoException
1085 );
1086 }
1087 }
1088 return configuration;
1089 }
1090
1091 private saveConfiguration(): void {
1092 if (this.getOcppPersistentConfiguration()) {
1093 if (this.configurationFile) {
1094 try {
1095 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1096 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1097 }
1098 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1099 fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2));
1100 fs.closeSync(fileDescriptor);
1101 } catch (error) {
1102 FileUtils.handleFileException(
1103 this.logPrefix(),
1104 FileType.ChargingStationConfiguration,
1105 this.configurationFile,
1106 error as NodeJS.ErrnoException
1107 );
1108 }
1109 } else {
1110 logger.error(
1111 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1112 );
1113 }
1114 }
1115 }
1116
1117 private getConfiguration(): ChargingStationConfiguration {
1118 let configuration: ChargingStationConfiguration = this.getConfigurationFromFile();
1119 if (!configuration) {
1120 configuration = this.getConfigurationFromTemplate();
1121 }
1122 return configuration;
1123 }
1124
1125 private async onOpen(): Promise<void> {
1126 logger.info(
1127 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1128 );
1129 if (!this.isInAcceptedState()) {
1130 // Send BootNotification
1131 let registrationRetryCount = 0;
1132 do {
1133 this.bootNotificationResponse =
1134 await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
1135 RequestCommand.BOOT_NOTIFICATION,
1136 {
1137 chargePointModel: this.bootNotificationRequest.chargePointModel,
1138 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1139 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1140 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1141 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1142 iccid: this.bootNotificationRequest.iccid,
1143 imsi: this.bootNotificationRequest.imsi,
1144 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1145 meterType: this.bootNotificationRequest.meterType,
1146 },
1147 { skipBufferingOnError: true }
1148 );
1149 if (!this.isInAcceptedState()) {
1150 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1151 await Utils.sleep(
1152 this.bootNotificationResponse?.interval
1153 ? this.bootNotificationResponse.interval * 1000
1154 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1155 );
1156 }
1157 } while (
1158 !this.isInAcceptedState() &&
1159 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1160 this.getRegistrationMaxRetries() === -1)
1161 );
1162 }
1163 if (this.isInAcceptedState()) {
1164 await this.startMessageSequence();
1165 this.stopped && (this.stopped = false);
1166 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
1167 this.flushMessageBuffer();
1168 }
1169 } else {
1170 logger.error(
1171 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1172 );
1173 }
1174 this.autoReconnectRetryCount = 0;
1175 this.wsConnectionRestarted = false;
1176 }
1177
1178 private async onClose(code: number, reason: string): Promise<void> {
1179 switch (code) {
1180 // Normal close
1181 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1182 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1183 logger.info(
1184 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1185 code
1186 )}' and reason '${reason}'`
1187 );
1188 this.autoReconnectRetryCount = 0;
1189 break;
1190 // Abnormal close
1191 default:
1192 logger.error(
1193 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1194 code
1195 )}' and reason '${reason}'`
1196 );
1197 await this.reconnect(code);
1198 break;
1199 }
1200 }
1201
1202 private async onMessage(data: Data): Promise<void> {
1203 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [
1204 0,
1205 '',
1206 '' as IncomingRequestCommand,
1207 {},
1208 {},
1209 ];
1210 let responseCallback: (
1211 payload: JsonType | string,
1212 requestPayload: JsonType | OCPPError
1213 ) => void;
1214 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1215 let requestCommandName: RequestCommand | IncomingRequestCommand;
1216 let requestPayload: JsonType | OCPPError;
1217 let cachedRequest: CachedRequest;
1218 let errMsg: string;
1219 try {
1220 const request = JSON.parse(data.toString()) as IncomingRequest;
1221 if (Utils.isIterable(request)) {
1222 // Parse the message
1223 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
1224 } else {
1225 throw new OCPPError(
1226 ErrorType.PROTOCOL_ERROR,
1227 'Incoming request is not iterable',
1228 commandName
1229 );
1230 }
1231 // Check the Type of message
1232 switch (messageType) {
1233 // Incoming Message
1234 case MessageType.CALL_MESSAGE:
1235 if (this.getEnableStatistics()) {
1236 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1237 }
1238 // Process the call
1239 await this.ocppIncomingRequestService.handleRequest(
1240 messageId,
1241 commandName,
1242 commandPayload
1243 );
1244 break;
1245 // Outcome Message
1246 case MessageType.CALL_RESULT_MESSAGE:
1247 // Respond
1248 cachedRequest = this.requests.get(messageId);
1249 if (Utils.isIterable(cachedRequest)) {
1250 [responseCallback, , , requestPayload] = cachedRequest;
1251 } else {
1252 throw new OCPPError(
1253 ErrorType.PROTOCOL_ERROR,
1254 `Cached request for message id ${messageId} response is not iterable`,
1255 commandName
1256 );
1257 }
1258 if (!responseCallback) {
1259 // Error
1260 throw new OCPPError(
1261 ErrorType.INTERNAL_ERROR,
1262 `Response for unknown message id ${messageId}`,
1263 commandName
1264 );
1265 }
1266 responseCallback(commandName, requestPayload);
1267 break;
1268 // Error Message
1269 case MessageType.CALL_ERROR_MESSAGE:
1270 cachedRequest = this.requests.get(messageId);
1271 if (Utils.isIterable(cachedRequest)) {
1272 [, rejectCallback, requestCommandName] = cachedRequest;
1273 } else {
1274 throw new OCPPError(
1275 ErrorType.PROTOCOL_ERROR,
1276 `Cached request for message id ${messageId} error response is not iterable`
1277 );
1278 }
1279 if (!rejectCallback) {
1280 // Error
1281 throw new OCPPError(
1282 ErrorType.INTERNAL_ERROR,
1283 `Error response for unknown message id ${messageId}`,
1284 requestCommandName
1285 );
1286 }
1287 rejectCallback(
1288 new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails)
1289 );
1290 break;
1291 // Error
1292 default:
1293 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1294 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1295 logger.error(errMsg);
1296 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1297 }
1298 } catch (error) {
1299 // Log
1300 logger.error(
1301 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1302 this.logPrefix(),
1303 data.toString(),
1304 this.requests.get(messageId),
1305 error
1306 );
1307 // Send error
1308 messageType === MessageType.CALL_MESSAGE &&
1309 (await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName));
1310 }
1311 }
1312
1313 private onPing(): void {
1314 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1315 }
1316
1317 private onPong(): void {
1318 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1319 }
1320
1321 private onError(error: WSError): void {
1322 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
1323 }
1324
1325 private getAuthorizationFile(): string | undefined {
1326 return (
1327 this.stationInfo.authorizationFile &&
1328 path.join(
1329 path.resolve(__dirname, '../'),
1330 'assets',
1331 path.basename(this.stationInfo.authorizationFile)
1332 )
1333 );
1334 }
1335
1336 private getAuthorizedTags(): string[] {
1337 let authorizedTags: string[] = [];
1338 const authorizationFile = this.getAuthorizationFile();
1339 if (authorizationFile) {
1340 try {
1341 // Load authorization file
1342 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
1343 } catch (error) {
1344 FileUtils.handleFileException(
1345 this.logPrefix(),
1346 FileType.Authorization,
1347 authorizationFile,
1348 error as NodeJS.ErrnoException
1349 );
1350 }
1351 } else {
1352 logger.info(
1353 this.logPrefix() +
1354 ' No authorization file given in template file ' +
1355 this.stationTemplateFile
1356 );
1357 }
1358 return authorizedTags;
1359 }
1360
1361 private getUseConnectorId0(): boolean | undefined {
1362 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1363 ? this.stationInfo.useConnectorId0
1364 : true;
1365 }
1366
1367 private getNumberOfRunningTransactions(): number {
1368 let trxCount = 0;
1369 for (const connectorId of this.connectors.keys()) {
1370 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1371 trxCount++;
1372 }
1373 }
1374 return trxCount;
1375 }
1376
1377 // 0 for disabling
1378 private getConnectionTimeout(): number | undefined {
1379 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1380 return (
1381 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1382 Constants.DEFAULT_CONNECTION_TIMEOUT
1383 );
1384 }
1385 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1386 }
1387
1388 // -1 for unlimited, 0 for disabling
1389 private getAutoReconnectMaxRetries(): number | undefined {
1390 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1391 return this.stationInfo.autoReconnectMaxRetries;
1392 }
1393 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1394 return Configuration.getAutoReconnectMaxRetries();
1395 }
1396 return -1;
1397 }
1398
1399 // 0 for disabling
1400 private getRegistrationMaxRetries(): number | undefined {
1401 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1402 return this.stationInfo.registrationMaxRetries;
1403 }
1404 return -1;
1405 }
1406
1407 private getPowerDivider(): number {
1408 let powerDivider = this.getNumberOfConnectors();
1409 if (this.stationInfo.powerSharedByConnectors) {
1410 powerDivider = this.getNumberOfRunningTransactions();
1411 }
1412 return powerDivider;
1413 }
1414
1415 private getTemplateMaxNumberOfConnectors(): number {
1416 return Object.keys(this.stationInfo.Connectors).length;
1417 }
1418
1419 private getMaxNumberOfConnectors(): number {
1420 let maxConnectors: number;
1421 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1422 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
1423 // Distribute evenly the number of connectors
1424 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1425 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1426 maxConnectors = this.stationInfo.numberOfConnectors as number;
1427 } else {
1428 maxConnectors = this.stationInfo.Connectors[0]
1429 ? this.getTemplateMaxNumberOfConnectors() - 1
1430 : this.getTemplateMaxNumberOfConnectors();
1431 }
1432 return maxConnectors;
1433 }
1434
1435 private async startMessageSequence(): Promise<void> {
1436 if (this.stationInfo.autoRegister) {
1437 await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
1438 RequestCommand.BOOT_NOTIFICATION,
1439 {
1440 chargePointModel: this.bootNotificationRequest.chargePointModel,
1441 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1442 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1443 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1444 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1445 iccid: this.bootNotificationRequest.iccid,
1446 imsi: this.bootNotificationRequest.imsi,
1447 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1448 meterType: this.bootNotificationRequest.meterType,
1449 },
1450 { skipBufferingOnError: true }
1451 );
1452 }
1453 // Start WebSocket ping
1454 this.startWebSocketPing();
1455 // Start heartbeat
1456 this.startHeartbeat();
1457 // Initialize connectors status
1458 for (const connectorId of this.connectors.keys()) {
1459 if (connectorId === 0) {
1460 continue;
1461 } else if (
1462 !this.stopped &&
1463 !this.getConnectorStatus(connectorId)?.status &&
1464 this.getConnectorStatus(connectorId)?.bootStatus
1465 ) {
1466 // Send status in template at startup
1467 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1468 RequestCommand.STATUS_NOTIFICATION,
1469 {
1470 connectorId,
1471 status: this.getConnectorStatus(connectorId).bootStatus,
1472 errorCode: ChargePointErrorCode.NO_ERROR,
1473 }
1474 );
1475 this.getConnectorStatus(connectorId).status =
1476 this.getConnectorStatus(connectorId).bootStatus;
1477 } else if (
1478 this.stopped &&
1479 this.getConnectorStatus(connectorId)?.status &&
1480 this.getConnectorStatus(connectorId)?.bootStatus
1481 ) {
1482 // Send status in template after reset
1483 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1484 RequestCommand.STATUS_NOTIFICATION,
1485 {
1486 connectorId,
1487 status: this.getConnectorStatus(connectorId).bootStatus,
1488 errorCode: ChargePointErrorCode.NO_ERROR,
1489 }
1490 );
1491 this.getConnectorStatus(connectorId).status =
1492 this.getConnectorStatus(connectorId).bootStatus;
1493 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1494 // Send previous status at template reload
1495 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1496 RequestCommand.STATUS_NOTIFICATION,
1497 {
1498 connectorId,
1499 status: this.getConnectorStatus(connectorId).status,
1500 errorCode: ChargePointErrorCode.NO_ERROR,
1501 }
1502 );
1503 } else {
1504 // Send default status
1505 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1506 RequestCommand.STATUS_NOTIFICATION,
1507 {
1508 connectorId,
1509 status: ChargePointStatus.AVAILABLE,
1510 errorCode: ChargePointErrorCode.NO_ERROR,
1511 }
1512 );
1513 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1514 }
1515 }
1516 // Start the ATG
1517 this.startAutomaticTransactionGenerator();
1518 }
1519
1520 private startAutomaticTransactionGenerator() {
1521 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
1522 if (!this.automaticTransactionGenerator) {
1523 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
1524 }
1525 if (!this.automaticTransactionGenerator.started) {
1526 this.automaticTransactionGenerator.start();
1527 }
1528 }
1529 }
1530
1531 private async stopMessageSequence(
1532 reason: StopTransactionReason = StopTransactionReason.NONE
1533 ): Promise<void> {
1534 // Stop WebSocket ping
1535 this.stopWebSocketPing();
1536 // Stop heartbeat
1537 this.stopHeartbeat();
1538 // Stop the ATG
1539 if (
1540 this.stationInfo.AutomaticTransactionGenerator.enable &&
1541 this.automaticTransactionGenerator?.started
1542 ) {
1543 this.automaticTransactionGenerator.stop();
1544 } else {
1545 for (const connectorId of this.connectors.keys()) {
1546 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1547 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1548 if (
1549 this.getBeginEndMeterValues() &&
1550 this.getOcppStrictCompliance() &&
1551 !this.getOutOfOrderEndMeterValues()
1552 ) {
1553 // FIXME: Implement OCPP version agnostic helpers
1554 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1555 this,
1556 connectorId,
1557 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1558 );
1559 await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
1560 RequestCommand.METER_VALUES,
1561 {
1562 connectorId,
1563 transactionId,
1564 meterValue: transactionEndMeterValue,
1565 }
1566 );
1567 }
1568 await this.ocppRequestService.sendMessageHandler<StopTransactionResponse>(
1569 RequestCommand.STOP_TRANSACTION,
1570 {
1571 transactionId,
1572 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1573 idTag: this.getTransactionIdTag(transactionId),
1574 reason,
1575 }
1576 );
1577 }
1578 }
1579 }
1580 }
1581
1582 private startWebSocketPing(): void {
1583 const webSocketPingInterval: number = this.getConfigurationKey(
1584 StandardParametersKey.WebSocketPingInterval
1585 )
1586 ? Utils.convertToInt(
1587 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1588 )
1589 : 0;
1590 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1591 this.webSocketPingSetInterval = setInterval(() => {
1592 if (this.isWebSocketConnectionOpened()) {
1593 this.wsConnection.ping((): void => {
1594 /* This is intentional */
1595 });
1596 }
1597 }, webSocketPingInterval * 1000);
1598 logger.info(
1599 this.logPrefix() +
1600 ' WebSocket ping started every ' +
1601 Utils.formatDurationSeconds(webSocketPingInterval)
1602 );
1603 } else if (this.webSocketPingSetInterval) {
1604 logger.info(
1605 this.logPrefix() +
1606 ' WebSocket ping every ' +
1607 Utils.formatDurationSeconds(webSocketPingInterval) +
1608 ' already started'
1609 );
1610 } else {
1611 logger.error(
1612 `${this.logPrefix()} WebSocket ping interval set to ${
1613 webSocketPingInterval
1614 ? Utils.formatDurationSeconds(webSocketPingInterval)
1615 : webSocketPingInterval
1616 }, not starting the WebSocket ping`
1617 );
1618 }
1619 }
1620
1621 private stopWebSocketPing(): void {
1622 if (this.webSocketPingSetInterval) {
1623 clearInterval(this.webSocketPingSetInterval);
1624 }
1625 }
1626
1627 private warnDeprecatedTemplateKey(
1628 template: ChargingStationTemplate,
1629 key: string,
1630 chargingStationId: string,
1631 logMsgToAppend = ''
1632 ): void {
1633 if (!Utils.isUndefined(template[key])) {
1634 const logPrefixStr = ` ${chargingStationId} |`;
1635 logger.warn(
1636 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1637 this.stationTemplateFile
1638 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1639 );
1640 }
1641 }
1642
1643 private convertDeprecatedTemplateKey(
1644 template: ChargingStationTemplate,
1645 deprecatedKey: string,
1646 key: string
1647 ): void {
1648 if (!Utils.isUndefined(template[deprecatedKey])) {
1649 template[key] = template[deprecatedKey] as unknown;
1650 delete template[deprecatedKey];
1651 }
1652 }
1653
1654 private getConfiguredSupervisionUrl(): URL {
1655 const supervisionUrls = Utils.cloneObject<string | string[]>(
1656 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1657 );
1658 if (!Utils.isEmptyArray(supervisionUrls)) {
1659 let urlIndex = 0;
1660 switch (Configuration.getSupervisionUrlDistribution()) {
1661 case SupervisionUrlDistribution.ROUND_ROBIN:
1662 urlIndex = (this.index - 1) % supervisionUrls.length;
1663 break;
1664 case SupervisionUrlDistribution.RANDOM:
1665 // Get a random url
1666 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1667 break;
1668 case SupervisionUrlDistribution.SEQUENTIAL:
1669 if (this.index <= supervisionUrls.length) {
1670 urlIndex = this.index - 1;
1671 } else {
1672 logger.warn(
1673 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1674 );
1675 }
1676 break;
1677 default:
1678 logger.error(
1679 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1680 SupervisionUrlDistribution.ROUND_ROBIN
1681 }`
1682 );
1683 urlIndex = (this.index - 1) % supervisionUrls.length;
1684 break;
1685 }
1686 return new URL(supervisionUrls[urlIndex]);
1687 }
1688 return new URL(supervisionUrls as string);
1689 }
1690
1691 private getHeartbeatInterval(): number | undefined {
1692 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1693 if (HeartbeatInterval) {
1694 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1695 }
1696 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1697 if (HeartBeatInterval) {
1698 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1699 }
1700 !this.stationInfo.autoRegister &&
1701 logger.warn(
1702 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1703 Constants.DEFAULT_HEARTBEAT_INTERVAL
1704 }`
1705 );
1706 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1707 }
1708
1709 private stopHeartbeat(): void {
1710 if (this.heartbeatSetInterval) {
1711 clearInterval(this.heartbeatSetInterval);
1712 }
1713 }
1714
1715 private openWSConnection(
1716 options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions,
1717 forceCloseOpened = false
1718 ): void {
1719 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1720 if (
1721 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
1722 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
1723 ) {
1724 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1725 }
1726 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1727 this.wsConnection.close();
1728 }
1729 let protocol: string;
1730 switch (this.getOcppVersion()) {
1731 case OCPPVersion.VERSION_16:
1732 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1733 break;
1734 default:
1735 this.handleUnsupportedVersion(this.getOcppVersion());
1736 break;
1737 }
1738 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1739 logger.info(
1740 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
1741 );
1742 }
1743
1744 private stopMeterValues(connectorId: number) {
1745 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1746 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1747 }
1748 }
1749
1750 private getReconnectExponentialDelay(): boolean | undefined {
1751 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1752 ? this.stationInfo.reconnectExponentialDelay
1753 : false;
1754 }
1755
1756 private async reconnect(code: number): Promise<void> {
1757 // Stop WebSocket ping
1758 this.stopWebSocketPing();
1759 // Stop heartbeat
1760 this.stopHeartbeat();
1761 // Stop the ATG if needed
1762 if (
1763 this.stationInfo.AutomaticTransactionGenerator.enable &&
1764 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1765 this.automaticTransactionGenerator?.started
1766 ) {
1767 this.automaticTransactionGenerator.stop();
1768 }
1769 if (
1770 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1771 this.getAutoReconnectMaxRetries() === -1
1772 ) {
1773 this.autoReconnectRetryCount++;
1774 const reconnectDelay = this.getReconnectExponentialDelay()
1775 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1776 : this.getConnectionTimeout() * 1000;
1777 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
1778 logger.error(
1779 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1780 reconnectDelay,
1781 2
1782 )}ms, timeout ${reconnectTimeout}ms`
1783 );
1784 await Utils.sleep(reconnectDelay);
1785 logger.error(
1786 this.logPrefix() +
1787 ' WebSocket: reconnecting try #' +
1788 this.autoReconnectRetryCount.toString()
1789 );
1790 this.openWSConnection(
1791 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
1792 true
1793 );
1794 this.wsConnectionRestarted = true;
1795 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1796 logger.error(
1797 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1798 this.autoReconnectRetryCount
1799 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1800 );
1801 }
1802 }
1803
1804 private initializeConnectorStatus(connectorId: number): void {
1805 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1806 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1807 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1808 this.getConnectorStatus(connectorId).transactionStarted = false;
1809 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1810 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
1811 }
1812 }