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