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 FileUtils from
'../utils/FileUtils';
42 import { JsonType
} from
'../types/JsonType';
43 import { MessageType
} from
'../types/ocpp/MessageType';
44 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
45 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
46 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
47 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
48 import OCPPError from
'../exception/OCPPError';
49 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
50 import OCPPRequestService from
'./ocpp/OCPPRequestService';
51 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
52 import PerformanceStatistics from
'../performance/PerformanceStatistics';
53 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
54 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
55 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
56 import { URL
} from
'url';
57 import Utils from
'../utils/Utils';
58 import crypto from
'crypto';
60 import logger from
'../utils/Logger';
61 import { parentPort
} from
'worker_threads';
62 import path from
'path';
64 export default class ChargingStation
{
65 public readonly id
: string;
66 public readonly stationTemplateFile
: string;
67 public authorizedTags
: string[];
68 public stationInfo
!: ChargingStationInfo
;
69 public readonly connectors
: Map
<number, ConnectorStatus
>;
70 public configuration
!: ChargingStationConfiguration
;
71 public wsConnection
!: WebSocket
;
72 public readonly requests
: Map
<string, CachedRequest
>;
73 public performanceStatistics
!: PerformanceStatistics
;
74 public heartbeatSetInterval
!: NodeJS
.Timeout
;
75 public ocppRequestService
!: OCPPRequestService
;
76 private readonly index
: number;
77 private configurationFile
!: string;
78 private bootNotificationRequest
!: BootNotificationRequest
;
79 private bootNotificationResponse
!: BootNotificationResponse
| null;
80 private connectorsConfigurationHash
!: string;
81 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
82 private readonly messageBuffer
: Set
<string>;
83 private wsConfiguredConnectionUrl
!: URL
;
84 private wsConnectionRestarted
: boolean;
85 private stopped
: boolean;
86 private autoReconnectRetryCount
: number;
87 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
88 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
90 constructor(index
: number, stationTemplateFile
: string) {
91 this.id
= Utils
.generateUUID();
93 this.stationTemplateFile
= stationTemplateFile
;
95 this.wsConnectionRestarted
= false;
96 this.autoReconnectRetryCount
= 0;
97 this.connectors
= new Map
<number, ConnectorStatus
>();
98 this.requests
= new Map
<string, CachedRequest
>();
99 this.messageBuffer
= new Set
<string>();
101 this.authorizedTags
= this.getAuthorizedTags();
104 get
wsConnectionUrl(): URL
{
105 return this.getSupervisionUrlOcppConfiguration()
107 this.getConfigurationKey(
108 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
111 this.stationInfo
.chargingStationId
113 : this.wsConfiguredConnectionUrl
;
116 public logPrefix(): string {
117 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
120 public getBootNotificationRequest(): BootNotificationRequest
{
121 return this.bootNotificationRequest
;
124 public getRandomIdTag(): string {
125 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
126 return this.authorizedTags
[index
];
129 public hasAuthorizedTags(): boolean {
130 return !Utils
.isEmptyArray(this.authorizedTags
);
133 public getEnableStatistics(): boolean | undefined {
134 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
135 ? this.stationInfo
.enableStatistics
139 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
140 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
143 public getNumberOfPhases(): number | undefined {
144 switch (this.getCurrentOutType()) {
146 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
147 ? this.stationInfo
.numberOfPhases
154 public isWebSocketConnectionOpened(): boolean {
155 return this?.wsConnection
?.readyState
=== OPEN
;
158 public getRegistrationStatus(): RegistrationStatus
{
159 return this?.bootNotificationResponse
?.status;
162 public isInUnknownState(): boolean {
163 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
166 public isInPendingState(): boolean {
167 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
170 public isInAcceptedState(): boolean {
171 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
174 public isInRejectedState(): boolean {
175 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
178 public isRegistered(): boolean {
179 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
182 public isChargingStationAvailable(): boolean {
183 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
186 public isConnectorAvailable(id
: number): boolean {
187 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
190 public getNumberOfConnectors(): number {
191 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
194 public getConnectorStatus(id
: number): ConnectorStatus
{
195 return this.connectors
.get(id
);
198 public getCurrentOutType(): CurrentType
| undefined {
199 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
202 public getOcppStrictCompliance(): boolean {
203 return this.stationInfo
.ocppStrictCompliance
?? false;
206 public getVoltageOut(): number | undefined {
207 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
208 this.stationTemplateFile
209 }, cannot define default voltage out`;
210 let defaultVoltageOut
: number;
211 switch (this.getCurrentOutType()) {
213 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
216 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
219 logger
.error(errMsg
);
220 throw new Error(errMsg
);
222 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
223 ? this.stationInfo
.voltageOut
227 public getTransactionIdTag(transactionId
: number): string | undefined {
228 for (const connectorId
of this.connectors
.keys()) {
229 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
230 return this.getConnectorStatus(connectorId
).transactionIdTag
;
235 public getOutOfOrderEndMeterValues(): boolean {
236 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
239 public getBeginEndMeterValues(): boolean {
240 return this.stationInfo
.beginEndMeterValues
?? false;
243 public getMeteringPerTransaction(): boolean {
244 return this.stationInfo
.meteringPerTransaction
?? true;
247 public getTransactionDataMeterValues(): boolean {
248 return this.stationInfo
.transactionDataMeterValues
?? false;
251 public getMainVoltageMeterValues(): boolean {
252 return this.stationInfo
.mainVoltageMeterValues
?? true;
255 public getPhaseLineToLineVoltageMeterValues(): boolean {
256 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
259 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
260 for (const connectorId
of this.connectors
.keys()) {
263 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
270 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
271 const transactionConnectorStatus
= this.getConnectorStatus(
272 this.getConnectorIdByTransactionId(transactionId
)
274 if (this.getMeteringPerTransaction()) {
275 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
277 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
280 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
281 const connectorStatus
= this.getConnectorStatus(connectorId
);
282 if (this.getMeteringPerTransaction()) {
283 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
285 return connectorStatus
?.energyActiveImportRegisterValue
;
288 public getAuthorizeRemoteTxRequests(): boolean {
289 const authorizeRemoteTxRequests
= this.getConfigurationKey(
290 StandardParametersKey
.AuthorizeRemoteTxRequests
292 return authorizeRemoteTxRequests
293 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
297 public getLocalAuthListEnabled(): boolean {
298 const localAuthListEnabled
= this.getConfigurationKey(
299 StandardParametersKey
.LocalAuthListEnabled
301 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
304 public restartWebSocketPing(): void {
305 // Stop WebSocket ping
306 this.stopWebSocketPing();
307 // Start WebSocket ping
308 this.startWebSocketPing();
311 public getSampledValueTemplate(
313 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
314 phase
?: MeterValuePhase
315 ): SampledValueTemplate
| undefined {
316 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
317 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
319 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
324 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
325 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
330 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
331 StandardParametersKey.MeterValuesSampledData
336 const sampledValueTemplates
: SampledValueTemplate
[] =
337 this.getConnectorStatus(connectorId
).MeterValues
;
340 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
344 !Constants
.SUPPORTED_MEASURANDS
.includes(
345 sampledValueTemplates
[index
]?.measurand
??
346 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
350 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
354 sampledValueTemplates
[index
]?.phase
=== phase
&&
355 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
356 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
360 return sampledValueTemplates
[index
];
363 !sampledValueTemplates
[index
].phase
&&
364 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
365 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
369 return sampledValueTemplates
[index
];
371 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
372 (!sampledValueTemplates
[index
].measurand
||
373 sampledValueTemplates
[index
].measurand
=== measurand
)
375 return sampledValueTemplates
[index
];
378 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
379 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
380 logger
.error(errorMsg
);
381 throw new Error(errorMsg
);
384 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
388 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
389 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
392 public startHeartbeat(): void {
394 this.getHeartbeatInterval() &&
395 this.getHeartbeatInterval() > 0 &&
396 !this.heartbeatSetInterval
398 // eslint-disable-next-line @typescript-eslint/no-misused-promises
399 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
400 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.HEARTBEAT
);
401 }, this.getHeartbeatInterval());
404 ' Heartbeat started every ' +
405 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
407 } else if (this.heartbeatSetInterval
) {
410 ' Heartbeat already started every ' +
411 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
415 `${this.logPrefix()} Heartbeat interval set to ${
416 this.getHeartbeatInterval()
417 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
418 : this.getHeartbeatInterval()
419 }, not starting the heartbeat`
424 public restartHeartbeat(): void {
426 this.stopHeartbeat();
428 this.startHeartbeat();
431 public startMeterValues(connectorId
: number, interval
: number): void {
432 if (connectorId
=== 0) {
434 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
438 if (!this.getConnectorStatus(connectorId
)) {
440 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
444 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
446 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
450 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
451 !this.getConnectorStatus(connectorId
)?.transactionId
454 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
459 // eslint-disable-next-line @typescript-eslint/no-misused-promises
460 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
461 // eslint-disable-next-line @typescript-eslint/no-misused-promises
462 async (): Promise
<void> => {
463 // FIXME: Implement OCPP version agnostic helpers
464 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
467 this.getConnectorStatus(connectorId
).transactionId
,
470 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.METER_VALUES
, {
472 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
473 meterValue
: [meterValue
],
480 `${this.logPrefix()} Charging station ${
481 StandardParametersKey.MeterValueSampleInterval
482 } configuration set to ${
483 interval ? Utils.formatDurationMilliSeconds(interval) : interval
484 }, not sending MeterValues`
489 public start(): void {
490 if (this.getEnableStatistics()) {
491 this.performanceStatistics
.start();
493 this.openWSConnection();
494 // Monitor authorization file
495 this.startAuthorizationFileMonitoring();
496 // Monitor station template file
497 this.startStationTemplateFileMonitoring();
498 // Handle WebSocket message
499 this.wsConnection
.on(
501 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
503 // Handle WebSocket error
504 this.wsConnection
.on(
506 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
508 // Handle WebSocket close
509 this.wsConnection
.on(
511 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
513 // Handle WebSocket open
514 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
515 // Handle WebSocket ping
516 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
517 // Handle WebSocket pong
518 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
519 parentPort
.postMessage({
520 id
: ChargingStationWorkerMessageEvents
.STARTED
,
521 data
: { id
: this.stationInfo
.chargingStationId
},
525 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
526 // Stop message sequence
527 await this.stopMessageSequence(reason
);
528 for (const connectorId
of this.connectors
.keys()) {
529 if (connectorId
> 0) {
530 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
532 status: ChargePointStatus
.UNAVAILABLE
,
533 errorCode
: ChargePointErrorCode
.NO_ERROR
,
535 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
538 if (this.isWebSocketConnectionOpened()) {
539 this.wsConnection
.close();
541 if (this.getEnableStatistics()) {
542 this.performanceStatistics
.stop();
544 this.bootNotificationResponse
= null;
545 parentPort
.postMessage({
546 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
547 data
: { id
: this.stationInfo
.chargingStationId
},
552 public getConfigurationKey(
553 key
: string | StandardParametersKey
,
554 caseInsensitive
= false
555 ): ConfigurationKey
| undefined {
556 return this.configuration
.configurationKey
.find((configElement
) => {
557 if (caseInsensitive
) {
558 return configElement
.key
.toLowerCase() === key
.toLowerCase();
560 return configElement
.key
=== key
;
564 public addConfigurationKey(
565 key
: string | StandardParametersKey
,
567 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
573 const keyFound
= this.getConfigurationKey(key
);
574 const readonly = options
.readonly;
575 const visible
= options
.visible
;
576 const reboot
= options
.reboot
;
578 this.configuration
.configurationKey
.push({
587 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
593 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
594 const keyFound
= this.getConfigurationKey(key
);
596 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
597 this.configuration
.configurationKey
[keyIndex
].value
= value
;
598 this.saveConfiguration();
601 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
607 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
608 let cpReplaced
= false;
609 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
610 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
611 (chargingProfile
: ChargingProfile
, index
: number) => {
613 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
614 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
615 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
617 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
623 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
626 public resetConnectorStatus(connectorId
: number): void {
627 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
628 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
629 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
630 this.getConnectorStatus(connectorId
).transactionStarted
= false;
631 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
632 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
633 delete this.getConnectorStatus(connectorId
).transactionId
;
634 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
635 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
636 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
637 this.stopMeterValues(connectorId
);
640 public bufferMessage(message
: string): void {
641 this.messageBuffer
.add(message
);
644 private flushMessageBuffer() {
645 if (this.messageBuffer
.size
> 0) {
646 this.messageBuffer
.forEach((message
) => {
647 // TODO: evaluate the need to track performance
648 this.wsConnection
.send(message
);
649 this.messageBuffer
.delete(message
);
654 private getSupervisionUrlOcppConfiguration(): boolean {
655 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
658 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
659 // In case of multiple instances: add instance index to charging station id
660 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
661 const idSuffix
= stationTemplate
.nameSuffix
?? '';
662 const idStr
= '000000000' + this.index
.toString();
663 return stationTemplate
.fixedName
664 ? stationTemplate
.baseName
665 : stationTemplate
.baseName
+
667 instanceIndex
.toString() +
668 idStr
.substring(idStr
.length
- 4) +
672 private buildStationInfo(): ChargingStationInfo
{
673 let stationTemplateFromFile
: ChargingStationTemplate
;
675 // Load template file
676 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
677 stationTemplateFromFile
= JSON
.parse(
678 fs
.readFileSync(fileDescriptor
, 'utf8')
679 ) as ChargingStationTemplate
;
680 fs
.closeSync(fileDescriptor
);
682 FileUtils
.handleFileException(
685 this.stationTemplateFile
,
686 error
as NodeJS
.ErrnoException
689 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
690 // Deprecation template keys section
691 this.warnDeprecatedTemplateKey(
692 stationTemplateFromFile
,
695 "Use 'supervisionUrls' instead"
697 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
698 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? ({} as ChargingStationInfo
);
699 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
700 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
701 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
702 const powerArrayRandomIndex
= Math.floor(
703 Utils
.secureRandom() * stationTemplateFromFile
.power
.length
705 stationInfo
.maxPower
=
706 stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
707 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
708 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
710 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
711 stationInfo
.maxPower
=
712 stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
713 ? stationTemplateFromFile
.power
* 1000
714 : stationTemplateFromFile
.power
;
716 delete stationInfo
.power
;
717 delete stationInfo
.powerUnit
;
718 stationInfo
.chargingStationId
= chargingStationId
;
719 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
720 ? stationTemplateFromFile
.resetTime
* 1000
721 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
725 private getOcppVersion(): OCPPVersion
{
726 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
729 private handleUnsupportedVersion(version
: OCPPVersion
) {
730 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
731 this.stationTemplateFile
733 logger
.error(errMsg
);
734 throw new Error(errMsg
);
737 private initialize(): void {
738 this.stationInfo
= this.buildStationInfo();
739 this.configurationFile
= path
.join(
740 path
.resolve(__dirname
, '../'),
743 this.stationInfo
.chargingStationId
+ '.json'
745 this.configuration
= this.getConfiguration();
746 delete this.stationInfo
.Configuration
;
747 this.bootNotificationRequest
= {
748 chargePointModel
: this.stationInfo
.chargePointModel
,
749 chargePointVendor
: this.stationInfo
.chargePointVendor
,
750 ...(!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && {
751 chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
,
753 ...(!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && {
754 firmwareVersion
: this.stationInfo
.firmwareVersion
,
757 // Build connectors if needed
758 const maxConnectors
= this.getMaxNumberOfConnectors();
759 if (maxConnectors
<= 0) {
761 `${this.logPrefix()} Charging station template ${
762 this.stationTemplateFile
763 } with ${maxConnectors} connectors`
766 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
767 if (templateMaxConnectors
<= 0) {
769 `${this.logPrefix()} Charging station template ${
770 this.stationTemplateFile
771 } with no connector configuration`
774 if (!this.stationInfo
.Connectors
[0]) {
776 `${this.logPrefix()} Charging station template ${
777 this.stationTemplateFile
778 } with no connector Id 0 configuration`
784 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
785 !this.stationInfo
.randomConnectors
788 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
789 this.stationTemplateFile
790 }, forcing random connector configurations affectation`
792 this.stationInfo
.randomConnectors
= true;
794 const connectorsConfigHash
= crypto
795 .createHash('sha256')
796 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
798 const connectorsConfigChanged
=
799 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
800 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
801 connectorsConfigChanged
&& this.connectors
.clear();
802 this.connectorsConfigurationHash
= connectorsConfigHash
;
803 // Add connector Id 0
804 let lastConnector
= '0';
805 for (lastConnector
in this.stationInfo
.Connectors
) {
806 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
808 lastConnectorId
=== 0 &&
809 this.getUseConnectorId0() &&
810 this.stationInfo
.Connectors
[lastConnector
]
814 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
816 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
817 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
818 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
822 // Generate all connectors
824 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
826 for (let index
= 1; index
<= maxConnectors
; index
++) {
827 const randConnectorId
= this.stationInfo
.randomConnectors
828 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
832 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
834 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
835 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
836 this.getConnectorStatus(index
).chargingProfiles
= [];
841 // Avoid duplication of connectors related information
842 delete this.stationInfo
.Connectors
;
843 // Initialize transaction attributes on connectors
844 for (const connectorId
of this.connectors
.keys()) {
845 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
846 this.initializeConnectorStatus(connectorId
);
849 this.wsConfiguredConnectionUrl
= new URL(
850 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
852 switch (this.getOcppVersion()) {
853 case OCPPVersion
.VERSION_16
:
854 this.ocppIncomingRequestService
=
855 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
856 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
858 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
862 this.handleUnsupportedVersion(this.getOcppVersion());
866 this.initOcppParameters();
867 if (this.stationInfo
.autoRegister
) {
868 this.bootNotificationResponse
= {
869 currentTime
: new Date().toISOString(),
870 interval
: this.getHeartbeatInterval() / 1000,
871 status: RegistrationStatus
.ACCEPTED
,
874 this.stationInfo
.powerDivider
= this.getPowerDivider();
875 if (this.getEnableStatistics()) {
876 this.performanceStatistics
= PerformanceStatistics
.getInstance(
878 this.stationInfo
.chargingStationId
,
884 private initOcppParameters(): void {
886 this.getSupervisionUrlOcppConfiguration() &&
887 !this.getConfigurationKey(
888 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
891 this.addConfigurationKey(
892 VendorDefaultParametersKey
.ConnectionUrl
,
893 this.getConfiguredSupervisionUrl().href
,
897 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
898 this.addConfigurationKey(
899 StandardParametersKey
.SupportedFeatureProfiles
,
900 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
903 this.addConfigurationKey(
904 StandardParametersKey
.NumberOfConnectors
,
905 this.getNumberOfConnectors().toString(),
908 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
909 this.addConfigurationKey(
910 StandardParametersKey
.MeterValuesSampledData
,
911 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
914 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
915 const connectorPhaseRotation
= [];
916 for (const connectorId
of this.connectors
.keys()) {
918 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
919 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
920 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
921 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
923 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
924 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
925 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
926 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
929 this.addConfigurationKey(
930 StandardParametersKey
.ConnectorPhaseRotation
,
931 connectorPhaseRotation
.toString()
934 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
935 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
938 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
939 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(
940 SupportedFeatureProfiles
.Local_Auth_List_Management
943 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
945 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
946 this.addConfigurationKey(
947 StandardParametersKey
.ConnectionTimeOut
,
948 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
951 this.saveConfiguration();
954 private getConfigurationFromTemplate(): ChargingStationConfiguration
{
955 return this.stationInfo
.Configuration
?? ({} as ChargingStationConfiguration
);
958 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
959 let configuration
: ChargingStationConfiguration
= null;
960 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
962 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'r');
963 configuration
= JSON
.parse(
964 fs
.readFileSync(fileDescriptor
, 'utf8')
965 ) as ChargingStationConfiguration
;
966 fs
.closeSync(fileDescriptor
);
968 FileUtils
.handleFileException(
971 this.configurationFile
,
972 error
as NodeJS
.ErrnoException
976 return configuration
;
979 private saveConfiguration(): void {
980 if (this.configurationFile
) {
982 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
983 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
985 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
986 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(this.configuration
, null, 2));
987 fs
.closeSync(fileDescriptor
);
989 FileUtils
.handleFileException(
992 this.configurationFile
,
993 error
as NodeJS
.ErrnoException
998 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1003 private getConfiguration(): ChargingStationConfiguration
{
1004 let configuration
: ChargingStationConfiguration
= this.getConfigurationFromFile();
1005 if (!configuration
) {
1006 configuration
= this.getConfigurationFromTemplate();
1008 return configuration
;
1011 private async onOpen(): Promise
<void> {
1013 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1015 if (!this.isInAcceptedState()) {
1016 // Send BootNotification
1017 let registrationRetryCount
= 0;
1019 this.bootNotificationResponse
= (await this.ocppRequestService
.sendMessageHandler(
1020 RequestCommand
.BOOT_NOTIFICATION
,
1022 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1023 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1024 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1025 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1026 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1027 iccid
: this.bootNotificationRequest
.iccid
,
1028 imsi
: this.bootNotificationRequest
.imsi
,
1029 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1030 meterType
: this.bootNotificationRequest
.meterType
,
1032 { skipBufferingOnError
: true }
1033 )) as BootNotificationResponse
;
1034 if (!this.isInAcceptedState()) {
1035 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1037 this.bootNotificationResponse
?.interval
1038 ? this.bootNotificationResponse
.interval
* 1000
1039 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1043 !this.isInAcceptedState() &&
1044 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1045 this.getRegistrationMaxRetries() === -1)
1048 if (this.isInAcceptedState()) {
1049 await this.startMessageSequence();
1050 this.stopped
&& (this.stopped
= false);
1051 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
1052 this.flushMessageBuffer();
1056 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1059 this.autoReconnectRetryCount
= 0;
1060 this.wsConnectionRestarted
= false;
1063 private async onClose(code
: number, reason
: string): Promise
<void> {
1066 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1067 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1069 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1071 )}' and reason '${reason}'`
1073 this.autoReconnectRetryCount
= 0;
1078 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1080 )}' and reason '${reason}'`
1082 await this.reconnect(code
);
1087 private async onMessage(data
: Data
): Promise
<void> {
1088 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1091 '' as IncomingRequestCommand
,
1095 let responseCallback
: (
1096 payload
: JsonType
| string,
1097 requestPayload
: JsonType
| OCPPError
1099 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1100 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1101 let requestPayload
: JsonType
| OCPPError
;
1102 let cachedRequest
: CachedRequest
;
1105 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
1106 if (Utils
.isIterable(request
)) {
1107 // Parse the message
1108 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
1110 throw new OCPPError(
1111 ErrorType
.PROTOCOL_ERROR
,
1112 'Incoming request is not iterable',
1116 // Check the Type of message
1117 switch (messageType
) {
1119 case MessageType
.CALL_MESSAGE
:
1120 if (this.getEnableStatistics()) {
1121 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1124 await this.ocppIncomingRequestService
.handleRequest(
1131 case MessageType
.CALL_RESULT_MESSAGE
:
1133 cachedRequest
= this.requests
.get(messageId
);
1134 if (Utils
.isIterable(cachedRequest
)) {
1135 [responseCallback
, , , requestPayload
] = cachedRequest
;
1137 throw new OCPPError(
1138 ErrorType
.PROTOCOL_ERROR
,
1139 `Cached request for message id ${messageId} response is not iterable`,
1143 if (!responseCallback
) {
1145 throw new OCPPError(
1146 ErrorType
.INTERNAL_ERROR
,
1147 `Response for unknown message id ${messageId}`,
1151 responseCallback(commandName
, requestPayload
);
1154 case MessageType
.CALL_ERROR_MESSAGE
:
1155 cachedRequest
= this.requests
.get(messageId
);
1156 if (Utils
.isIterable(cachedRequest
)) {
1157 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1159 throw new OCPPError(
1160 ErrorType
.PROTOCOL_ERROR
,
1161 `Cached request for message id ${messageId} error response is not iterable`
1164 if (!rejectCallback
) {
1166 throw new OCPPError(
1167 ErrorType
.INTERNAL_ERROR
,
1168 `Error response for unknown message id ${messageId}`,
1173 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
1178 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1179 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1180 logger
.error(errMsg
);
1181 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1186 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1189 this.requests
.get(messageId
),
1193 messageType
=== MessageType
.CALL_MESSAGE
&&
1194 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1198 private onPing(): void {
1199 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1202 private onPong(): void {
1203 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1206 private onError(error
: WSError
): void {
1207 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1210 private getAuthorizationFile(): string | undefined {
1212 this.stationInfo
.authorizationFile
&&
1214 path
.resolve(__dirname
, '../'),
1216 path
.basename(this.stationInfo
.authorizationFile
)
1221 private getAuthorizedTags(): string[] {
1222 let authorizedTags
: string[] = [];
1223 const authorizationFile
= this.getAuthorizationFile();
1224 if (authorizationFile
) {
1226 // Load authorization file
1227 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
1228 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
1229 fs
.closeSync(fileDescriptor
);
1231 FileUtils
.handleFileException(
1235 error
as NodeJS
.ErrnoException
1241 ' No authorization file given in template file ' +
1242 this.stationTemplateFile
1245 return authorizedTags
;
1248 private getUseConnectorId0(): boolean | undefined {
1249 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1250 ? this.stationInfo
.useConnectorId0
1254 private getNumberOfRunningTransactions(): number {
1256 for (const connectorId
of this.connectors
.keys()) {
1257 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1265 private getConnectionTimeout(): number | undefined {
1266 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1268 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1269 Constants
.DEFAULT_CONNECTION_TIMEOUT
1272 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1275 // -1 for unlimited, 0 for disabling
1276 private getAutoReconnectMaxRetries(): number | undefined {
1277 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1278 return this.stationInfo
.autoReconnectMaxRetries
;
1280 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1281 return Configuration
.getAutoReconnectMaxRetries();
1287 private getRegistrationMaxRetries(): number | undefined {
1288 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1289 return this.stationInfo
.registrationMaxRetries
;
1294 private getPowerDivider(): number {
1295 let powerDivider
= this.getNumberOfConnectors();
1296 if (this.stationInfo
.powerSharedByConnectors
) {
1297 powerDivider
= this.getNumberOfRunningTransactions();
1299 return powerDivider
;
1302 private getTemplateMaxNumberOfConnectors(): number {
1303 return Object.keys(this.stationInfo
.Connectors
).length
;
1306 private getMaxNumberOfConnectors(): number {
1307 let maxConnectors
: number;
1308 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1309 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1310 // Distribute evenly the number of connectors
1311 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1312 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1313 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1315 maxConnectors
= this.stationInfo
.Connectors
[0]
1316 ? this.getTemplateMaxNumberOfConnectors() - 1
1317 : this.getTemplateMaxNumberOfConnectors();
1319 return maxConnectors
;
1322 private async startMessageSequence(): Promise
<void> {
1323 if (this.stationInfo
.autoRegister
) {
1324 await this.ocppRequestService
.sendMessageHandler(
1325 RequestCommand
.BOOT_NOTIFICATION
,
1327 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1328 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1329 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1330 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1331 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1332 iccid
: this.bootNotificationRequest
.iccid
,
1333 imsi
: this.bootNotificationRequest
.imsi
,
1334 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1335 meterType
: this.bootNotificationRequest
.meterType
,
1337 { skipBufferingOnError
: true }
1340 // Start WebSocket ping
1341 this.startWebSocketPing();
1343 this.startHeartbeat();
1344 // Initialize connectors status
1345 for (const connectorId
of this.connectors
.keys()) {
1346 if (connectorId
=== 0) {
1350 !this.getConnectorStatus(connectorId
)?.status &&
1351 this.getConnectorStatus(connectorId
)?.bootStatus
1353 // Send status in template at startup
1354 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1356 status: this.getConnectorStatus(connectorId
).bootStatus
,
1357 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1359 this.getConnectorStatus(connectorId
).status =
1360 this.getConnectorStatus(connectorId
).bootStatus
;
1363 this.getConnectorStatus(connectorId
)?.status &&
1364 this.getConnectorStatus(connectorId
)?.bootStatus
1366 // Send status in template after reset
1367 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1369 status: this.getConnectorStatus(connectorId
).bootStatus
,
1370 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1372 this.getConnectorStatus(connectorId
).status =
1373 this.getConnectorStatus(connectorId
).bootStatus
;
1374 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1375 // Send previous status at template reload
1376 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1378 status: this.getConnectorStatus(connectorId
).status,
1379 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1382 // Send default status
1383 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1385 status: ChargePointStatus
.AVAILABLE
,
1386 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1388 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1392 this.startAutomaticTransactionGenerator();
1395 private startAutomaticTransactionGenerator() {
1396 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1397 if (!this.automaticTransactionGenerator
) {
1398 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1400 if (!this.automaticTransactionGenerator
.started
) {
1401 this.automaticTransactionGenerator
.start();
1406 private async stopMessageSequence(
1407 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1409 // Stop WebSocket ping
1410 this.stopWebSocketPing();
1412 this.stopHeartbeat();
1415 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1416 this.automaticTransactionGenerator
?.started
1418 this.automaticTransactionGenerator
.stop();
1420 for (const connectorId
of this.connectors
.keys()) {
1421 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1422 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1424 this.getBeginEndMeterValues() &&
1425 this.getOcppStrictCompliance() &&
1426 !this.getOutOfOrderEndMeterValues()
1428 // FIXME: Implement OCPP version agnostic helpers
1429 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1432 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1434 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.METER_VALUES
, {
1437 meterValue
: transactionEndMeterValue
,
1440 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STOP_TRANSACTION
, {
1442 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1443 idTag
: this.getTransactionIdTag(transactionId
),
1451 private startWebSocketPing(): void {
1452 const webSocketPingInterval
: number = this.getConfigurationKey(
1453 StandardParametersKey
.WebSocketPingInterval
1455 ? Utils
.convertToInt(
1456 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1459 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1460 this.webSocketPingSetInterval
= setInterval(() => {
1461 if (this.isWebSocketConnectionOpened()) {
1462 this.wsConnection
.ping((): void => {
1463 /* This is intentional */
1466 }, webSocketPingInterval
* 1000);
1469 ' WebSocket ping started every ' +
1470 Utils
.formatDurationSeconds(webSocketPingInterval
)
1472 } else if (this.webSocketPingSetInterval
) {
1475 ' WebSocket ping every ' +
1476 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1481 `${this.logPrefix()} WebSocket ping interval set to ${
1482 webSocketPingInterval
1483 ? Utils.formatDurationSeconds(webSocketPingInterval)
1484 : webSocketPingInterval
1485 }, not starting the WebSocket ping`
1490 private stopWebSocketPing(): void {
1491 if (this.webSocketPingSetInterval
) {
1492 clearInterval(this.webSocketPingSetInterval
);
1496 private warnDeprecatedTemplateKey(
1497 template
: ChargingStationTemplate
,
1499 chargingStationId
: string,
1502 if (!Utils
.isUndefined(template
[key
])) {
1503 const logPrefixStr
= ` ${chargingStationId} |`;
1505 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1506 this.stationTemplateFile
1507 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1512 private convertDeprecatedTemplateKey(
1513 template
: ChargingStationTemplate
,
1514 deprecatedKey
: string,
1517 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1518 template
[key
] = template
[deprecatedKey
] as unknown
;
1519 delete template
[deprecatedKey
];
1523 private getConfiguredSupervisionUrl(): URL
{
1524 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1525 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1527 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1529 switch (Configuration
.getSupervisionUrlDistribution()) {
1530 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1531 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1533 case SupervisionUrlDistribution
.RANDOM
:
1535 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1537 case SupervisionUrlDistribution
.SEQUENTIAL
:
1538 if (this.index
<= supervisionUrls
.length
) {
1539 urlIndex
= this.index
- 1;
1542 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1548 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1549 SupervisionUrlDistribution.ROUND_ROBIN
1552 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1555 return new URL(supervisionUrls
[urlIndex
]);
1557 return new URL(supervisionUrls
as string);
1560 private getHeartbeatInterval(): number | undefined {
1561 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
1562 if (HeartbeatInterval
) {
1563 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1565 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
1566 if (HeartBeatInterval
) {
1567 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1569 !this.stationInfo
.autoRegister
&&
1571 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1572 Constants.DEFAULT_HEARTBEAT_INTERVAL
1575 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1578 private stopHeartbeat(): void {
1579 if (this.heartbeatSetInterval
) {
1580 clearInterval(this.heartbeatSetInterval
);
1584 private openWSConnection(
1585 options
: ClientOptions
& ClientRequestArgs
= this.stationInfo
.wsOptions
,
1586 forceCloseOpened
= false
1588 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1590 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1591 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1593 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1595 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1596 this.wsConnection
.close();
1598 let protocol
: string;
1599 switch (this.getOcppVersion()) {
1600 case OCPPVersion
.VERSION_16
:
1601 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1604 this.handleUnsupportedVersion(this.getOcppVersion());
1607 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1609 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1613 private stopMeterValues(connectorId
: number) {
1614 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1615 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1619 private startAuthorizationFileMonitoring(): void {
1620 const authorizationFile
= this.getAuthorizationFile();
1621 if (authorizationFile
) {
1623 fs
.watch(authorizationFile
, (event
, filename
) => {
1624 if (filename
&& event
=== 'change') {
1628 ' Authorization file ' +
1630 ' have changed, reload'
1632 // Initialize authorizedTags
1633 this.authorizedTags
= this.getAuthorizedTags();
1635 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
1640 FileUtils
.handleFileException(
1644 error
as NodeJS
.ErrnoException
1650 ' No authorization file given in template file ' +
1651 this.stationTemplateFile
+
1652 '. Not monitoring changes'
1657 private startStationTemplateFileMonitoring(): void {
1659 fs
.watch(this.stationTemplateFile
, (event
, filename
): void => {
1660 if (filename
&& event
=== 'change') {
1665 this.stationTemplateFile
+
1666 ' have changed, reload'
1672 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1673 this.automaticTransactionGenerator
1675 this.automaticTransactionGenerator
.stop();
1677 this.startAutomaticTransactionGenerator();
1678 if (this.getEnableStatistics()) {
1679 this.performanceStatistics
.restart();
1681 this.performanceStatistics
.stop();
1683 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1686 this.logPrefix() + ' Charging station template file monitoring error: %j',
1693 FileUtils
.handleFileException(
1696 this.stationTemplateFile
,
1697 error
as NodeJS
.ErrnoException
1702 private getReconnectExponentialDelay(): boolean | undefined {
1703 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1704 ? this.stationInfo
.reconnectExponentialDelay
1708 private async reconnect(code
: number): Promise
<void> {
1709 // Stop WebSocket ping
1710 this.stopWebSocketPing();
1712 this.stopHeartbeat();
1713 // Stop the ATG if needed
1715 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1716 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1717 this.automaticTransactionGenerator
?.started
1719 this.automaticTransactionGenerator
.stop();
1722 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1723 this.getAutoReconnectMaxRetries() === -1
1725 this.autoReconnectRetryCount
++;
1726 const reconnectDelay
= this.getReconnectExponentialDelay()
1727 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1728 : this.getConnectionTimeout() * 1000;
1729 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1731 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1734 )}ms, timeout ${reconnectTimeout}ms`
1736 await Utils
.sleep(reconnectDelay
);
1739 ' WebSocket: reconnecting try #' +
1740 this.autoReconnectRetryCount
.toString()
1742 this.openWSConnection(
1743 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
1746 this.wsConnectionRestarted
= true;
1747 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1749 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1750 this.autoReconnectRetryCount
1751 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1756 private initializeConnectorStatus(connectorId
: number): void {
1757 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1758 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1759 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1760 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1761 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1762 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;