1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
6 BootNotificationRequest
,
9 IncomingRequestCommand
,
11 } from
'../types/ocpp/Requests';
13 BootNotificationResponse
,
17 StatusNotificationResponse
,
18 } from
'../types/ocpp/Responses';
19 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
20 import ChargingStationOcppConfiguration
, {
22 } from
'../types/ChargingStationOcppConfiguration';
23 import ChargingStationTemplate
, {
29 } from
'../types/ChargingStationTemplate';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { MeterValue
, MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
37 import { StopTransactionReason
, StopTransactionResponse
} from
'../types/ocpp/Transaction';
38 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
39 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
41 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
42 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
43 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
44 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
45 import ChargingStationInfo from
'../types/ChargingStationInfo';
46 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
47 import Configuration from
'../utils/Configuration';
48 import { ConnectorStatus
} from
'../types/ConnectorStatus';
49 import Constants from
'../utils/Constants';
50 import { ErrorType
} from
'../types/ocpp/ErrorType';
51 import { FileType
} from
'../types/FileType';
52 import FileUtils from
'../utils/FileUtils';
53 import { JsonType
} from
'../types/JsonType';
54 import { MessageType
} from
'../types/ocpp/MessageType';
55 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
56 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
57 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
58 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
59 import OCPPError from
'../exception/OCPPError';
60 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
61 import OCPPRequestService from
'./ocpp/OCPPRequestService';
62 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
63 import PerformanceStatistics from
'../performance/PerformanceStatistics';
64 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
65 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
66 import { URL
} from
'url';
67 import Utils from
'../utils/Utils';
68 import crypto from
'crypto';
70 import logger from
'../utils/Logger';
71 import { parentPort
} from
'worker_threads';
72 import path from
'path';
74 export default class ChargingStation
{
75 public hashId
!: string;
76 public readonly templateFile
: string;
77 public authorizedTags
: string[];
78 public stationInfo
!: ChargingStationInfo
;
79 public readonly connectors
: Map
<number, ConnectorStatus
>;
80 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
81 public wsConnection
!: WebSocket
;
82 public readonly requests
: Map
<string, CachedRequest
>;
83 public performanceStatistics
!: PerformanceStatistics
;
84 public heartbeatSetInterval
!: NodeJS
.Timeout
;
85 public ocppRequestService
!: OCPPRequestService
;
86 public bootNotificationResponse
!: BootNotificationResponse
| null;
87 private readonly index
: number;
88 private configurationFile
!: string;
89 private bootNotificationRequest
!: BootNotificationRequest
;
90 private connectorsConfigurationHash
!: string;
91 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
92 private readonly messageBuffer
: Set
<string>;
93 private wsConfiguredConnectionUrl
!: URL
;
94 private wsConnectionRestarted
: boolean;
95 private stopped
: boolean;
96 private autoReconnectRetryCount
: number;
97 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
98 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
100 constructor(index
: number, templateFile
: string) {
102 this.templateFile
= templateFile
;
103 this.stopped
= false;
104 this.wsConnectionRestarted
= false;
105 this.autoReconnectRetryCount
= 0;
106 this.connectors
= new Map
<number, ConnectorStatus
>();
107 this.requests
= new Map
<string, CachedRequest
>();
108 this.messageBuffer
= new Set
<string>();
110 this.authorizedTags
= this.getAuthorizedTags();
113 private get
wsConnectionUrl(): URL
{
114 return this.getSupervisionUrlOcppConfiguration()
116 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value
+
118 this.stationInfo
.chargingStationId
120 : this.wsConfiguredConnectionUrl
;
123 public logPrefix(): string {
124 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
127 public getBootNotificationRequest(): BootNotificationRequest
{
128 return this.bootNotificationRequest
;
131 public getRandomIdTag(): string {
132 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
133 return this.authorizedTags
[index
];
136 public hasAuthorizedTags(): boolean {
137 return !Utils
.isEmptyArray(this.authorizedTags
);
140 public getEnableStatistics(): boolean | undefined {
141 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
142 ? this.stationInfo
.enableStatistics
146 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
147 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
150 public getNumberOfPhases(): number | undefined {
151 switch (this.getCurrentOutType()) {
153 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
154 ? this.stationInfo
.numberOfPhases
161 public isWebSocketConnectionOpened(): boolean {
162 return this?.wsConnection
?.readyState
=== OPEN
;
165 public getRegistrationStatus(): RegistrationStatus
{
166 return this?.bootNotificationResponse
?.status;
169 public isInUnknownState(): boolean {
170 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
173 public isInPendingState(): boolean {
174 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
177 public isInAcceptedState(): boolean {
178 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
181 public isInRejectedState(): boolean {
182 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
185 public isRegistered(): boolean {
186 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
189 public isChargingStationAvailable(): boolean {
190 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
193 public isConnectorAvailable(id
: number): boolean {
194 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
197 public getNumberOfConnectors(): number {
198 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
201 public getConnectorStatus(id
: number): ConnectorStatus
{
202 return this.connectors
.get(id
);
205 public getCurrentOutType(): CurrentType
| undefined {
206 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
209 public getOcppStrictCompliance(): boolean {
210 return this.stationInfo
.ocppStrictCompliance
?? false;
213 public getVoltageOut(): number | undefined {
214 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
216 }, cannot define default voltage out`;
217 let defaultVoltageOut
: number;
218 switch (this.getCurrentOutType()) {
220 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
223 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
226 logger
.error(errMsg
);
227 throw new Error(errMsg
);
229 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
230 ? this.stationInfo
.voltageOut
234 public getMaximumConfiguredPower(): number | undefined {
235 let maximumConfiguredPower
=
236 (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
237 if (this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
) {
238 maximumConfiguredPower
=
239 this.getCurrentOutType() === CurrentType
.AC
240 ? ACElectricUtils
.powerTotal(
241 this.getNumberOfPhases(),
242 this.getVoltageOut(),
243 this.getAmperageLimitation()
245 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation());
247 return maximumConfiguredPower
;
250 public getTransactionIdTag(transactionId
: number): string | undefined {
251 for (const connectorId
of this.connectors
.keys()) {
252 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
253 return this.getConnectorStatus(connectorId
).transactionIdTag
;
258 public getOutOfOrderEndMeterValues(): boolean {
259 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
262 public getBeginEndMeterValues(): boolean {
263 return this.stationInfo
.beginEndMeterValues
?? false;
266 public getMeteringPerTransaction(): boolean {
267 return this.stationInfo
.meteringPerTransaction
?? true;
270 public getTransactionDataMeterValues(): boolean {
271 return this.stationInfo
.transactionDataMeterValues
?? false;
274 public getMainVoltageMeterValues(): boolean {
275 return this.stationInfo
.mainVoltageMeterValues
?? true;
278 public getPhaseLineToLineVoltageMeterValues(): boolean {
279 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
282 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
283 for (const connectorId
of this.connectors
.keys()) {
286 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
293 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
294 const transactionConnectorStatus
= this.getConnectorStatus(
295 this.getConnectorIdByTransactionId(transactionId
)
297 if (this.getMeteringPerTransaction()) {
298 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
300 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
303 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
304 const connectorStatus
= this.getConnectorStatus(connectorId
);
305 if (this.getMeteringPerTransaction()) {
306 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
308 return connectorStatus
?.energyActiveImportRegisterValue
;
311 public getAuthorizeRemoteTxRequests(): boolean {
312 const authorizeRemoteTxRequests
= this.getConfigurationKey(
313 StandardParametersKey
.AuthorizeRemoteTxRequests
315 return authorizeRemoteTxRequests
316 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
320 public getLocalAuthListEnabled(): boolean {
321 const localAuthListEnabled
= this.getConfigurationKey(
322 StandardParametersKey
.LocalAuthListEnabled
324 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
327 public restartWebSocketPing(): void {
328 // Stop WebSocket ping
329 this.stopWebSocketPing();
330 // Start WebSocket ping
331 this.startWebSocketPing();
334 public getSampledValueTemplate(
336 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
337 phase
?: MeterValuePhase
338 ): SampledValueTemplate
| undefined {
339 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
340 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
342 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
347 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
348 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
353 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
354 StandardParametersKey.MeterValuesSampledData
359 const sampledValueTemplates
: SampledValueTemplate
[] =
360 this.getConnectorStatus(connectorId
).MeterValues
;
363 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
367 !Constants
.SUPPORTED_MEASURANDS
.includes(
368 sampledValueTemplates
[index
]?.measurand
??
369 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
373 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
377 sampledValueTemplates
[index
]?.phase
=== phase
&&
378 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
379 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
383 return sampledValueTemplates
[index
];
386 !sampledValueTemplates
[index
].phase
&&
387 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
388 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
392 return sampledValueTemplates
[index
];
394 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
395 (!sampledValueTemplates
[index
].measurand
||
396 sampledValueTemplates
[index
].measurand
=== measurand
)
398 return sampledValueTemplates
[index
];
401 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
402 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
403 logger
.error(errorMsg
);
404 throw new Error(errorMsg
);
407 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
411 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
412 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
415 public startHeartbeat(): void {
417 this.getHeartbeatInterval() &&
418 this.getHeartbeatInterval() > 0 &&
419 !this.heartbeatSetInterval
421 // eslint-disable-next-line @typescript-eslint/no-misused-promises
422 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
423 await this.ocppRequestService
.sendMessageHandler
<HeartbeatResponse
>(
424 RequestCommand
.HEARTBEAT
426 }, this.getHeartbeatInterval());
429 ' Heartbeat started every ' +
430 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
432 } else if (this.heartbeatSetInterval
) {
435 ' Heartbeat already started every ' +
436 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
440 `${this.logPrefix()} Heartbeat interval set to ${
441 this.getHeartbeatInterval()
442 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
443 : this.getHeartbeatInterval()
444 }, not starting the heartbeat`
449 public restartHeartbeat(): void {
451 this.stopHeartbeat();
453 this.startHeartbeat();
456 public startMeterValues(connectorId
: number, interval
: number): void {
457 if (connectorId
=== 0) {
459 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
463 if (!this.getConnectorStatus(connectorId
)) {
465 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
469 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
471 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
475 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
476 !this.getConnectorStatus(connectorId
)?.transactionId
479 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
484 // eslint-disable-next-line @typescript-eslint/no-misused-promises
485 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
486 // eslint-disable-next-line @typescript-eslint/no-misused-promises
487 async (): Promise
<void> => {
488 // FIXME: Implement OCPP version agnostic helpers
489 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
492 this.getConnectorStatus(connectorId
).transactionId
,
495 await this.ocppRequestService
.sendMessageHandler
<MeterValuesResponse
>(
496 RequestCommand
.METER_VALUES
,
499 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
500 meterValue
: [meterValue
],
508 `${this.logPrefix()} Charging station ${
509 StandardParametersKey.MeterValueSampleInterval
510 } configuration set to ${
511 interval ? Utils.formatDurationMilliSeconds(interval) : interval
512 }, not sending MeterValues`
517 public start(): void {
518 if (this.getEnableStatistics()) {
519 this.performanceStatistics
.start();
521 this.openWSConnection();
522 // Monitor authorization file
523 FileUtils
.watchJsonFile
<string[]>(
525 FileType
.Authorization
,
526 this.getAuthorizationFile(),
529 // Monitor charging station template file
530 FileUtils
.watchJsonFile(
532 FileType
.ChargingStationTemplate
,
535 (event
, filename
): void => {
536 if (filename
&& event
=== 'change') {
539 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
541 } file have changed, reload`
547 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
548 this.automaticTransactionGenerator
550 this.automaticTransactionGenerator
.stop();
552 this.startAutomaticTransactionGenerator();
553 if (this.getEnableStatistics()) {
554 this.performanceStatistics
.restart();
556 this.performanceStatistics
.stop();
558 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
561 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
568 // Handle WebSocket message
569 this.wsConnection
.on(
571 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
573 // Handle WebSocket error
574 this.wsConnection
.on(
576 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
578 // Handle WebSocket close
579 this.wsConnection
.on(
581 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
583 // Handle WebSocket open
584 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
585 // Handle WebSocket ping
586 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
587 // Handle WebSocket pong
588 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
589 parentPort
.postMessage({
590 id
: ChargingStationWorkerMessageEvents
.STARTED
,
591 data
: { id
: this.stationInfo
.chargingStationId
},
595 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
596 // Stop message sequence
597 await this.stopMessageSequence(reason
);
598 for (const connectorId
of this.connectors
.keys()) {
599 if (connectorId
> 0) {
600 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
601 RequestCommand
.STATUS_NOTIFICATION
,
604 status: ChargePointStatus
.UNAVAILABLE
,
605 errorCode
: ChargePointErrorCode
.NO_ERROR
,
608 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
611 if (this.isWebSocketConnectionOpened()) {
612 this.wsConnection
.close();
614 if (this.getEnableStatistics()) {
615 this.performanceStatistics
.stop();
617 this.bootNotificationResponse
= null;
618 parentPort
.postMessage({
619 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
620 data
: { id
: this.stationInfo
.chargingStationId
},
625 public getConfigurationKey(
626 key
: string | StandardParametersKey
,
627 caseInsensitive
= false
628 ): ConfigurationKey
| undefined {
629 return this.ocppConfiguration
.configurationKey
.find((configElement
) => {
630 if (caseInsensitive
) {
631 return configElement
.key
.toLowerCase() === key
.toLowerCase();
633 return configElement
.key
=== key
;
637 public addConfigurationKey(
638 key
: string | StandardParametersKey
,
640 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
645 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
647 options
= options
?? ({} as { readonly?: boolean; visible
?: boolean; reboot
?: boolean });
648 options
.readonly = options
?.readonly ?? false;
649 options
.visible
= options
?.visible
?? true;
650 options
.reboot
= options
?.reboot
?? false;
651 let keyFound
= this.getConfigurationKey(key
);
652 if (keyFound
&& params
?.overwrite
) {
653 this.deleteConfigurationKey(keyFound
.key
, { save
: false });
654 keyFound
= undefined;
657 this.ocppConfiguration
.configurationKey
.push({
659 readonly: options
.readonly,
661 visible
: options
.visible
,
662 reboot
: options
.reboot
,
664 params
?.save
&& this.saveOcppConfiguration();
667 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
673 public setConfigurationKeyValue(
674 key
: string | StandardParametersKey
,
676 caseInsensitive
= false
678 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
680 this.ocppConfiguration
.configurationKey
[
681 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
)
683 this.saveOcppConfiguration();
686 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
692 public deleteConfigurationKey(
693 key
: string | StandardParametersKey
,
694 params
: { save
?: boolean; caseInsensitive
?: boolean } = { save
: true, caseInsensitive
: false }
695 ): ConfigurationKey
[] {
696 const keyFound
= this.getConfigurationKey(key
, params
?.caseInsensitive
);
698 const deletedConfigurationKey
= this.ocppConfiguration
.configurationKey
.splice(
699 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
),
702 params
?.save
&& this.saveOcppConfiguration();
703 return deletedConfigurationKey
;
707 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
708 let cpReplaced
= false;
709 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
710 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
711 (chargingProfile
: ChargingProfile
, index
: number) => {
713 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
714 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
715 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
717 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
723 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
726 public resetConnectorStatus(connectorId
: number): void {
727 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
728 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
729 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
730 this.getConnectorStatus(connectorId
).transactionStarted
= false;
731 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
732 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
733 delete this.getConnectorStatus(connectorId
).transactionId
;
734 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
735 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
736 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
737 this.stopMeterValues(connectorId
);
740 public bufferMessage(message
: string): void {
741 this.messageBuffer
.add(message
);
744 private flushMessageBuffer() {
745 if (this.messageBuffer
.size
> 0) {
746 this.messageBuffer
.forEach((message
) => {
747 // TODO: evaluate the need to track performance
748 this.wsConnection
.send(message
);
749 this.messageBuffer
.delete(message
);
754 private getSupervisionUrlOcppConfiguration(): boolean {
755 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
758 private getSupervisionUrlOcppKey(): string {
759 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
762 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
763 // In case of multiple instances: add instance index to charging station id
764 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
765 const idSuffix
= stationTemplate
.nameSuffix
?? '';
766 const idStr
= '000000000' + this.index
.toString();
767 return stationTemplate
.fixedName
768 ? stationTemplate
.baseName
769 : stationTemplate
.baseName
+
771 instanceIndex
.toString() +
772 idStr
.substring(idStr
.length
- 4) +
776 private getRandomSerialNumberSuffix(params
?: {
777 randomBytesLength
?: number;
780 const randomSerialNumberSuffix
= crypto
781 .randomBytes(params
?.randomBytesLength
?? 16)
783 if (params
?.upperCase
) {
784 return randomSerialNumberSuffix
.toUpperCase();
786 return randomSerialNumberSuffix
;
789 private getTemplateFromFile(): ChargingStationTemplate
| null {
790 let template
: ChargingStationTemplate
= null;
792 const measureId
= `${FileType.ChargingStationTemplate} read`;
793 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
794 template
= JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
795 PerformanceStatistics
.endMeasure(measureId
, beginId
);
797 FileUtils
.handleFileException(
799 FileType
.ChargingStationTemplate
,
801 error
as NodeJS
.ErrnoException
807 private createSerialNumber(
808 stationInfo
: ChargingStationInfo
,
809 existingStationInfo
?: ChargingStationInfo
,
810 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
811 randomSerialNumberUpperCase
: true,
812 randomSerialNumber
: true,
815 params
= params
?? {};
816 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
817 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
818 if (existingStationInfo
) {
819 existingStationInfo
?.chargePointSerialNumber
&&
820 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
821 existingStationInfo
?.chargeBoxSerialNumber
&&
822 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
824 const serialNumberSuffix
= params
?.randomSerialNumber
825 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
827 stationInfo
.chargePointSerialNumber
=
828 stationInfo
?.chargePointSerialNumberPrefix
&&
829 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
830 stationInfo
.chargeBoxSerialNumber
=
831 stationInfo
?.chargeBoxSerialNumberPrefix
&&
832 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
836 private getStationInfoFromTemplate(): ChargingStationInfo
{
837 const stationInfo
: ChargingStationInfo
=
838 this.getTemplateFromFile() ?? ({} as ChargingStationInfo
);
839 stationInfo
.hash
= crypto
840 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
841 .update(JSON
.stringify(stationInfo
))
843 const chargingStationId
= this.getChargingStationId(stationInfo
);
844 // Deprecation template keys section
845 this.warnDeprecatedTemplateKey(
849 "Use 'supervisionUrls' instead"
851 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
852 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
853 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
854 stationInfo
.power
= stationInfo
.power
as number[];
855 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
856 stationInfo
.maximumPower
=
857 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
858 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
859 : stationInfo
.power
[powerArrayRandomIndex
];
861 stationInfo
.power
= stationInfo
.power
as number;
862 stationInfo
.maximumPower
=
863 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
864 ? stationInfo
.power
* 1000
867 delete stationInfo
.power
;
868 delete stationInfo
.powerUnit
;
869 stationInfo
.chargingStationId
= chargingStationId
;
870 stationInfo
.resetTime
= stationInfo
.resetTime
871 ? stationInfo
.resetTime
* 1000
872 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
876 private getStationInfoFromFile(): ChargingStationInfo
| null {
877 return this.getConfigurationFromFile()?.stationInfo
?? null;
880 private getStationInfo(): ChargingStationInfo
{
881 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
882 this.hashId
= this.getHashId(stationInfoFromTemplate
);
883 this.configurationFile
= path
.join(
884 path
.resolve(__dirname
, '../'),
887 this.hashId
+ '.json'
889 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
890 if (stationInfoFromFile
?.hash
=== stationInfoFromTemplate
.hash
) {
891 return stationInfoFromFile
;
893 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
894 return stationInfoFromTemplate
;
897 private saveStationInfo(): void {
898 this.saveConfiguration(Section
.stationInfo
);
901 private getOcppVersion(): OCPPVersion
{
902 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
905 private getOcppPersistentConfiguration(): boolean {
906 return this.stationInfo
.ocppPersistentConfiguration
?? true;
909 private handleUnsupportedVersion(version
: OCPPVersion
) {
910 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
913 logger
.error(errMsg
);
914 throw new Error(errMsg
);
917 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
919 chargePointModel
: stationInfo
.chargePointModel
,
920 chargePointVendor
: stationInfo
.chargePointVendor
,
921 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
922 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
924 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
925 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
927 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
928 firmwareVersion
: stationInfo
.firmwareVersion
,
930 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
931 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
932 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
933 meterSerialNumber
: stationInfo
.meterSerialNumber
,
935 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
936 meterType
: stationInfo
.meterType
,
941 private getHashId(stationInfo
: ChargingStationInfo
): string {
942 const hashBootNotificationRequest
= {
943 chargePointModel
: stationInfo
.chargePointModel
,
944 chargePointVendor
: stationInfo
.chargePointVendor
,
945 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
946 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
948 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
949 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
951 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
952 firmwareVersion
: stationInfo
.firmwareVersion
,
954 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
955 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
956 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
957 meterSerialNumber
: stationInfo
.meterSerialNumber
,
959 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
960 meterType
: stationInfo
.meterType
,
964 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
965 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
969 private initialize(): void {
970 this.stationInfo
= this.getStationInfo();
971 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
972 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
973 this.ocppConfiguration
= this.getOcppConfiguration();
974 delete this.stationInfo
.Configuration
;
975 // Build connectors if needed
976 const maxConnectors
= this.getMaxNumberOfConnectors();
977 if (maxConnectors
<= 0) {
979 `${this.logPrefix()} Charging station template ${
981 } with ${maxConnectors} connectors`
984 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
985 if (templateMaxConnectors
<= 0) {
987 `${this.logPrefix()} Charging station template ${
989 } with no connector configuration`
992 if (!this.stationInfo
.Connectors
[0]) {
994 `${this.logPrefix()} Charging station template ${
996 } with no connector Id 0 configuration`
1002 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
1003 !this.stationInfo
.randomConnectors
1006 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1008 }, forcing random connector configurations affectation`
1010 this.stationInfo
.randomConnectors
= true;
1012 const connectorsConfigHash
= crypto
1013 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1014 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
1016 const connectorsConfigChanged
=
1017 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1018 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1019 connectorsConfigChanged
&& this.connectors
.clear();
1020 this.connectorsConfigurationHash
= connectorsConfigHash
;
1021 // Add connector Id 0
1022 let lastConnector
= '0';
1023 for (lastConnector
in this.stationInfo
.Connectors
) {
1024 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1026 lastConnectorId
=== 0 &&
1027 this.getUseConnectorId0() &&
1028 this.stationInfo
.Connectors
[lastConnector
]
1030 this.connectors
.set(
1032 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
1034 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1035 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1036 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1040 // Generate all connectors
1042 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
1044 for (let index
= 1; index
<= maxConnectors
; index
++) {
1045 const randConnectorId
= this.stationInfo
.randomConnectors
1046 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1048 this.connectors
.set(
1050 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
1052 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1053 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1054 this.getConnectorStatus(index
).chargingProfiles
= [];
1059 // The connectors attribute need to be initialized
1060 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
1061 this.saveStationInfo();
1062 // Avoid duplication of connectors related information in RAM
1063 delete this.stationInfo
.Connectors
;
1064 // Initialize transaction attributes on connectors
1065 for (const connectorId
of this.connectors
.keys()) {
1066 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1067 this.initializeConnectorStatus(connectorId
);
1070 this.wsConfiguredConnectionUrl
= new URL(
1071 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1073 // OCPP configuration
1074 this.initializeOcppConfiguration();
1075 switch (this.getOcppVersion()) {
1076 case OCPPVersion
.VERSION_16
:
1077 this.ocppIncomingRequestService
=
1078 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
1079 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1081 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
1085 this.handleUnsupportedVersion(this.getOcppVersion());
1088 if (this.stationInfo
.autoRegister
) {
1089 this.bootNotificationResponse
= {
1090 currentTime
: new Date().toISOString(),
1091 interval
: this.getHeartbeatInterval() / 1000,
1092 status: RegistrationStatus
.ACCEPTED
,
1095 this.stationInfo
.powerDivider
= this.getPowerDivider();
1096 if (this.getEnableStatistics()) {
1097 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1099 this.stationInfo
.chargingStationId
,
1100 this.wsConnectionUrl
1105 private initializeOcppConfiguration(): void {
1107 this.getSupervisionUrlOcppConfiguration() &&
1108 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1110 this.addConfigurationKey(
1111 this.getSupervisionUrlOcppKey(),
1112 this.getConfiguredSupervisionUrl().href
,
1116 !this.getSupervisionUrlOcppConfiguration() &&
1117 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1119 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1122 this.stationInfo
.amperageLimitationOcppKey
&&
1123 !this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1125 this.addConfigurationKey(
1126 this.stationInfo
.amperageLimitationOcppKey
,
1127 (this.stationInfo
.maximumAmperage
* this.getAmperageLimitationUnitDivider()).toString()
1130 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1131 this.addConfigurationKey(
1132 StandardParametersKey
.SupportedFeatureProfiles
,
1133 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
1136 this.addConfigurationKey(
1137 StandardParametersKey
.NumberOfConnectors
,
1138 this.getNumberOfConnectors().toString(),
1142 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1143 this.addConfigurationKey(
1144 StandardParametersKey
.MeterValuesSampledData
,
1145 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1148 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1149 const connectorPhaseRotation
= [];
1150 for (const connectorId
of this.connectors
.keys()) {
1152 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1153 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1154 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1155 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1157 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1158 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1159 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1160 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1163 this.addConfigurationKey(
1164 StandardParametersKey
.ConnectorPhaseRotation
,
1165 connectorPhaseRotation
.toString()
1168 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1169 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1172 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1173 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(
1174 SupportedFeatureProfiles
.Local_Auth_List_Management
1177 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1179 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1180 this.addConfigurationKey(
1181 StandardParametersKey
.ConnectionTimeOut
,
1182 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1185 this.saveOcppConfiguration();
1188 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1189 let configuration
: ChargingStationConfiguration
= null;
1190 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1192 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1193 const beginId
= PerformanceStatistics
.beginMeasure(
1194 `${FileType.ChargingStationConfiguration} read`
1196 configuration
= JSON
.parse(
1197 fs
.readFileSync(this.configurationFile
, 'utf8')
1198 ) as ChargingStationConfiguration
;
1199 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1201 FileUtils
.handleFileException(
1203 FileType
.ChargingStationConfiguration
,
1204 this.configurationFile
,
1205 error
as NodeJS
.ErrnoException
1209 return configuration
;
1212 private saveConfiguration(section
?: Section
): void {
1213 if (this.configurationFile
) {
1215 const configurationData
: ChargingStationConfiguration
=
1216 this.getConfigurationFromFile() ?? {};
1217 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1218 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1221 case Section
.ocppConfiguration
:
1222 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1224 case Section
.stationInfo
:
1225 configurationData
.stationInfo
= this.stationInfo
;
1228 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1229 configurationData
.stationInfo
= this.stationInfo
;
1232 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1233 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1234 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1235 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1236 fs
.closeSync(fileDescriptor
);
1237 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1239 FileUtils
.handleFileException(
1241 FileType
.ChargingStationConfiguration
,
1242 this.configurationFile
,
1243 error
as NodeJS
.ErrnoException
1248 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1253 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1254 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1257 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1258 let configuration
: ChargingStationConfiguration
= null;
1259 if (this.getOcppPersistentConfiguration()) {
1260 const configurationFromFile
= this.getConfigurationFromFile();
1261 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1263 configuration
&& delete configuration
.stationInfo
;
1264 return configuration
;
1267 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1268 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1269 if (!ocppConfiguration
) {
1270 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1272 return ocppConfiguration
;
1275 private saveOcppConfiguration(): void {
1276 if (this.getOcppPersistentConfiguration()) {
1277 this.saveConfiguration(Section
.ocppConfiguration
);
1281 private async onOpen(): Promise
<void> {
1283 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1285 if (!this.isInAcceptedState()) {
1286 // Send BootNotification
1287 let registrationRetryCount
= 0;
1289 this.bootNotificationResponse
=
1290 await this.ocppRequestService
.sendMessageHandler
<BootNotificationResponse
>(
1291 RequestCommand
.BOOT_NOTIFICATION
,
1293 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1294 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1295 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1296 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1297 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1298 iccid
: this.bootNotificationRequest
.iccid
,
1299 imsi
: this.bootNotificationRequest
.imsi
,
1300 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1301 meterType
: this.bootNotificationRequest
.meterType
,
1303 { skipBufferingOnError
: true }
1305 if (!this.isInAcceptedState()) {
1306 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1308 this.bootNotificationResponse
?.interval
1309 ? this.bootNotificationResponse
.interval
* 1000
1310 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1314 !this.isInAcceptedState() &&
1315 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1316 this.getRegistrationMaxRetries() === -1)
1319 if (this.isInAcceptedState()) {
1320 await this.startMessageSequence();
1321 this.stopped
&& (this.stopped
= false);
1322 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
1323 this.flushMessageBuffer();
1327 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1330 this.autoReconnectRetryCount
= 0;
1331 this.wsConnectionRestarted
= false;
1334 private async onClose(code
: number, reason
: string): Promise
<void> {
1337 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1338 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1340 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1342 )}' and reason '${reason}'`
1344 this.autoReconnectRetryCount
= 0;
1349 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1351 )}' and reason '${reason}'`
1353 await this.reconnect(code
);
1358 private async onMessage(data
: Data
): Promise
<void> {
1359 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1362 '' as IncomingRequestCommand
,
1366 let responseCallback
: (
1367 payload
: JsonType
| string,
1368 requestPayload
: JsonType
| OCPPError
1370 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1371 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1372 let requestPayload
: JsonType
| OCPPError
;
1373 let cachedRequest
: CachedRequest
;
1376 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
1377 if (Utils
.isIterable(request
)) {
1378 // Parse the message
1379 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
1381 throw new OCPPError(
1382 ErrorType
.PROTOCOL_ERROR
,
1383 'Incoming request is not iterable',
1387 // Check the Type of message
1388 switch (messageType
) {
1390 case MessageType
.CALL_MESSAGE
:
1391 if (this.getEnableStatistics()) {
1392 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1395 await this.ocppIncomingRequestService
.handleRequest(
1402 case MessageType
.CALL_RESULT_MESSAGE
:
1404 cachedRequest
= this.requests
.get(messageId
);
1405 if (Utils
.isIterable(cachedRequest
)) {
1406 [responseCallback
, , , requestPayload
] = cachedRequest
;
1408 throw new OCPPError(
1409 ErrorType
.PROTOCOL_ERROR
,
1410 `Cached request for message id ${messageId} response is not iterable`,
1414 if (!responseCallback
) {
1416 throw new OCPPError(
1417 ErrorType
.INTERNAL_ERROR
,
1418 `Response for unknown message id ${messageId}`,
1422 responseCallback(commandName
, requestPayload
);
1425 case MessageType
.CALL_ERROR_MESSAGE
:
1426 cachedRequest
= this.requests
.get(messageId
);
1427 if (Utils
.isIterable(cachedRequest
)) {
1428 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1430 throw new OCPPError(
1431 ErrorType
.PROTOCOL_ERROR
,
1432 `Cached request for message id ${messageId} error response is not iterable`
1435 if (!rejectCallback
) {
1437 throw new OCPPError(
1438 ErrorType
.INTERNAL_ERROR
,
1439 `Error response for unknown message id ${messageId}`,
1444 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
1449 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1450 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1451 logger
.error(errMsg
);
1452 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1457 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1460 this.requests
.get(messageId
),
1464 messageType
=== MessageType
.CALL_MESSAGE
&&
1465 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1469 private onPing(): void {
1470 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1473 private onPong(): void {
1474 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1477 private onError(error
: WSError
): void {
1478 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1481 private getAuthorizationFile(): string | undefined {
1483 this.stationInfo
.authorizationFile
&&
1485 path
.resolve(__dirname
, '../'),
1487 path
.basename(this.stationInfo
.authorizationFile
)
1492 private getAuthorizedTags(): string[] {
1493 let authorizedTags
: string[] = [];
1494 const authorizationFile
= this.getAuthorizationFile();
1495 if (authorizationFile
) {
1497 // Load authorization file
1498 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1500 FileUtils
.handleFileException(
1502 FileType
.Authorization
,
1504 error
as NodeJS
.ErrnoException
1509 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1512 return authorizedTags
;
1515 private getUseConnectorId0(): boolean | undefined {
1516 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1517 ? this.stationInfo
.useConnectorId0
1521 private getNumberOfRunningTransactions(): number {
1523 for (const connectorId
of this.connectors
.keys()) {
1524 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1532 private getConnectionTimeout(): number | undefined {
1533 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1535 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1536 Constants
.DEFAULT_CONNECTION_TIMEOUT
1539 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1542 // -1 for unlimited, 0 for disabling
1543 private getAutoReconnectMaxRetries(): number | undefined {
1544 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1545 return this.stationInfo
.autoReconnectMaxRetries
;
1547 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1548 return Configuration
.getAutoReconnectMaxRetries();
1554 private getRegistrationMaxRetries(): number | undefined {
1555 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1556 return this.stationInfo
.registrationMaxRetries
;
1561 private getPowerDivider(): number {
1562 let powerDivider
= this.getNumberOfConnectors();
1563 if (this.stationInfo
.powerSharedByConnectors
) {
1564 powerDivider
= this.getNumberOfRunningTransactions();
1566 return powerDivider
;
1569 private getTemplateMaxNumberOfConnectors(): number {
1570 return Object.keys(this.stationInfo
.Connectors
).length
;
1573 private getMaxNumberOfConnectors(): number {
1574 let maxConnectors
: number;
1575 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1576 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1577 // Distribute evenly the number of connectors
1578 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1579 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1580 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1582 maxConnectors
= this.stationInfo
.Connectors
[0]
1583 ? this.getTemplateMaxNumberOfConnectors() - 1
1584 : this.getTemplateMaxNumberOfConnectors();
1586 return maxConnectors
;
1589 private getMaximumAmperage(): number | undefined {
1590 switch (this.getCurrentOutType()) {
1591 case CurrentType
.AC
:
1592 return ACElectricUtils
.amperagePerPhaseFromPower(
1593 this.getNumberOfPhases(),
1594 (this.stationInfo
['maxPower'] as number) ??
1595 this.stationInfo
.maximumPower
/ this.getNumberOfConnectors(),
1596 this.getVoltageOut()
1598 case CurrentType
.DC
:
1599 return DCElectricUtils
.amperage(this.stationInfo
.maximumPower
, this.getVoltageOut());
1603 private getAmperageLimitationUnitDivider(): number {
1604 let unitDivider
= 1;
1605 switch (this.stationInfo
.amperageLimitationUnit
) {
1606 case AmpereUnits
.DECI_AMPERE
:
1609 case AmpereUnits
.CENTI_AMPERE
:
1612 case AmpereUnits
.MILLI_AMPERE
:
1619 private getAmperageLimitation(): number | undefined {
1621 this.stationInfo
.amperageLimitationOcppKey
&&
1622 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1626 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
).value
1627 ) / this.getAmperageLimitationUnitDivider()
1632 private async startMessageSequence(): Promise
<void> {
1633 if (this.stationInfo
.autoRegister
) {
1634 await this.ocppRequestService
.sendMessageHandler
<BootNotificationResponse
>(
1635 RequestCommand
.BOOT_NOTIFICATION
,
1637 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1638 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1639 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1640 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1641 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1642 iccid
: this.bootNotificationRequest
.iccid
,
1643 imsi
: this.bootNotificationRequest
.imsi
,
1644 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1645 meterType
: this.bootNotificationRequest
.meterType
,
1647 { skipBufferingOnError
: true }
1650 // Start WebSocket ping
1651 this.startWebSocketPing();
1653 this.startHeartbeat();
1654 // Initialize connectors status
1655 for (const connectorId
of this.connectors
.keys()) {
1656 if (connectorId
=== 0) {
1660 !this.getConnectorStatus(connectorId
)?.status &&
1661 this.getConnectorStatus(connectorId
)?.bootStatus
1663 // Send status in template at startup
1664 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1665 RequestCommand
.STATUS_NOTIFICATION
,
1668 status: this.getConnectorStatus(connectorId
).bootStatus
,
1669 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1672 this.getConnectorStatus(connectorId
).status =
1673 this.getConnectorStatus(connectorId
).bootStatus
;
1676 this.getConnectorStatus(connectorId
)?.status &&
1677 this.getConnectorStatus(connectorId
)?.bootStatus
1679 // Send status in template after reset
1680 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1681 RequestCommand
.STATUS_NOTIFICATION
,
1684 status: this.getConnectorStatus(connectorId
).bootStatus
,
1685 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1688 this.getConnectorStatus(connectorId
).status =
1689 this.getConnectorStatus(connectorId
).bootStatus
;
1690 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1691 // Send previous status at template reload
1692 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1693 RequestCommand
.STATUS_NOTIFICATION
,
1696 status: this.getConnectorStatus(connectorId
).status,
1697 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1701 // Send default status
1702 await this.ocppRequestService
.sendMessageHandler
<StatusNotificationResponse
>(
1703 RequestCommand
.STATUS_NOTIFICATION
,
1706 status: ChargePointStatus
.AVAILABLE
,
1707 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1710 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1714 this.startAutomaticTransactionGenerator();
1717 private startAutomaticTransactionGenerator() {
1718 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1719 if (!this.automaticTransactionGenerator
) {
1720 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1722 if (!this.automaticTransactionGenerator
.started
) {
1723 this.automaticTransactionGenerator
.start();
1728 private async stopMessageSequence(
1729 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1731 // Stop WebSocket ping
1732 this.stopWebSocketPing();
1734 this.stopHeartbeat();
1737 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1738 this.automaticTransactionGenerator
?.started
1740 this.automaticTransactionGenerator
.stop();
1742 for (const connectorId
of this.connectors
.keys()) {
1743 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1744 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1746 this.getBeginEndMeterValues() &&
1747 this.getOcppStrictCompliance() &&
1748 !this.getOutOfOrderEndMeterValues()
1750 // FIXME: Implement OCPP version agnostic helpers
1751 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1754 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1756 await this.ocppRequestService
.sendMessageHandler
<MeterValuesResponse
>(
1757 RequestCommand
.METER_VALUES
,
1761 meterValue
: transactionEndMeterValue
,
1765 await this.ocppRequestService
.sendMessageHandler
<StopTransactionResponse
>(
1766 RequestCommand
.STOP_TRANSACTION
,
1769 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1770 idTag
: this.getTransactionIdTag(transactionId
),
1779 private startWebSocketPing(): void {
1780 const webSocketPingInterval
: number = this.getConfigurationKey(
1781 StandardParametersKey
.WebSocketPingInterval
1783 ? Utils
.convertToInt(
1784 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1787 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1788 this.webSocketPingSetInterval
= setInterval(() => {
1789 if (this.isWebSocketConnectionOpened()) {
1790 this.wsConnection
.ping((): void => {
1791 /* This is intentional */
1794 }, webSocketPingInterval
* 1000);
1797 ' WebSocket ping started every ' +
1798 Utils
.formatDurationSeconds(webSocketPingInterval
)
1800 } else if (this.webSocketPingSetInterval
) {
1803 ' WebSocket ping every ' +
1804 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1809 `${this.logPrefix()} WebSocket ping interval set to ${
1810 webSocketPingInterval
1811 ? Utils.formatDurationSeconds(webSocketPingInterval)
1812 : webSocketPingInterval
1813 }, not starting the WebSocket ping`
1818 private stopWebSocketPing(): void {
1819 if (this.webSocketPingSetInterval
) {
1820 clearInterval(this.webSocketPingSetInterval
);
1824 private warnDeprecatedTemplateKey(
1825 template
: ChargingStationTemplate
,
1827 chargingStationId
: string,
1830 if (!Utils
.isUndefined(template
[key
])) {
1831 const logPrefixStr
= ` ${chargingStationId} |`;
1833 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1835 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1840 private convertDeprecatedTemplateKey(
1841 template
: ChargingStationTemplate
,
1842 deprecatedKey
: string,
1845 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1846 template
[key
] = template
[deprecatedKey
] as unknown
;
1847 delete template
[deprecatedKey
];
1851 private getConfiguredSupervisionUrl(): URL
{
1852 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1853 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1855 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1857 switch (Configuration
.getSupervisionUrlDistribution()) {
1858 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1859 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1861 case SupervisionUrlDistribution
.RANDOM
:
1863 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1865 case SupervisionUrlDistribution
.SEQUENTIAL
:
1866 if (this.index
<= supervisionUrls
.length
) {
1867 urlIndex
= this.index
- 1;
1870 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1876 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1877 SupervisionUrlDistribution.ROUND_ROBIN
1880 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1883 return new URL(supervisionUrls
[urlIndex
]);
1885 return new URL(supervisionUrls
as string);
1888 private getHeartbeatInterval(): number | undefined {
1889 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
1890 if (HeartbeatInterval
) {
1891 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1893 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
1894 if (HeartBeatInterval
) {
1895 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1897 !this.stationInfo
.autoRegister
&&
1899 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1900 Constants.DEFAULT_HEARTBEAT_INTERVAL
1903 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1906 private stopHeartbeat(): void {
1907 if (this.heartbeatSetInterval
) {
1908 clearInterval(this.heartbeatSetInterval
);
1912 private openWSConnection(
1913 options
: WsOptions
= this.stationInfo
.wsOptions
,
1914 forceCloseOpened
= false
1916 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1918 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1919 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1921 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1923 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1924 this.wsConnection
.close();
1926 let protocol
: string;
1927 switch (this.getOcppVersion()) {
1928 case OCPPVersion
.VERSION_16
:
1929 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1932 this.handleUnsupportedVersion(this.getOcppVersion());
1935 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1937 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1941 private stopMeterValues(connectorId
: number) {
1942 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1943 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1947 private getReconnectExponentialDelay(): boolean | undefined {
1948 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1949 ? this.stationInfo
.reconnectExponentialDelay
1953 private async reconnect(code
: number): Promise
<void> {
1954 // Stop WebSocket ping
1955 this.stopWebSocketPing();
1957 this.stopHeartbeat();
1958 // Stop the ATG if needed
1960 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1961 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1962 this.automaticTransactionGenerator
?.started
1964 this.automaticTransactionGenerator
.stop();
1967 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1968 this.getAutoReconnectMaxRetries() === -1
1970 this.autoReconnectRetryCount
++;
1971 const reconnectDelay
= this.getReconnectExponentialDelay()
1972 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1973 : this.getConnectionTimeout() * 1000;
1974 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1976 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1979 )}ms, timeout ${reconnectTimeout}ms`
1981 await Utils
.sleep(reconnectDelay
);
1984 ' WebSocket: reconnecting try #' +
1985 this.autoReconnectRetryCount
.toString()
1987 this.openWSConnection(
1988 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
1991 this.wsConnectionRestarted
= true;
1992 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1994 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1995 this.autoReconnectRetryCount
1996 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2001 private initializeConnectorStatus(connectorId
: number): void {
2002 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2003 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2004 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2005 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2006 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2007 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;