1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
5 BootNotificationRequest
,
8 IncomingRequestCommand
,
10 } from
'../types/ocpp/Requests';
11 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
12 import ChargingStationConfiguration
, {
14 } from
'../types/ChargingStationConfiguration';
15 import ChargingStationTemplate
, {
19 } from
'../types/ChargingStationTemplate';
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';
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';
61 import logger from
'../utils/Logger';
62 import { parentPort
} from
'worker_threads';
63 import path from
'path';
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
;
91 constructor(index
: number, stationTemplateFile
: string) {
92 this.id
= Utils
.generateUUID();
94 this.stationTemplateFile
= stationTemplateFile
;
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>();
102 this.authorizedTags
= this.getAuthorizedTags();
105 get
wsConnectionUrl(): URL
{
106 return this.getSupervisionUrlOcppConfiguration()
108 this.getConfigurationKey(
109 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
112 this.stationInfo
.chargingStationId
114 : this.wsConfiguredConnectionUrl
;
117 public logPrefix(): string {
118 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
121 public getBootNotificationRequest(): BootNotificationRequest
{
122 return this.bootNotificationRequest
;
125 public getRandomIdTag(): string {
126 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
127 return this.authorizedTags
[index
];
130 public hasAuthorizedTags(): boolean {
131 return !Utils
.isEmptyArray(this.authorizedTags
);
134 public getEnableStatistics(): boolean | undefined {
135 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
136 ? this.stationInfo
.enableStatistics
140 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
141 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
144 public getNumberOfPhases(): number | undefined {
145 switch (this.getCurrentOutType()) {
147 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
148 ? this.stationInfo
.numberOfPhases
155 public isWebSocketConnectionOpened(): boolean {
156 return this?.wsConnection
?.readyState
=== OPEN
;
159 public getRegistrationStatus(): RegistrationStatus
{
160 return this?.bootNotificationResponse
?.status;
163 public isInUnknownState(): boolean {
164 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
167 public isInPendingState(): boolean {
168 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
171 public isInAcceptedState(): boolean {
172 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
175 public isInRejectedState(): boolean {
176 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
179 public isRegistered(): boolean {
180 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
183 public isChargingStationAvailable(): boolean {
184 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
187 public isConnectorAvailable(id
: number): boolean {
188 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
191 public getNumberOfConnectors(): number {
192 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
195 public getConnectorStatus(id
: number): ConnectorStatus
{
196 return this.connectors
.get(id
);
199 public getCurrentOutType(): CurrentType
| undefined {
200 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
203 public getOcppStrictCompliance(): boolean {
204 return this.stationInfo
.ocppStrictCompliance
?? false;
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()) {
214 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
217 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
220 logger
.error(errMsg
);
221 throw new Error(errMsg
);
223 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
224 ? this.stationInfo
.voltageOut
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
;
236 public getOutOfOrderEndMeterValues(): boolean {
237 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
240 public getBeginEndMeterValues(): boolean {
241 return this.stationInfo
.beginEndMeterValues
?? false;
244 public getMeteringPerTransaction(): boolean {
245 return this.stationInfo
.meteringPerTransaction
?? true;
248 public getTransactionDataMeterValues(): boolean {
249 return this.stationInfo
.transactionDataMeterValues
?? false;
252 public getMainVoltageMeterValues(): boolean {
253 return this.stationInfo
.mainVoltageMeterValues
?? true;
256 public getPhaseLineToLineVoltageMeterValues(): boolean {
257 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
260 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
261 for (const connectorId
of this.connectors
.keys()) {
264 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
271 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
272 const transactionConnectorStatus
= this.getConnectorStatus(
273 this.getConnectorIdByTransactionId(transactionId
)
275 if (this.getMeteringPerTransaction()) {
276 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
278 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
281 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
282 const connectorStatus
= this.getConnectorStatus(connectorId
);
283 if (this.getMeteringPerTransaction()) {
284 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
286 return connectorStatus
?.energyActiveImportRegisterValue
;
289 public getAuthorizeRemoteTxRequests(): boolean {
290 const authorizeRemoteTxRequests
= this.getConfigurationKey(
291 StandardParametersKey
.AuthorizeRemoteTxRequests
293 return authorizeRemoteTxRequests
294 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
298 public getLocalAuthListEnabled(): boolean {
299 const localAuthListEnabled
= this.getConfigurationKey(
300 StandardParametersKey
.LocalAuthListEnabled
302 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
305 public restartWebSocketPing(): void {
306 // Stop WebSocket ping
307 this.stopWebSocketPing();
308 // Start WebSocket ping
309 this.startWebSocketPing();
312 public getSampledValueTemplate(
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
)) {
320 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
325 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
326 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
331 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
332 StandardParametersKey.MeterValuesSampledData
337 const sampledValueTemplates
: SampledValueTemplate
[] =
338 this.getConnectorStatus(connectorId
).MeterValues
;
341 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
345 !Constants
.SUPPORTED_MEASURANDS
.includes(
346 sampledValueTemplates
[index
]?.measurand
??
347 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
351 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
355 sampledValueTemplates
[index
]?.phase
=== phase
&&
356 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
357 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
361 return sampledValueTemplates
[index
];
364 !sampledValueTemplates
[index
].phase
&&
365 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
366 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
370 return sampledValueTemplates
[index
];
372 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
373 (!sampledValueTemplates
[index
].measurand
||
374 sampledValueTemplates
[index
].measurand
=== measurand
)
376 return sampledValueTemplates
[index
];
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
);
385 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
389 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
390 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
393 public startHeartbeat(): void {
395 this.getHeartbeatInterval() &&
396 this.getHeartbeatInterval() > 0 &&
397 !this.heartbeatSetInterval
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());
405 ' Heartbeat started every ' +
406 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
408 } else if (this.heartbeatSetInterval
) {
411 ' Heartbeat already started every ' +
412 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
416 `${this.logPrefix()} Heartbeat interval set to ${
417 this.getHeartbeatInterval()
418 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
419 : this.getHeartbeatInterval()
420 }, not starting the heartbeat`
425 public restartHeartbeat(): void {
427 this.stopHeartbeat();
429 this.startHeartbeat();
432 public startMeterValues(connectorId
: number, interval
: number): void {
433 if (connectorId
=== 0) {
435 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
439 if (!this.getConnectorStatus(connectorId
)) {
441 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
445 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
447 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
451 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
452 !this.getConnectorStatus(connectorId
)?.transactionId
455 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
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(
468 this.getConnectorStatus(connectorId
).transactionId
,
471 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.METER_VALUES
, {
473 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
474 meterValue
: [meterValue
],
481 `${this.logPrefix()} Charging station ${
482 StandardParametersKey.MeterValueSampleInterval
483 } configuration set to ${
484 interval ? Utils.formatDurationMilliSeconds(interval) : interval
485 }, not sending MeterValues`
490 public start(): void {
491 if (this.getEnableStatistics()) {
492 this.performanceStatistics
.start();
494 this.openWSConnection();
495 // Monitor authorization file
496 FileUtils
.watchJsonFile
<string[]>(
498 FileType
.Authorization
,
499 this.getAuthorizationFile(),
502 // Monitor charging station template file
503 FileUtils
.watchJsonFile(
505 FileType
.ChargingStationTemplate
,
506 this.stationTemplateFile
,
508 (event
, filename
): void => {
509 if (filename
&& event
=== 'change') {
512 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
513 this.stationTemplateFile
514 } file have changed, reload`
520 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
521 this.automaticTransactionGenerator
523 this.automaticTransactionGenerator
.stop();
525 this.startAutomaticTransactionGenerator();
526 if (this.getEnableStatistics()) {
527 this.performanceStatistics
.restart();
529 this.performanceStatistics
.stop();
531 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
534 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
541 FileUtils
.watchJsonFile
<ChargingStationConfiguration
>(
543 FileType
.ChargingStationConfiguration
,
544 this.configurationFile
,
547 // Handle WebSocket message
548 this.wsConnection
.on(
550 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
552 // Handle WebSocket error
553 this.wsConnection
.on(
555 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
557 // Handle WebSocket close
558 this.wsConnection
.on(
560 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
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
},
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
, {
581 status: ChargePointStatus
.UNAVAILABLE
,
582 errorCode
: ChargePointErrorCode
.NO_ERROR
,
584 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
587 if (this.isWebSocketConnectionOpened()) {
588 this.wsConnection
.close();
590 if (this.getEnableStatistics()) {
591 this.performanceStatistics
.stop();
593 this.bootNotificationResponse
= null;
594 parentPort
.postMessage({
595 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
596 data
: { id
: this.stationInfo
.chargingStationId
},
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();
609 return configElement
.key
=== key
;
613 public addConfigurationKey(
614 key
: string | StandardParametersKey
,
616 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
621 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
623 if (!options
|| Utils
.isEmptyObject(options
)) {
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
),
639 keyFound
= undefined;
642 this.configuration
.configurationKey
.push({
649 params
?.save
&& this.saveConfiguration();
652 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
658 public setConfigurationKeyValue(
659 key
: string | StandardParametersKey
,
661 caseInsensitive
= false
663 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
665 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
666 this.configuration
.configurationKey
[keyIndex
].value
= value
;
667 this.saveConfiguration();
670 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
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) => {
682 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
683 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
684 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
686 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
692 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
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
);
709 public bufferMessage(message
: string): void {
710 this.messageBuffer
.add(message
);
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
);
723 private getSupervisionUrlOcppConfiguration(): boolean {
724 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
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
+
736 instanceIndex
.toString() +
737 idStr
.substring(idStr
.length
- 4) +
741 private buildStationInfo(): ChargingStationInfo
{
742 let stationTemplateFromFile
: ChargingStationTemplate
;
744 // Load template file
745 stationTemplateFromFile
= JSON
.parse(
746 fs
.readFileSync(this.stationTemplateFile
, 'utf8')
747 ) as ChargingStationTemplate
;
749 FileUtils
.handleFileException(
751 FileType
.ChargingStationTemplate
,
752 this.stationTemplateFile
,
753 error
as NodeJS
.ErrnoException
756 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
757 // Deprecation template keys section
758 this.warnDeprecatedTemplateKey(
759 stationTemplateFromFile
,
762 "Use 'supervisionUrls' instead"
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
772 stationInfo
.maxPower
=
773 stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
774 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
775 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
777 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
778 stationInfo
.maxPower
=
779 stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
780 ? stationTemplateFromFile
.power
* 1000
781 : stationTemplateFromFile
.power
;
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
;
792 private getOcppVersion(): OCPPVersion
{
793 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
796 private handleUnsupportedVersion(version
: OCPPVersion
) {
797 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
798 this.stationTemplateFile
800 logger
.error(errMsg
);
801 throw new Error(errMsg
);
804 private initialize(): void {
805 this.stationInfo
= this.buildStationInfo();
806 this.configurationFile
= path
.join(
807 path
.resolve(__dirname
, '../'),
810 this.stationInfo
.chargingStationId
+ '.json'
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
,
820 ...(!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && {
821 firmwareVersion
: this.stationInfo
.firmwareVersion
,
824 // Build connectors if needed
825 const maxConnectors
= this.getMaxNumberOfConnectors();
826 if (maxConnectors
<= 0) {
828 `${this.logPrefix()} Charging station template ${
829 this.stationTemplateFile
830 } with ${maxConnectors} connectors`
833 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
834 if (templateMaxConnectors
<= 0) {
836 `${this.logPrefix()} Charging station template ${
837 this.stationTemplateFile
838 } with no connector configuration`
841 if (!this.stationInfo
.Connectors
[0]) {
843 `${this.logPrefix()} Charging station template ${
844 this.stationTemplateFile
845 } with no connector Id 0 configuration`
851 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
852 !this.stationInfo
.randomConnectors
855 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
856 this.stationTemplateFile
857 }, forcing random connector configurations affectation`
859 this.stationInfo
.randomConnectors
= true;
861 const connectorsConfigHash
= crypto
862 .createHash('sha256')
863 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
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
);
875 lastConnectorId
=== 0 &&
876 this.getUseConnectorId0() &&
877 this.stationInfo
.Connectors
[lastConnector
]
881 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
883 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
884 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
885 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
889 // Generate all connectors
891 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
893 for (let index
= 1; index
<= maxConnectors
; index
++) {
894 const randConnectorId
= this.stationInfo
.randomConnectors
895 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
899 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
901 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
902 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
903 this.getConnectorStatus(index
).chargingProfiles
= [];
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
);
916 this.wsConfiguredConnectionUrl
= new URL(
917 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
919 switch (this.getOcppVersion()) {
920 case OCPPVersion
.VERSION_16
:
921 this.ocppIncomingRequestService
=
922 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
923 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
925 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
929 this.handleUnsupportedVersion(this.getOcppVersion());
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
,
941 this.stationInfo
.powerDivider
= this.getPowerDivider();
942 if (this.getEnableStatistics()) {
943 this.performanceStatistics
= PerformanceStatistics
.getInstance(
945 this.stationInfo
.chargingStationId
,
951 private initOcppParameters(): void {
953 this.getSupervisionUrlOcppConfiguration() &&
954 !this.getConfigurationKey(
955 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
958 this.addConfigurationKey(
959 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
,
960 this.getConfiguredSupervisionUrl().href
,
964 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
965 this.addConfigurationKey(
966 StandardParametersKey
.SupportedFeatureProfiles
,
967 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
970 this.addConfigurationKey(
971 StandardParametersKey
.NumberOfConnectors
,
972 this.getNumberOfConnectors().toString(),
976 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
977 this.addConfigurationKey(
978 StandardParametersKey
.MeterValuesSampledData
,
979 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
982 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
983 const connectorPhaseRotation
= [];
984 for (const connectorId
of this.connectors
.keys()) {
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}`);
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}`);
997 this.addConfigurationKey(
998 StandardParametersKey
.ConnectorPhaseRotation
,
999 connectorPhaseRotation
.toString()
1002 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1003 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1006 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1007 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(
1008 SupportedFeatureProfiles
.Local_Auth_List_Management
1011 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1013 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1014 this.addConfigurationKey(
1015 StandardParametersKey
.ConnectionTimeOut
,
1016 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1019 this.saveConfiguration();
1022 private getConfigurationFromTemplate(): ChargingStationConfiguration
{
1023 return this.stationInfo
.Configuration
?? ({} as ChargingStationConfiguration
);
1026 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1027 let configuration
: ChargingStationConfiguration
= null;
1028 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1030 configuration
= JSON
.parse(
1031 fs
.readFileSync(this.configurationFile
, 'utf8')
1032 ) as ChargingStationConfiguration
;
1034 FileUtils
.handleFileException(
1036 FileType
.ChargingStationConfiguration
,
1037 this.configurationFile
,
1038 error
as NodeJS
.ErrnoException
1042 return configuration
;
1045 private saveConfiguration(): void {
1046 if (this.configurationFile
) {
1048 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1049 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1051 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1052 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(this.configuration
, null, 2));
1053 fs
.closeSync(fileDescriptor
);
1055 FileUtils
.handleFileException(
1057 FileType
.ChargingStationConfiguration
,
1058 this.configurationFile
,
1059 error
as NodeJS
.ErrnoException
1064 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1069 private getConfiguration(): ChargingStationConfiguration
{
1070 let configuration
: ChargingStationConfiguration
= this.getConfigurationFromFile();
1071 if (!configuration
) {
1072 configuration
= this.getConfigurationFromTemplate();
1074 return configuration
;
1077 private async onOpen(): Promise
<void> {
1079 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1081 if (!this.isInAcceptedState()) {
1082 // Send BootNotification
1083 let registrationRetryCount
= 0;
1085 this.bootNotificationResponse
= (await this.ocppRequestService
.sendMessageHandler(
1086 RequestCommand
.BOOT_NOTIFICATION
,
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
,
1098 { skipBufferingOnError
: true }
1099 )) as BootNotificationResponse
;
1100 if (!this.isInAcceptedState()) {
1101 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1103 this.bootNotificationResponse
?.interval
1104 ? this.bootNotificationResponse
.interval
* 1000
1105 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1109 !this.isInAcceptedState() &&
1110 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1111 this.getRegistrationMaxRetries() === -1)
1114 if (this.isInAcceptedState()) {
1115 await this.startMessageSequence();
1116 this.stopped
&& (this.stopped
= false);
1117 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
1118 this.flushMessageBuffer();
1122 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1125 this.autoReconnectRetryCount
= 0;
1126 this.wsConnectionRestarted
= false;
1129 private async onClose(code
: number, reason
: string): Promise
<void> {
1132 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1133 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1135 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1137 )}' and reason '${reason}'`
1139 this.autoReconnectRetryCount
= 0;
1144 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1146 )}' and reason '${reason}'`
1148 await this.reconnect(code
);
1153 private async onMessage(data
: Data
): Promise
<void> {
1154 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1157 '' as IncomingRequestCommand
,
1161 let responseCallback
: (
1162 payload
: JsonType
| string,
1163 requestPayload
: JsonType
| OCPPError
1165 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1166 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1167 let requestPayload
: JsonType
| OCPPError
;
1168 let cachedRequest
: CachedRequest
;
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
;
1176 throw new OCPPError(
1177 ErrorType
.PROTOCOL_ERROR
,
1178 'Incoming request is not iterable',
1182 // Check the Type of message
1183 switch (messageType
) {
1185 case MessageType
.CALL_MESSAGE
:
1186 if (this.getEnableStatistics()) {
1187 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1190 await this.ocppIncomingRequestService
.handleRequest(
1197 case MessageType
.CALL_RESULT_MESSAGE
:
1199 cachedRequest
= this.requests
.get(messageId
);
1200 if (Utils
.isIterable(cachedRequest
)) {
1201 [responseCallback
, , , requestPayload
] = cachedRequest
;
1203 throw new OCPPError(
1204 ErrorType
.PROTOCOL_ERROR
,
1205 `Cached request for message id ${messageId} response is not iterable`,
1209 if (!responseCallback
) {
1211 throw new OCPPError(
1212 ErrorType
.INTERNAL_ERROR
,
1213 `Response for unknown message id ${messageId}`,
1217 responseCallback(commandName
, requestPayload
);
1220 case MessageType
.CALL_ERROR_MESSAGE
:
1221 cachedRequest
= this.requests
.get(messageId
);
1222 if (Utils
.isIterable(cachedRequest
)) {
1223 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1225 throw new OCPPError(
1226 ErrorType
.PROTOCOL_ERROR
,
1227 `Cached request for message id ${messageId} error response is not iterable`
1230 if (!rejectCallback
) {
1232 throw new OCPPError(
1233 ErrorType
.INTERNAL_ERROR
,
1234 `Error response for unknown message id ${messageId}`,
1239 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
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
);
1252 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1255 this.requests
.get(messageId
),
1259 messageType
=== MessageType
.CALL_MESSAGE
&&
1260 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1264 private onPing(): void {
1265 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1268 private onPong(): void {
1269 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1272 private onError(error
: WSError
): void {
1273 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1276 private getAuthorizationFile(): string | undefined {
1278 this.stationInfo
.authorizationFile
&&
1280 path
.resolve(__dirname
, '../'),
1282 path
.basename(this.stationInfo
.authorizationFile
)
1287 private getAuthorizedTags(): string[] {
1288 let authorizedTags
: string[] = [];
1289 const authorizationFile
= this.getAuthorizationFile();
1290 if (authorizationFile
) {
1292 // Load authorization file
1293 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1295 FileUtils
.handleFileException(
1297 FileType
.Authorization
,
1299 error
as NodeJS
.ErrnoException
1305 ' No authorization file given in template file ' +
1306 this.stationTemplateFile
1309 return authorizedTags
;
1312 private getUseConnectorId0(): boolean | undefined {
1313 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1314 ? this.stationInfo
.useConnectorId0
1318 private getNumberOfRunningTransactions(): number {
1320 for (const connectorId
of this.connectors
.keys()) {
1321 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1329 private getConnectionTimeout(): number | undefined {
1330 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1332 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1333 Constants
.DEFAULT_CONNECTION_TIMEOUT
1336 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1339 // -1 for unlimited, 0 for disabling
1340 private getAutoReconnectMaxRetries(): number | undefined {
1341 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1342 return this.stationInfo
.autoReconnectMaxRetries
;
1344 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1345 return Configuration
.getAutoReconnectMaxRetries();
1351 private getRegistrationMaxRetries(): number | undefined {
1352 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1353 return this.stationInfo
.registrationMaxRetries
;
1358 private getPowerDivider(): number {
1359 let powerDivider
= this.getNumberOfConnectors();
1360 if (this.stationInfo
.powerSharedByConnectors
) {
1361 powerDivider
= this.getNumberOfRunningTransactions();
1363 return powerDivider
;
1366 private getTemplateMaxNumberOfConnectors(): number {
1367 return Object.keys(this.stationInfo
.Connectors
).length
;
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;
1379 maxConnectors
= this.stationInfo
.Connectors
[0]
1380 ? this.getTemplateMaxNumberOfConnectors() - 1
1381 : this.getTemplateMaxNumberOfConnectors();
1383 return maxConnectors
;
1386 private async startMessageSequence(): Promise
<void> {
1387 if (this.stationInfo
.autoRegister
) {
1388 await this.ocppRequestService
.sendMessageHandler(
1389 RequestCommand
.BOOT_NOTIFICATION
,
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
,
1401 { skipBufferingOnError
: true }
1404 // Start WebSocket ping
1405 this.startWebSocketPing();
1407 this.startHeartbeat();
1408 // Initialize connectors status
1409 for (const connectorId
of this.connectors
.keys()) {
1410 if (connectorId
=== 0) {
1414 !this.getConnectorStatus(connectorId
)?.status &&
1415 this.getConnectorStatus(connectorId
)?.bootStatus
1417 // Send status in template at startup
1418 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1420 status: this.getConnectorStatus(connectorId
).bootStatus
,
1421 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1423 this.getConnectorStatus(connectorId
).status =
1424 this.getConnectorStatus(connectorId
).bootStatus
;
1427 this.getConnectorStatus(connectorId
)?.status &&
1428 this.getConnectorStatus(connectorId
)?.bootStatus
1430 // Send status in template after reset
1431 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1433 status: this.getConnectorStatus(connectorId
).bootStatus
,
1434 errorCode
: ChargePointErrorCode
.NO_ERROR
,
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
, {
1442 status: this.getConnectorStatus(connectorId
).status,
1443 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1446 // Send default status
1447 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1449 status: ChargePointStatus
.AVAILABLE
,
1450 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1452 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1456 this.startAutomaticTransactionGenerator();
1459 private startAutomaticTransactionGenerator() {
1460 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1461 if (!this.automaticTransactionGenerator
) {
1462 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1464 if (!this.automaticTransactionGenerator
.started
) {
1465 this.automaticTransactionGenerator
.start();
1470 private async stopMessageSequence(
1471 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1473 // Stop WebSocket ping
1474 this.stopWebSocketPing();
1476 this.stopHeartbeat();
1479 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1480 this.automaticTransactionGenerator
?.started
1482 this.automaticTransactionGenerator
.stop();
1484 for (const connectorId
of this.connectors
.keys()) {
1485 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1486 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1488 this.getBeginEndMeterValues() &&
1489 this.getOcppStrictCompliance() &&
1490 !this.getOutOfOrderEndMeterValues()
1492 // FIXME: Implement OCPP version agnostic helpers
1493 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1496 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1498 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.METER_VALUES
, {
1501 meterValue
: transactionEndMeterValue
,
1504 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STOP_TRANSACTION
, {
1506 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1507 idTag
: this.getTransactionIdTag(transactionId
),
1515 private startWebSocketPing(): void {
1516 const webSocketPingInterval
: number = this.getConfigurationKey(
1517 StandardParametersKey
.WebSocketPingInterval
1519 ? Utils
.convertToInt(
1520 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1523 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1524 this.webSocketPingSetInterval
= setInterval(() => {
1525 if (this.isWebSocketConnectionOpened()) {
1526 this.wsConnection
.ping((): void => {
1527 /* This is intentional */
1530 }, webSocketPingInterval
* 1000);
1533 ' WebSocket ping started every ' +
1534 Utils
.formatDurationSeconds(webSocketPingInterval
)
1536 } else if (this.webSocketPingSetInterval
) {
1539 ' WebSocket ping every ' +
1540 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1545 `${this.logPrefix()} WebSocket ping interval set to ${
1546 webSocketPingInterval
1547 ? Utils.formatDurationSeconds(webSocketPingInterval)
1548 : webSocketPingInterval
1549 }, not starting the WebSocket ping`
1554 private stopWebSocketPing(): void {
1555 if (this.webSocketPingSetInterval
) {
1556 clearInterval(this.webSocketPingSetInterval
);
1560 private warnDeprecatedTemplateKey(
1561 template
: ChargingStationTemplate
,
1563 chargingStationId
: string,
1566 if (!Utils
.isUndefined(template
[key
])) {
1567 const logPrefixStr
= ` ${chargingStationId} |`;
1569 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1570 this.stationTemplateFile
1571 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1576 private convertDeprecatedTemplateKey(
1577 template
: ChargingStationTemplate
,
1578 deprecatedKey
: string,
1581 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1582 template
[key
] = template
[deprecatedKey
] as unknown
;
1583 delete template
[deprecatedKey
];
1587 private getConfiguredSupervisionUrl(): URL
{
1588 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1589 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1591 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1593 switch (Configuration
.getSupervisionUrlDistribution()) {
1594 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1595 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1597 case SupervisionUrlDistribution
.RANDOM
:
1599 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1601 case SupervisionUrlDistribution
.SEQUENTIAL
:
1602 if (this.index
<= supervisionUrls
.length
) {
1603 urlIndex
= this.index
- 1;
1606 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1612 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1613 SupervisionUrlDistribution.ROUND_ROBIN
1616 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1619 return new URL(supervisionUrls
[urlIndex
]);
1621 return new URL(supervisionUrls
as string);
1624 private getHeartbeatInterval(): number | undefined {
1625 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
1626 if (HeartbeatInterval
) {
1627 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1629 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
1630 if (HeartBeatInterval
) {
1631 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1633 !this.stationInfo
.autoRegister
&&
1635 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1636 Constants.DEFAULT_HEARTBEAT_INTERVAL
1639 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1642 private stopHeartbeat(): void {
1643 if (this.heartbeatSetInterval
) {
1644 clearInterval(this.heartbeatSetInterval
);
1648 private openWSConnection(
1649 options
: ClientOptions
& ClientRequestArgs
= this.stationInfo
.wsOptions
,
1650 forceCloseOpened
= false
1652 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1654 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1655 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1657 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1659 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1660 this.wsConnection
.close();
1662 let protocol
: string;
1663 switch (this.getOcppVersion()) {
1664 case OCPPVersion
.VERSION_16
:
1665 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1668 this.handleUnsupportedVersion(this.getOcppVersion());
1671 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1673 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1677 private stopMeterValues(connectorId
: number) {
1678 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1679 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1683 private getReconnectExponentialDelay(): boolean | undefined {
1684 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1685 ? this.stationInfo
.reconnectExponentialDelay
1689 private async reconnect(code
: number): Promise
<void> {
1690 // Stop WebSocket ping
1691 this.stopWebSocketPing();
1693 this.stopHeartbeat();
1694 // Stop the ATG if needed
1696 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1697 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1698 this.automaticTransactionGenerator
?.started
1700 this.automaticTransactionGenerator
.stop();
1703 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1704 this.getAutoReconnectMaxRetries() === -1
1706 this.autoReconnectRetryCount
++;
1707 const reconnectDelay
= this.getReconnectExponentialDelay()
1708 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1709 : this.getConnectionTimeout() * 1000;
1710 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1712 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1715 )}ms, timeout ${reconnectTimeout}ms`
1717 await Utils
.sleep(reconnectDelay
);
1720 ' WebSocket: reconnecting try #' +
1721 this.autoReconnectRetryCount
.toString()
1723 this.openWSConnection(
1724 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
1727 this.wsConnectionRestarted
= true;
1728 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1730 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1731 this.autoReconnectRetryCount
1732 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
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;