1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
5 BootNotificationRequest
,
8 IncomingRequestCommand
,
10 } from
'../types/ocpp/Requests';
12 BootNotificationResponse
,
16 StatusNotificationResponse
,
17 } from
'../types/ocpp/Responses';
18 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
19 import ChargingStationOcppConfiguration
, {
21 } from
'../types/ChargingStationOcppConfiguration';
22 import ChargingStationTemplate
, {
27 } from
'../types/ChargingStationTemplate';
29 ConnectorPhaseRotation
,
30 StandardParametersKey
,
31 SupportedFeatureProfiles
,
32 VendorDefaultParametersKey
,
33 } from
'../types/ocpp/Configuration';
34 import { MeterValue
, MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
35 import { StopTransactionReason
, StopTransactionResponse
} from
'../types/ocpp/Transaction';
36 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
37 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
39 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
40 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
41 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
42 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
43 import ChargingStationInfo from
'../types/ChargingStationInfo';
44 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
45 import Configuration from
'../utils/Configuration';
46 import { ConnectorStatus
} from
'../types/ConnectorStatus';
47 import Constants from
'../utils/Constants';
48 import { ErrorType
} from
'../types/ocpp/ErrorType';
49 import { FileType
} from
'../types/FileType';
50 import FileUtils from
'../utils/FileUtils';
51 import { JsonType
} from
'../types/JsonType';
52 import { MessageType
} from
'../types/ocpp/MessageType';
53 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
54 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
55 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
56 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
57 import OCPPError from
'../exception/OCPPError';
58 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
59 import OCPPRequestService from
'./ocpp/OCPPRequestService';
60 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
61 import PerformanceStatistics from
'../performance/PerformanceStatistics';
62 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
63 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
64 import { URL
} from
'url';
65 import Utils from
'../utils/Utils';
66 import crypto from
'crypto';
68 import logger from
'../utils/Logger';
69 import { parentPort
} from
'worker_threads';
70 import path from
'path';
72 export default class ChargingStation
{
73 public hashId
!: string;
74 public readonly templateFile
: string;
75 public authorizedTags
: string[];
76 public stationInfo
!: ChargingStationInfo
;
77 public readonly connectors
: Map
<number, ConnectorStatus
>;
78 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
79 public wsConnection
!: WebSocket
;
80 public readonly requests
: Map
<string, CachedRequest
>;
81 public performanceStatistics
!: PerformanceStatistics
;
82 public heartbeatSetInterval
!: NodeJS
.Timeout
;
83 public ocppRequestService
!: OCPPRequestService
;
84 public bootNotificationResponse
!: BootNotificationResponse
| null;
85 private readonly index
: number;
86 private configurationFile
!: string;
87 private bootNotificationRequest
!: BootNotificationRequest
;
88 private connectorsConfigurationHash
!: string;
89 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
90 private readonly messageBuffer
: Set
<string>;
91 private wsConfiguredConnectionUrl
!: URL
;
92 private wsConnectionRestarted
: boolean;
93 private stopped
: boolean;
94 private autoReconnectRetryCount
: number;
95 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
96 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
98 constructor(index
: number, templateFile
: string) {
100 this.templateFile
= templateFile
;
101 this.stopped
= false;
102 this.wsConnectionRestarted
= false;
103 this.autoReconnectRetryCount
= 0;
104 this.connectors
= new Map
<number, ConnectorStatus
>();
105 this.requests
= new Map
<string, CachedRequest
>();
106 this.messageBuffer
= new Set
<string>();
108 this.authorizedTags
= this.getAuthorizedTags();
111 private get
wsConnectionUrl(): URL
{
112 return this.getSupervisionUrlOcppConfiguration()
114 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value
+
116 this.stationInfo
.chargingStationId
118 : this.wsConfiguredConnectionUrl
;
121 public logPrefix(): string {
122 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
125 public getBootNotificationRequest(): BootNotificationRequest
{
126 return this.bootNotificationRequest
;
129 public getRandomIdTag(): string {
130 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
131 return this.authorizedTags
[index
];
134 public hasAuthorizedTags(): boolean {
135 return !Utils
.isEmptyArray(this.authorizedTags
);
138 public getEnableStatistics(): boolean | undefined {
139 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
140 ? this.stationInfo
.enableStatistics
144 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
145 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
148 public getNumberOfPhases(): number | undefined {
149 switch (this.getCurrentOutType()) {
151 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
152 ? this.stationInfo
.numberOfPhases
159 public isWebSocketConnectionOpened(): boolean {
160 return this?.wsConnection
?.readyState
=== OPEN
;
163 public getRegistrationStatus(): RegistrationStatus
{
164 return this?.bootNotificationResponse
?.status;
167 public isInUnknownState(): boolean {
168 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
171 public isInPendingState(): boolean {
172 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
175 public isInAcceptedState(): boolean {
176 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
179 public isInRejectedState(): boolean {
180 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
183 public isRegistered(): boolean {
184 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
187 public isChargingStationAvailable(): boolean {
188 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
191 public isConnectorAvailable(id
: number): boolean {
192 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
195 public getNumberOfConnectors(): number {
196 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
199 public getConnectorStatus(id
: number): ConnectorStatus
{
200 return this.connectors
.get(id
);
203 public getCurrentOutType(): CurrentType
| undefined {
204 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
207 public getOcppStrictCompliance(): boolean {
208 return this.stationInfo
.ocppStrictCompliance
?? false;
211 public getVoltageOut(): number | undefined {
212 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
214 }, cannot define default voltage out`;
215 let defaultVoltageOut
: number;
216 switch (this.getCurrentOutType()) {
218 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
221 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
224 logger
.error(errMsg
);
225 throw new Error(errMsg
);
227 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
228 ? this.stationInfo
.voltageOut
232 public getTransactionIdTag(transactionId
: number): string | undefined {
233 for (const connectorId
of this.connectors
.keys()) {
234 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
235 return this.getConnectorStatus(connectorId
).transactionIdTag
;
240 public getOutOfOrderEndMeterValues(): boolean {
241 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
244 public getBeginEndMeterValues(): boolean {
245 return this.stationInfo
.beginEndMeterValues
?? false;
248 public getMeteringPerTransaction(): boolean {
249 return this.stationInfo
.meteringPerTransaction
?? true;
252 public getTransactionDataMeterValues(): boolean {
253 return this.stationInfo
.transactionDataMeterValues
?? false;
256 public getMainVoltageMeterValues(): boolean {
257 return this.stationInfo
.mainVoltageMeterValues
?? true;
260 public getPhaseLineToLineVoltageMeterValues(): boolean {
261 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
264 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
265 for (const connectorId
of this.connectors
.keys()) {
268 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
275 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
276 const transactionConnectorStatus
= this.getConnectorStatus(
277 this.getConnectorIdByTransactionId(transactionId
)
279 if (this.getMeteringPerTransaction()) {
280 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
282 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
285 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
286 const connectorStatus
= this.getConnectorStatus(connectorId
);
287 if (this.getMeteringPerTransaction()) {
288 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
290 return connectorStatus
?.energyActiveImportRegisterValue
;
293 public getAuthorizeRemoteTxRequests(): boolean {
294 const authorizeRemoteTxRequests
= this.getConfigurationKey(
295 StandardParametersKey
.AuthorizeRemoteTxRequests
297 return authorizeRemoteTxRequests
298 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
302 public getLocalAuthListEnabled(): boolean {
303 const localAuthListEnabled
= this.getConfigurationKey(
304 StandardParametersKey
.LocalAuthListEnabled
306 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
309 public restartWebSocketPing(): void {
310 // Stop WebSocket ping
311 this.stopWebSocketPing();
312 // Start WebSocket ping
313 this.startWebSocketPing();
316 public getSampledValueTemplate(
318 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
319 phase
?: MeterValuePhase
320 ): SampledValueTemplate
| undefined {
321 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
322 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
324 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
329 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
330 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
335 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
336 StandardParametersKey.MeterValuesSampledData
341 const sampledValueTemplates
: SampledValueTemplate
[] =
342 this.getConnectorStatus(connectorId
).MeterValues
;
345 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
349 !Constants
.SUPPORTED_MEASURANDS
.includes(
350 sampledValueTemplates
[index
]?.measurand
??
351 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
355 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
359 sampledValueTemplates
[index
]?.phase
=== phase
&&
360 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
361 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
365 return sampledValueTemplates
[index
];
368 !sampledValueTemplates
[index
].phase
&&
369 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
370 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
374 return sampledValueTemplates
[index
];
376 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
377 (!sampledValueTemplates
[index
].measurand
||
378 sampledValueTemplates
[index
].measurand
=== measurand
)
380 return sampledValueTemplates
[index
];
383 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
384 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
385 logger
.error(errorMsg
);
386 throw new Error(errorMsg
);
389 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
393 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
394 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
397 public startHeartbeat(): void {
399 this.getHeartbeatInterval() &&
400 this.getHeartbeatInterval() > 0 &&
401 !this.heartbeatSetInterval
403 // eslint-disable-next-line @typescript-eslint/no-misused-promises
404 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
405 await this.ocppRequestService
.sendMessageHandler
<HeartbeatResponse
>(
406 RequestCommand
.HEARTBEAT
408 }, this.getHeartbeatInterval());
411 ' Heartbeat started every ' +
412 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
414 } else if (this.heartbeatSetInterval
) {
417 ' Heartbeat already started every ' +
418 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
422 `${this.logPrefix()} Heartbeat interval set to ${
423 this.getHeartbeatInterval()
424 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
425 : this.getHeartbeatInterval()
426 }, not starting the heartbeat`
431 public restartHeartbeat(): void {
433 this.stopHeartbeat();
435 this.startHeartbeat();
438 public startMeterValues(connectorId
: number, interval
: number): void {
439 if (connectorId
=== 0) {
441 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
445 if (!this.getConnectorStatus(connectorId
)) {
447 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
451 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
453 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
457 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
458 !this.getConnectorStatus(connectorId
)?.transactionId
461 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
466 // eslint-disable-next-line @typescript-eslint/no-misused-promises
467 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
468 // eslint-disable-next-line @typescript-eslint/no-misused-promises
469 async (): Promise
<void> => {
470 // FIXME: Implement OCPP version agnostic helpers
471 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
474 this.getConnectorStatus(connectorId
).transactionId
,
477 await this.ocppRequestService
.sendMessageHandler
<MeterValuesResponse
>(
478 RequestCommand
.METER_VALUES
,
481 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
482 meterValue
: [meterValue
],
490 `${this.logPrefix()} Charging station ${
491 StandardParametersKey.MeterValueSampleInterval
492 } configuration set to ${
493 interval ? Utils.formatDurationMilliSeconds(interval) : interval
494 }, not sending MeterValues`
499 public start(): void {
500 if (this.getEnableStatistics()) {
501 this.performanceStatistics
.start();
503 this.openWSConnection();
504 // Monitor authorization file
505 FileUtils
.watchJsonFile
<string[]>(
507 FileType
.Authorization
,
508 this.getAuthorizationFile(),
511 // Monitor charging station template file
512 FileUtils
.watchJsonFile(
514 FileType
.ChargingStationTemplate
,
517 (event
, filename
): void => {
518 if (filename
&& event
=== 'change') {
521 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
523 } file have changed, reload`
529 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
530 this.automaticTransactionGenerator
532 this.automaticTransactionGenerator
.stop();
534 this.startAutomaticTransactionGenerator();
535 if (this.getEnableStatistics()) {
536 this.performanceStatistics
.restart();
538 this.performanceStatistics
.stop();
540 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
543 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
550 // Handle WebSocket message
551 this.wsConnection
.on(
553 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
555 // Handle WebSocket error
556 this.wsConnection
.on(
558 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
560 // Handle WebSocket close
561 this.wsConnection
.on(
563 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
565 // Handle WebSocket open
566 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
567 // Handle WebSocket ping
568 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
569 // Handle WebSocket pong
570 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
571 parentPort
.postMessage({
572 id
: ChargingStationWorkerMessageEvents
.STARTED
,
573 data
: { id
: this.stationInfo
.chargingStationId
},
577 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
578 // Stop message sequence
579 await this.stopMessageSequence(reason
);
580 for (const connectorId
of this.connectors
.keys()) {
581 if (connectorId
> 0) {
582 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
583 RequestCommand
.STATUS_NOTIFICATION
,
586 status: ChargePointStatus
.UNAVAILABLE
,
587 errorCode
: ChargePointErrorCode
.NO_ERROR
,
590 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
593 if (this.isWebSocketConnectionOpened()) {
594 this.wsConnection
.close();
596 if (this.getEnableStatistics()) {
597 this.performanceStatistics
.stop();
599 this.bootNotificationResponse
= null;
600 parentPort
.postMessage({
601 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
602 data
: { id
: this.stationInfo
.chargingStationId
},
607 public getConfigurationKey(
608 key
: string | StandardParametersKey
,
609 caseInsensitive
= false
610 ): ConfigurationKey
| undefined {
611 return this.ocppConfiguration
.configurationKey
.find((configElement
) => {
612 if (caseInsensitive
) {
613 return configElement
.key
.toLowerCase() === key
.toLowerCase();
615 return configElement
.key
=== key
;
619 public addConfigurationKey(
620 key
: string | StandardParametersKey
,
622 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
627 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
629 options
= options
?? ({} as { readonly?: boolean; visible
?: boolean; reboot
?: boolean });
630 options
.readonly = options
?.readonly ?? false;
631 options
.visible
= options
?.visible
?? true;
632 options
.reboot
= options
?.reboot
?? false;
633 let keyFound
= this.getConfigurationKey(key
);
634 if (keyFound
&& params
?.overwrite
) {
635 this.deleteConfigurationKey(keyFound
.key
, { save
: false });
636 keyFound
= undefined;
639 this.ocppConfiguration
.configurationKey
.push({
641 readonly: options
.readonly,
643 visible
: options
.visible
,
644 reboot
: options
.reboot
,
646 params
?.save
&& this.saveOcppConfiguration();
649 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
655 public setConfigurationKeyValue(
656 key
: string | StandardParametersKey
,
658 caseInsensitive
= false
660 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
662 this.ocppConfiguration
.configurationKey
[
663 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
)
665 this.saveOcppConfiguration();
668 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
674 public deleteConfigurationKey(
675 key
: string | StandardParametersKey
,
676 params
: { save
?: boolean; caseInsensitive
?: boolean } = { save
: true, caseInsensitive
: false }
677 ): ConfigurationKey
[] {
678 const keyFound
= this.getConfigurationKey(key
, params
?.caseInsensitive
);
680 const deletedConfigurationKey
= this.ocppConfiguration
.configurationKey
.splice(
681 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
),
684 params
?.save
&& this.saveOcppConfiguration();
685 return deletedConfigurationKey
;
689 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
690 let cpReplaced
= false;
691 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
692 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
693 (chargingProfile
: ChargingProfile
, index
: number) => {
695 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
696 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
697 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
699 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
705 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
708 public resetConnectorStatus(connectorId
: number): void {
709 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
710 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
711 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
712 this.getConnectorStatus(connectorId
).transactionStarted
= false;
713 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
714 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
715 delete this.getConnectorStatus(connectorId
).transactionId
;
716 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
717 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
718 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
719 this.stopMeterValues(connectorId
);
722 public bufferMessage(message
: string): void {
723 this.messageBuffer
.add(message
);
726 private flushMessageBuffer() {
727 if (this.messageBuffer
.size
> 0) {
728 this.messageBuffer
.forEach((message
) => {
729 // TODO: evaluate the need to track performance
730 this.wsConnection
.send(message
);
731 this.messageBuffer
.delete(message
);
736 private getSupervisionUrlOcppConfiguration(): boolean {
737 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
740 private getSupervisionUrlOcppKey(): string {
741 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
744 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
745 // In case of multiple instances: add instance index to charging station id
746 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
747 const idSuffix
= stationTemplate
.nameSuffix
?? '';
748 const idStr
= '000000000' + this.index
.toString();
749 return stationTemplate
.fixedName
750 ? stationTemplate
.baseName
751 : stationTemplate
.baseName
+
753 instanceIndex
.toString() +
754 idStr
.substring(idStr
.length
- 4) +
758 private getRandomSerialNumberSuffix(params
?: {
759 randomBytesLength
?: number;
762 const randomSerialNumberSuffix
= crypto
763 .randomBytes(params
?.randomBytesLength
?? 16)
765 if (params
?.upperCase
) {
766 return randomSerialNumberSuffix
.toUpperCase();
768 return randomSerialNumberSuffix
;
771 private getTemplateFromFile(): ChargingStationTemplate
| null {
772 let template
: ChargingStationTemplate
= null;
774 const measureId
= `${FileType.ChargingStationTemplate} read`;
775 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
776 template
= JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
777 PerformanceStatistics
.endMeasure(measureId
, beginId
);
779 FileUtils
.handleFileException(
781 FileType
.ChargingStationTemplate
,
783 error
as NodeJS
.ErrnoException
789 private createSerialNumber(
790 stationInfo
: ChargingStationInfo
,
791 existingStationInfo
?: ChargingStationInfo
,
792 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
793 randomSerialNumberUpperCase
: true,
794 randomSerialNumber
: true,
797 params
= params
?? {};
798 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
799 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
800 if (existingStationInfo
) {
801 existingStationInfo
?.chargePointSerialNumber
&&
802 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
803 existingStationInfo
?.chargeBoxSerialNumber
&&
804 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
806 const serialNumberSuffix
= params
?.randomSerialNumber
807 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
809 stationInfo
.chargePointSerialNumber
=
810 stationInfo
?.chargePointSerialNumberPrefix
&&
811 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
812 stationInfo
.chargeBoxSerialNumber
=
813 stationInfo
?.chargeBoxSerialNumberPrefix
&&
814 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
818 private getStationInfoFromTemplate(): ChargingStationInfo
{
819 const stationInfo
: ChargingStationInfo
=
820 this.getTemplateFromFile() ?? ({} as ChargingStationInfo
);
821 stationInfo
.hash
= crypto
822 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
823 .update(JSON
.stringify(stationInfo
))
825 const chargingStationId
= this.getChargingStationId(stationInfo
);
826 // Deprecation template keys section
827 this.warnDeprecatedTemplateKey(
831 "Use 'supervisionUrls' instead"
833 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
834 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
835 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
836 stationInfo
.power
= stationInfo
.power
as number[];
837 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
838 stationInfo
.maxPower
=
839 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
840 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
841 : stationInfo
.power
[powerArrayRandomIndex
];
843 stationInfo
.power
= stationInfo
.power
as number;
844 stationInfo
.maxPower
=
845 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
846 ? stationInfo
.power
* 1000
849 delete stationInfo
.power
;
850 delete stationInfo
.powerUnit
;
851 stationInfo
.chargingStationId
= chargingStationId
;
852 stationInfo
.resetTime
= stationInfo
.resetTime
853 ? stationInfo
.resetTime
* 1000
854 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
858 private getStationInfoFromFile(): ChargingStationInfo
| null {
859 return this.getConfigurationFromFile()?.stationInfo
?? null;
862 private getStationInfo(): ChargingStationInfo
{
863 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
864 this.hashId
= this.getHashId(stationInfoFromTemplate
);
865 this.configurationFile
= path
.join(
866 path
.resolve(__dirname
, '../'),
869 this.hashId
+ '.json'
871 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
872 if (stationInfoFromFile
?.hash
=== stationInfoFromTemplate
.hash
) {
873 return stationInfoFromFile
;
875 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
876 return stationInfoFromTemplate
;
879 private saveStationInfo(): void {
880 this.saveConfiguration(Section
.stationInfo
);
883 private getOcppVersion(): OCPPVersion
{
884 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
887 private getOcppPersistentConfiguration(): boolean {
888 return this.stationInfo
.ocppPersistentConfiguration
?? true;
891 private handleUnsupportedVersion(version
: OCPPVersion
) {
892 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
895 logger
.error(errMsg
);
896 throw new Error(errMsg
);
899 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
901 chargePointModel
: stationInfo
.chargePointModel
,
902 chargePointVendor
: stationInfo
.chargePointVendor
,
903 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
904 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
906 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
907 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
909 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
910 firmwareVersion
: stationInfo
.firmwareVersion
,
912 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
913 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
914 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
915 meterSerialNumber
: stationInfo
.meterSerialNumber
,
917 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
918 meterType
: stationInfo
.meterType
,
923 private getHashId(stationInfo
: ChargingStationInfo
): string {
924 const hashBootNotificationRequest
= {
925 chargePointModel
: stationInfo
.chargePointModel
,
926 chargePointVendor
: stationInfo
.chargePointVendor
,
927 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
928 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
930 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
931 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
933 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
934 firmwareVersion
: stationInfo
.firmwareVersion
,
936 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
937 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
938 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
939 meterSerialNumber
: stationInfo
.meterSerialNumber
,
941 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
942 meterType
: stationInfo
.meterType
,
946 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
947 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
951 private initialize(): void {
952 this.stationInfo
= this.getStationInfo();
953 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
954 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
955 this.ocppConfiguration
= this.getOcppConfiguration();
956 delete this.stationInfo
.Configuration
;
957 this.saveStationInfo();
958 // Build connectors if needed
959 const maxConnectors
= this.getMaxNumberOfConnectors();
960 if (maxConnectors
<= 0) {
962 `${this.logPrefix()} Charging station template ${
964 } with ${maxConnectors} connectors`
967 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
968 if (templateMaxConnectors
<= 0) {
970 `${this.logPrefix()} Charging station template ${
972 } with no connector configuration`
975 if (!this.stationInfo
.Connectors
[0]) {
977 `${this.logPrefix()} Charging station template ${
979 } with no connector Id 0 configuration`
985 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
986 !this.stationInfo
.randomConnectors
989 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
991 }, forcing random connector configurations affectation`
993 this.stationInfo
.randomConnectors
= true;
995 const connectorsConfigHash
= crypto
996 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
997 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
999 const connectorsConfigChanged
=
1000 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1001 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1002 connectorsConfigChanged
&& this.connectors
.clear();
1003 this.connectorsConfigurationHash
= connectorsConfigHash
;
1004 // Add connector Id 0
1005 let lastConnector
= '0';
1006 for (lastConnector
in this.stationInfo
.Connectors
) {
1007 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1009 lastConnectorId
=== 0 &&
1010 this.getUseConnectorId0() &&
1011 this.stationInfo
.Connectors
[lastConnector
]
1013 this.connectors
.set(
1015 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
1017 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1018 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1019 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1023 // Generate all connectors
1025 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
1027 for (let index
= 1; index
<= maxConnectors
; index
++) {
1028 const randConnectorId
= this.stationInfo
.randomConnectors
1029 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1031 this.connectors
.set(
1033 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
1035 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1036 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1037 this.getConnectorStatus(index
).chargingProfiles
= [];
1042 // Avoid duplication of connectors related information in RAM
1043 delete this.stationInfo
.Connectors
;
1044 // Initialize transaction attributes on connectors
1045 for (const connectorId
of this.connectors
.keys()) {
1046 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1047 this.initializeConnectorStatus(connectorId
);
1050 this.wsConfiguredConnectionUrl
= new URL(
1051 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1053 // OCPP configuration
1054 this.initializeOcppConfiguration();
1055 switch (this.getOcppVersion()) {
1056 case OCPPVersion
.VERSION_16
:
1057 this.ocppIncomingRequestService
=
1058 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
1059 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1061 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
1065 this.handleUnsupportedVersion(this.getOcppVersion());
1068 if (this.stationInfo
.autoRegister
) {
1069 this.bootNotificationResponse
= {
1070 currentTime
: new Date().toISOString(),
1071 interval
: this.getHeartbeatInterval() / 1000,
1072 status: RegistrationStatus
.ACCEPTED
,
1075 this.stationInfo
.powerDivider
= this.getPowerDivider();
1076 if (this.getEnableStatistics()) {
1077 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1079 this.stationInfo
.chargingStationId
,
1080 this.wsConnectionUrl
1085 private initializeOcppConfiguration(): void {
1087 this.getSupervisionUrlOcppConfiguration() &&
1088 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1090 this.addConfigurationKey(
1091 this.getSupervisionUrlOcppKey(),
1092 this.getConfiguredSupervisionUrl().href
,
1096 !this.getSupervisionUrlOcppConfiguration() &&
1097 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1099 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1101 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1102 this.addConfigurationKey(
1103 StandardParametersKey
.SupportedFeatureProfiles
,
1104 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
1107 this.addConfigurationKey(
1108 StandardParametersKey
.NumberOfConnectors
,
1109 this.getNumberOfConnectors().toString(),
1113 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1114 this.addConfigurationKey(
1115 StandardParametersKey
.MeterValuesSampledData
,
1116 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1119 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1120 const connectorPhaseRotation
= [];
1121 for (const connectorId
of this.connectors
.keys()) {
1123 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1124 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1125 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1126 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1128 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1129 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1130 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1131 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1134 this.addConfigurationKey(
1135 StandardParametersKey
.ConnectorPhaseRotation
,
1136 connectorPhaseRotation
.toString()
1139 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1140 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1143 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1144 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(
1145 SupportedFeatureProfiles
.Local_Auth_List_Management
1148 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1150 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1151 this.addConfigurationKey(
1152 StandardParametersKey
.ConnectionTimeOut
,
1153 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1156 this.saveOcppConfiguration();
1159 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1160 let configuration
: ChargingStationConfiguration
= null;
1161 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1163 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1164 const beginId
= PerformanceStatistics
.beginMeasure(
1165 `${FileType.ChargingStationConfiguration} read`
1167 configuration
= JSON
.parse(
1168 fs
.readFileSync(this.configurationFile
, 'utf8')
1169 ) as ChargingStationConfiguration
;
1170 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1172 FileUtils
.handleFileException(
1174 FileType
.ChargingStationConfiguration
,
1175 this.configurationFile
,
1176 error
as NodeJS
.ErrnoException
1180 return configuration
;
1183 private saveConfiguration(section
?: Section
): void {
1184 if (this.configurationFile
) {
1186 const configurationData
: ChargingStationConfiguration
=
1187 this.getConfigurationFromFile() ?? {};
1188 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1189 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1192 case Section
.ocppConfiguration
:
1193 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1195 case Section
.stationInfo
:
1196 configurationData
.stationInfo
= this.stationInfo
;
1199 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1200 configurationData
.stationInfo
= this.stationInfo
;
1203 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1204 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1205 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1206 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1207 fs
.closeSync(fileDescriptor
);
1208 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1210 FileUtils
.handleFileException(
1212 FileType
.ChargingStationConfiguration
,
1213 this.configurationFile
,
1214 error
as NodeJS
.ErrnoException
1219 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1224 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1225 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1228 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1229 let configuration
: ChargingStationConfiguration
= null;
1230 if (this.getOcppPersistentConfiguration()) {
1231 const configurationFromFile
= this.getConfigurationFromFile();
1232 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1234 configuration
&& delete configuration
.stationInfo
;
1235 return configuration
;
1238 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1239 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1240 if (!ocppConfiguration
) {
1241 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1243 return ocppConfiguration
;
1246 private saveOcppConfiguration(): void {
1247 if (this.getOcppPersistentConfiguration()) {
1248 this.saveConfiguration(Section
.ocppConfiguration
);
1252 private async onOpen(): Promise
<void> {
1254 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1256 if (!this.isInAcceptedState()) {
1257 // Send BootNotification
1258 let registrationRetryCount
= 0;
1260 this.bootNotificationResponse
=
1261 await this.ocppRequestService
.sendMessageHandler
<BootNotificationResponse
>(
1262 RequestCommand
.BOOT_NOTIFICATION
,
1264 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1265 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1266 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1267 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1268 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1269 iccid
: this.bootNotificationRequest
.iccid
,
1270 imsi
: this.bootNotificationRequest
.imsi
,
1271 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1272 meterType
: this.bootNotificationRequest
.meterType
,
1274 { skipBufferingOnError
: true }
1276 if (!this.isInAcceptedState()) {
1277 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1279 this.bootNotificationResponse
?.interval
1280 ? this.bootNotificationResponse
.interval
* 1000
1281 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1285 !this.isInAcceptedState() &&
1286 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1287 this.getRegistrationMaxRetries() === -1)
1290 if (this.isInAcceptedState()) {
1291 await this.startMessageSequence();
1292 this.stopped
&& (this.stopped
= false);
1293 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
1294 this.flushMessageBuffer();
1298 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1301 this.autoReconnectRetryCount
= 0;
1302 this.wsConnectionRestarted
= false;
1305 private async onClose(code
: number, reason
: string): Promise
<void> {
1308 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1309 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1311 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1313 )}' and reason '${reason}'`
1315 this.autoReconnectRetryCount
= 0;
1320 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1322 )}' and reason '${reason}'`
1324 await this.reconnect(code
);
1329 private async onMessage(data
: Data
): Promise
<void> {
1330 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1333 '' as IncomingRequestCommand
,
1337 let responseCallback
: (
1338 payload
: JsonType
| string,
1339 requestPayload
: JsonType
| OCPPError
1341 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1342 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1343 let requestPayload
: JsonType
| OCPPError
;
1344 let cachedRequest
: CachedRequest
;
1347 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
1348 if (Utils
.isIterable(request
)) {
1349 // Parse the message
1350 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
1352 throw new OCPPError(
1353 ErrorType
.PROTOCOL_ERROR
,
1354 'Incoming request is not iterable',
1358 // Check the Type of message
1359 switch (messageType
) {
1361 case MessageType
.CALL_MESSAGE
:
1362 if (this.getEnableStatistics()) {
1363 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1366 await this.ocppIncomingRequestService
.handleRequest(
1373 case MessageType
.CALL_RESULT_MESSAGE
:
1375 cachedRequest
= this.requests
.get(messageId
);
1376 if (Utils
.isIterable(cachedRequest
)) {
1377 [responseCallback
, , , requestPayload
] = cachedRequest
;
1379 throw new OCPPError(
1380 ErrorType
.PROTOCOL_ERROR
,
1381 `Cached request for message id ${messageId} response is not iterable`,
1385 if (!responseCallback
) {
1387 throw new OCPPError(
1388 ErrorType
.INTERNAL_ERROR
,
1389 `Response for unknown message id ${messageId}`,
1393 responseCallback(commandName
, requestPayload
);
1396 case MessageType
.CALL_ERROR_MESSAGE
:
1397 cachedRequest
= this.requests
.get(messageId
);
1398 if (Utils
.isIterable(cachedRequest
)) {
1399 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1401 throw new OCPPError(
1402 ErrorType
.PROTOCOL_ERROR
,
1403 `Cached request for message id ${messageId} error response is not iterable`
1406 if (!rejectCallback
) {
1408 throw new OCPPError(
1409 ErrorType
.INTERNAL_ERROR
,
1410 `Error response for unknown message id ${messageId}`,
1415 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
1420 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1421 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1422 logger
.error(errMsg
);
1423 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1428 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1431 this.requests
.get(messageId
),
1435 messageType
=== MessageType
.CALL_MESSAGE
&&
1436 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1440 private onPing(): void {
1441 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1444 private onPong(): void {
1445 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1448 private onError(error
: WSError
): void {
1449 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1452 private getAuthorizationFile(): string | undefined {
1454 this.stationInfo
.authorizationFile
&&
1456 path
.resolve(__dirname
, '../'),
1458 path
.basename(this.stationInfo
.authorizationFile
)
1463 private getAuthorizedTags(): string[] {
1464 let authorizedTags
: string[] = [];
1465 const authorizationFile
= this.getAuthorizationFile();
1466 if (authorizationFile
) {
1468 // Load authorization file
1469 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1471 FileUtils
.handleFileException(
1473 FileType
.Authorization
,
1475 error
as NodeJS
.ErrnoException
1480 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1483 return authorizedTags
;
1486 private getUseConnectorId0(): boolean | undefined {
1487 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1488 ? this.stationInfo
.useConnectorId0
1492 private getNumberOfRunningTransactions(): number {
1494 for (const connectorId
of this.connectors
.keys()) {
1495 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1503 private getConnectionTimeout(): number | undefined {
1504 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1506 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1507 Constants
.DEFAULT_CONNECTION_TIMEOUT
1510 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1513 // -1 for unlimited, 0 for disabling
1514 private getAutoReconnectMaxRetries(): number | undefined {
1515 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1516 return this.stationInfo
.autoReconnectMaxRetries
;
1518 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1519 return Configuration
.getAutoReconnectMaxRetries();
1525 private getRegistrationMaxRetries(): number | undefined {
1526 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1527 return this.stationInfo
.registrationMaxRetries
;
1532 private getPowerDivider(): number {
1533 let powerDivider
= this.getNumberOfConnectors();
1534 if (this.stationInfo
.powerSharedByConnectors
) {
1535 powerDivider
= this.getNumberOfRunningTransactions();
1537 return powerDivider
;
1540 private getTemplateMaxNumberOfConnectors(): number {
1541 return Object.keys(this.stationInfo
.Connectors
).length
;
1544 private getMaxNumberOfConnectors(): number {
1545 let maxConnectors
: number;
1546 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1547 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1548 // Distribute evenly the number of connectors
1549 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1550 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1551 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1553 maxConnectors
= this.stationInfo
.Connectors
[0]
1554 ? this.getTemplateMaxNumberOfConnectors() - 1
1555 : this.getTemplateMaxNumberOfConnectors();
1557 return maxConnectors
;
1560 private async startMessageSequence(): Promise
<void> {
1561 if (this.stationInfo
.autoRegister
) {
1562 await this.ocppRequestService
.sendMessageHandler
<BootNotificationResponse
>(
1563 RequestCommand
.BOOT_NOTIFICATION
,
1565 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1566 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1567 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1568 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1569 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1570 iccid
: this.bootNotificationRequest
.iccid
,
1571 imsi
: this.bootNotificationRequest
.imsi
,
1572 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1573 meterType
: this.bootNotificationRequest
.meterType
,
1575 { skipBufferingOnError
: true }
1578 // Start WebSocket ping
1579 this.startWebSocketPing();
1581 this.startHeartbeat();
1582 // Initialize connectors status
1583 for (const connectorId
of this.connectors
.keys()) {
1584 if (connectorId
=== 0) {
1588 !this.getConnectorStatus(connectorId
)?.status &&
1589 this.getConnectorStatus(connectorId
)?.bootStatus
1591 // Send status in template at startup
1592 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1593 RequestCommand
.STATUS_NOTIFICATION
,
1596 status: this.getConnectorStatus(connectorId
).bootStatus
,
1597 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1600 this.getConnectorStatus(connectorId
).status =
1601 this.getConnectorStatus(connectorId
).bootStatus
;
1604 this.getConnectorStatus(connectorId
)?.status &&
1605 this.getConnectorStatus(connectorId
)?.bootStatus
1607 // Send status in template after reset
1608 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1609 RequestCommand
.STATUS_NOTIFICATION
,
1612 status: this.getConnectorStatus(connectorId
).bootStatus
,
1613 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1616 this.getConnectorStatus(connectorId
).status =
1617 this.getConnectorStatus(connectorId
).bootStatus
;
1618 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1619 // Send previous status at template reload
1620 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1621 RequestCommand
.STATUS_NOTIFICATION
,
1624 status: this.getConnectorStatus(connectorId
).status,
1625 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1629 // Send default status
1630 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1631 RequestCommand
.STATUS_NOTIFICATION
,
1634 status: ChargePointStatus
.AVAILABLE
,
1635 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1638 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1642 this.startAutomaticTransactionGenerator();
1645 private startAutomaticTransactionGenerator() {
1646 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1647 if (!this.automaticTransactionGenerator
) {
1648 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1650 if (!this.automaticTransactionGenerator
.started
) {
1651 this.automaticTransactionGenerator
.start();
1656 private async stopMessageSequence(
1657 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1659 // Stop WebSocket ping
1660 this.stopWebSocketPing();
1662 this.stopHeartbeat();
1665 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1666 this.automaticTransactionGenerator
?.started
1668 this.automaticTransactionGenerator
.stop();
1670 for (const connectorId
of this.connectors
.keys()) {
1671 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1672 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1674 this.getBeginEndMeterValues() &&
1675 this.getOcppStrictCompliance() &&
1676 !this.getOutOfOrderEndMeterValues()
1678 // FIXME: Implement OCPP version agnostic helpers
1679 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1682 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1684 await this.ocppRequestService
.sendMessageHandler
<MeterValuesResponse
>(
1685 RequestCommand
.METER_VALUES
,
1689 meterValue
: transactionEndMeterValue
,
1693 await this.ocppRequestService
.sendMessageHandler
<StopTransactionResponse
>(
1694 RequestCommand
.STOP_TRANSACTION
,
1697 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1698 idTag
: this.getTransactionIdTag(transactionId
),
1707 private startWebSocketPing(): void {
1708 const webSocketPingInterval
: number = this.getConfigurationKey(
1709 StandardParametersKey
.WebSocketPingInterval
1711 ? Utils
.convertToInt(
1712 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1715 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1716 this.webSocketPingSetInterval
= setInterval(() => {
1717 if (this.isWebSocketConnectionOpened()) {
1718 this.wsConnection
.ping((): void => {
1719 /* This is intentional */
1722 }, webSocketPingInterval
* 1000);
1725 ' WebSocket ping started every ' +
1726 Utils
.formatDurationSeconds(webSocketPingInterval
)
1728 } else if (this.webSocketPingSetInterval
) {
1731 ' WebSocket ping every ' +
1732 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1737 `${this.logPrefix()} WebSocket ping interval set to ${
1738 webSocketPingInterval
1739 ? Utils.formatDurationSeconds(webSocketPingInterval)
1740 : webSocketPingInterval
1741 }, not starting the WebSocket ping`
1746 private stopWebSocketPing(): void {
1747 if (this.webSocketPingSetInterval
) {
1748 clearInterval(this.webSocketPingSetInterval
);
1752 private warnDeprecatedTemplateKey(
1753 template
: ChargingStationTemplate
,
1755 chargingStationId
: string,
1758 if (!Utils
.isUndefined(template
[key
])) {
1759 const logPrefixStr
= ` ${chargingStationId} |`;
1761 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1763 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1768 private convertDeprecatedTemplateKey(
1769 template
: ChargingStationTemplate
,
1770 deprecatedKey
: string,
1773 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1774 template
[key
] = template
[deprecatedKey
] as unknown
;
1775 delete template
[deprecatedKey
];
1779 private getConfiguredSupervisionUrl(): URL
{
1780 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1781 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1783 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1785 switch (Configuration
.getSupervisionUrlDistribution()) {
1786 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1787 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1789 case SupervisionUrlDistribution
.RANDOM
:
1791 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1793 case SupervisionUrlDistribution
.SEQUENTIAL
:
1794 if (this.index
<= supervisionUrls
.length
) {
1795 urlIndex
= this.index
- 1;
1798 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1804 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1805 SupervisionUrlDistribution.ROUND_ROBIN
1808 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1811 return new URL(supervisionUrls
[urlIndex
]);
1813 return new URL(supervisionUrls
as string);
1816 private getHeartbeatInterval(): number | undefined {
1817 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
1818 if (HeartbeatInterval
) {
1819 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1821 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
1822 if (HeartBeatInterval
) {
1823 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1825 !this.stationInfo
.autoRegister
&&
1827 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1828 Constants.DEFAULT_HEARTBEAT_INTERVAL
1831 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1834 private stopHeartbeat(): void {
1835 if (this.heartbeatSetInterval
) {
1836 clearInterval(this.heartbeatSetInterval
);
1840 private openWSConnection(
1841 options
: WsOptions
= this.stationInfo
.wsOptions
,
1842 forceCloseOpened
= false
1844 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1846 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1847 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1849 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1851 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1852 this.wsConnection
.close();
1854 let protocol
: string;
1855 switch (this.getOcppVersion()) {
1856 case OCPPVersion
.VERSION_16
:
1857 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1860 this.handleUnsupportedVersion(this.getOcppVersion());
1863 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1865 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1869 private stopMeterValues(connectorId
: number) {
1870 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1871 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1875 private getReconnectExponentialDelay(): boolean | undefined {
1876 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1877 ? this.stationInfo
.reconnectExponentialDelay
1881 private async reconnect(code
: number): Promise
<void> {
1882 // Stop WebSocket ping
1883 this.stopWebSocketPing();
1885 this.stopHeartbeat();
1886 // Stop the ATG if needed
1888 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1889 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1890 this.automaticTransactionGenerator
?.started
1892 this.automaticTransactionGenerator
.stop();
1895 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1896 this.getAutoReconnectMaxRetries() === -1
1898 this.autoReconnectRetryCount
++;
1899 const reconnectDelay
= this.getReconnectExponentialDelay()
1900 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1901 : this.getConnectionTimeout() * 1000;
1902 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1904 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1907 )}ms, timeout ${reconnectTimeout}ms`
1909 await Utils
.sleep(reconnectDelay
);
1912 ' WebSocket: reconnecting try #' +
1913 this.autoReconnectRetryCount
.toString()
1915 this.openWSConnection(
1916 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
1919 this.wsConnectionRestarted
= true;
1920 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1922 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1923 this.autoReconnectRetryCount
1924 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1929 private initializeConnectorStatus(connectorId
: number): void {
1930 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1931 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1932 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1933 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1934 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1935 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;