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 bootNotificationRequest
!: BootNotificationRequest
;
78 private bootNotificationResponse
!: BootNotificationResponse
| null;
79 private connectorsConfigurationHash
!: string;
80 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
81 private readonly messageBuffer
: Set
<string>;
82 private wsConfiguredConnectionUrl
!: URL
;
83 private wsConnectionRestarted
: boolean;
84 private stopped
: boolean;
85 private autoReconnectRetryCount
: number;
86 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
87 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
89 constructor(index
: number, stationTemplateFile
: string) {
90 this.id
= Utils
.generateUUID();
92 this.stationTemplateFile
= stationTemplateFile
;
94 this.wsConnectionRestarted
= false;
95 this.autoReconnectRetryCount
= 0;
96 this.connectors
= new Map
<number, ConnectorStatus
>();
97 this.requests
= new Map
<string, CachedRequest
>();
98 this.messageBuffer
= new Set
<string>();
100 this.authorizedTags
= this.getAuthorizedTags();
103 get
wsConnectionUrl(): URL
{
104 return this.getSupervisionUrlOcppConfiguration()
106 this.getConfigurationKey(
107 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
110 this.stationInfo
.chargingStationId
112 : this.wsConfiguredConnectionUrl
;
115 public logPrefix(): string {
116 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
119 public getBootNotificationRequest(): BootNotificationRequest
{
120 return this.bootNotificationRequest
;
123 public getRandomIdTag(): string {
124 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
125 return this.authorizedTags
[index
];
128 public hasAuthorizedTags(): boolean {
129 return !Utils
.isEmptyArray(this.authorizedTags
);
132 public getEnableStatistics(): boolean | undefined {
133 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
134 ? this.stationInfo
.enableStatistics
138 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
139 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
142 public getNumberOfPhases(): number | undefined {
143 switch (this.getCurrentOutType()) {
145 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
146 ? this.stationInfo
.numberOfPhases
153 public isWebSocketConnectionOpened(): boolean {
154 return this?.wsConnection
?.readyState
=== OPEN
;
157 public getRegistrationStatus(): RegistrationStatus
{
158 return this?.bootNotificationResponse
?.status;
161 public isInUnknownState(): boolean {
162 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
165 public isInPendingState(): boolean {
166 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
169 public isInAcceptedState(): boolean {
170 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
173 public isInRejectedState(): boolean {
174 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
177 public isRegistered(): boolean {
178 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
181 public isChargingStationAvailable(): boolean {
182 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
185 public isConnectorAvailable(id
: number): boolean {
186 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
189 public getNumberOfConnectors(): number {
190 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
193 public getConnectorStatus(id
: number): ConnectorStatus
{
194 return this.connectors
.get(id
);
197 public getCurrentOutType(): CurrentType
| undefined {
198 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
201 public getOcppStrictCompliance(): boolean {
202 return this.stationInfo
.ocppStrictCompliance
?? false;
205 public getVoltageOut(): number | undefined {
206 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
207 this.stationTemplateFile
208 }, cannot define default voltage out`;
209 let defaultVoltageOut
: number;
210 switch (this.getCurrentOutType()) {
212 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
215 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
218 logger
.error(errMsg
);
219 throw new Error(errMsg
);
221 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
222 ? this.stationInfo
.voltageOut
226 public getTransactionIdTag(transactionId
: number): string | undefined {
227 for (const connectorId
of this.connectors
.keys()) {
228 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
229 return this.getConnectorStatus(connectorId
).transactionIdTag
;
234 public getOutOfOrderEndMeterValues(): boolean {
235 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
238 public getBeginEndMeterValues(): boolean {
239 return this.stationInfo
.beginEndMeterValues
?? false;
242 public getMeteringPerTransaction(): boolean {
243 return this.stationInfo
.meteringPerTransaction
?? true;
246 public getTransactionDataMeterValues(): boolean {
247 return this.stationInfo
.transactionDataMeterValues
?? false;
250 public getMainVoltageMeterValues(): boolean {
251 return this.stationInfo
.mainVoltageMeterValues
?? true;
254 public getPhaseLineToLineVoltageMeterValues(): boolean {
255 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
258 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
259 if (this.getMeteringPerTransaction()) {
260 for (const connectorId
of this.connectors
.keys()) {
263 this.getConnectorStatus(connectorId
).transactionId
=== transactionId
265 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
269 for (const connectorId
of this.connectors
.keys()) {
270 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
271 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
276 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
277 if (this.getMeteringPerTransaction()) {
278 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
280 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
283 public getAuthorizeRemoteTxRequests(): boolean {
284 const authorizeRemoteTxRequests
= this.getConfigurationKey(
285 StandardParametersKey
.AuthorizeRemoteTxRequests
287 return authorizeRemoteTxRequests
288 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
292 public getLocalAuthListEnabled(): boolean {
293 const localAuthListEnabled
= this.getConfigurationKey(
294 StandardParametersKey
.LocalAuthListEnabled
296 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
299 public restartWebSocketPing(): void {
300 // Stop WebSocket ping
301 this.stopWebSocketPing();
302 // Start WebSocket ping
303 this.startWebSocketPing();
306 public getSampledValueTemplate(
308 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
309 phase
?: MeterValuePhase
310 ): SampledValueTemplate
| undefined {
311 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
312 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
314 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
319 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
320 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
325 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
326 StandardParametersKey.MeterValuesSampledData
331 const sampledValueTemplates
: SampledValueTemplate
[] =
332 this.getConnectorStatus(connectorId
).MeterValues
;
335 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
339 !Constants
.SUPPORTED_MEASURANDS
.includes(
340 sampledValueTemplates
[index
]?.measurand
??
341 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
345 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
349 sampledValueTemplates
[index
]?.phase
=== phase
&&
350 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
351 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
355 return sampledValueTemplates
[index
];
358 !sampledValueTemplates
[index
].phase
&&
359 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
360 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(
364 return sampledValueTemplates
[index
];
366 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
367 (!sampledValueTemplates
[index
].measurand
||
368 sampledValueTemplates
[index
].measurand
=== measurand
)
370 return sampledValueTemplates
[index
];
373 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
374 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
375 logger
.error(errorMsg
);
376 throw new Error(errorMsg
);
379 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
383 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
384 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
387 public startHeartbeat(): void {
389 this.getHeartbeatInterval() &&
390 this.getHeartbeatInterval() > 0 &&
391 !this.heartbeatSetInterval
393 // eslint-disable-next-line @typescript-eslint/no-misused-promises
394 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
395 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.HEARTBEAT
);
396 }, this.getHeartbeatInterval());
399 ' Heartbeat started every ' +
400 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
402 } else if (this.heartbeatSetInterval
) {
405 ' Heartbeat already started every ' +
406 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
410 `${this.logPrefix()} Heartbeat interval set to ${
411 this.getHeartbeatInterval()
412 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
413 : this.getHeartbeatInterval()
414 }, not starting the heartbeat`
419 public restartHeartbeat(): void {
421 this.stopHeartbeat();
423 this.startHeartbeat();
426 public startMeterValues(connectorId
: number, interval
: number): void {
427 if (connectorId
=== 0) {
429 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
433 if (!this.getConnectorStatus(connectorId
)) {
435 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
439 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
441 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
445 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
446 !this.getConnectorStatus(connectorId
)?.transactionId
449 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
454 // eslint-disable-next-line @typescript-eslint/no-misused-promises
455 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
456 // eslint-disable-next-line @typescript-eslint/no-misused-promises
457 async (): Promise
<void> => {
458 // FIXME: Implement OCPP version agnostic helpers
459 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
462 this.getConnectorStatus(connectorId
).transactionId
,
465 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.METER_VALUES
, {
467 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
468 meterValue
: [meterValue
],
475 `${this.logPrefix()} Charging station ${
476 StandardParametersKey.MeterValueSampleInterval
477 } configuration set to ${
478 interval ? Utils.formatDurationMilliSeconds(interval) : interval
479 }, not sending MeterValues`
484 public start(): void {
485 if (this.getEnableStatistics()) {
486 this.performanceStatistics
.start();
488 this.openWSConnection();
489 // Monitor authorization file
490 this.startAuthorizationFileMonitoring();
491 // Monitor station template file
492 this.startStationTemplateFileMonitoring();
493 // Handle WebSocket message
494 this.wsConnection
.on(
496 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
498 // Handle WebSocket error
499 this.wsConnection
.on(
501 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
503 // Handle WebSocket close
504 this.wsConnection
.on(
506 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
508 // Handle WebSocket open
509 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
510 // Handle WebSocket ping
511 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
512 // Handle WebSocket pong
513 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
514 parentPort
.postMessage({
515 id
: ChargingStationWorkerMessageEvents
.STARTED
,
516 data
: { id
: this.stationInfo
.chargingStationId
},
520 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
521 // Stop message sequence
522 await this.stopMessageSequence(reason
);
523 for (const connectorId
of this.connectors
.keys()) {
524 if (connectorId
> 0) {
525 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
527 status: ChargePointStatus
.UNAVAILABLE
,
528 errorCode
: ChargePointErrorCode
.NO_ERROR
,
530 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
533 if (this.isWebSocketConnectionOpened()) {
534 this.wsConnection
.close();
536 if (this.getEnableStatistics()) {
537 this.performanceStatistics
.stop();
539 this.bootNotificationResponse
= null;
540 parentPort
.postMessage({
541 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
542 data
: { id
: this.stationInfo
.chargingStationId
},
547 public getConfigurationKey(
548 key
: string | StandardParametersKey
,
549 caseInsensitive
= false
550 ): ConfigurationKey
| undefined {
551 return this.configuration
.configurationKey
.find((configElement
) => {
552 if (caseInsensitive
) {
553 return configElement
.key
.toLowerCase() === key
.toLowerCase();
555 return configElement
.key
=== key
;
559 public addConfigurationKey(
560 key
: string | StandardParametersKey
,
562 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
568 const keyFound
= this.getConfigurationKey(key
);
569 const readonly = options
.readonly;
570 const visible
= options
.visible
;
571 const reboot
= options
.reboot
;
573 this.configuration
.configurationKey
.push({
582 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
588 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
589 const keyFound
= this.getConfigurationKey(key
);
591 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
592 this.configuration
.configurationKey
[keyIndex
].value
= value
;
595 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
601 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
602 let cpReplaced
= false;
603 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
604 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
605 (chargingProfile
: ChargingProfile
, index
: number) => {
607 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
608 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
609 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
611 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
617 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
620 public resetConnectorStatus(connectorId
: number): void {
621 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
622 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
623 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
624 this.getConnectorStatus(connectorId
).transactionStarted
= false;
625 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
626 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
627 delete this.getConnectorStatus(connectorId
).transactionId
;
628 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
629 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
630 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
631 this.stopMeterValues(connectorId
);
634 public bufferMessage(message
: string): void {
635 this.messageBuffer
.add(message
);
638 private flushMessageBuffer() {
639 if (this.messageBuffer
.size
> 0) {
640 this.messageBuffer
.forEach((message
) => {
641 // TODO: evaluate the need to track performance
642 this.wsConnection
.send(message
);
643 this.messageBuffer
.delete(message
);
648 private getSupervisionUrlOcppConfiguration(): boolean {
649 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
652 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
653 // In case of multiple instances: add instance index to charging station id
654 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
655 const idSuffix
= stationTemplate
.nameSuffix
?? '';
656 const idStr
= '000000000' + this.index
.toString();
657 return stationTemplate
.fixedName
658 ? stationTemplate
.baseName
659 : stationTemplate
.baseName
+
661 instanceIndex
.toString() +
662 idStr
.substring(idStr
.length
- 4) +
666 private buildStationInfo(): ChargingStationInfo
{
667 let stationTemplateFromFile
: ChargingStationTemplate
;
669 // Load template file
670 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
671 stationTemplateFromFile
= JSON
.parse(
672 fs
.readFileSync(fileDescriptor
, 'utf8')
673 ) as ChargingStationTemplate
;
674 fs
.closeSync(fileDescriptor
);
676 FileUtils
.handleFileException(
679 this.stationTemplateFile
,
680 error
as NodeJS
.ErrnoException
683 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
684 // Deprecation template keys section
685 this.warnDeprecatedTemplateKey(
686 stationTemplateFromFile
,
689 "Use 'supervisionUrls' instead"
691 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
692 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? ({} as ChargingStationInfo
);
693 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
694 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
695 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
696 const powerArrayRandomIndex
= Math.floor(
697 Utils
.secureRandom() * stationTemplateFromFile
.power
.length
699 stationInfo
.maxPower
=
700 stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
701 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
702 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
704 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
705 stationInfo
.maxPower
=
706 stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
707 ? stationTemplateFromFile
.power
* 1000
708 : stationTemplateFromFile
.power
;
710 delete stationInfo
.power
;
711 delete stationInfo
.powerUnit
;
712 stationInfo
.chargingStationId
= chargingStationId
;
713 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
714 ? stationTemplateFromFile
.resetTime
* 1000
715 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
719 private getOcppVersion(): OCPPVersion
{
720 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
723 private handleUnsupportedVersion(version
: OCPPVersion
) {
724 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
725 this.stationTemplateFile
727 logger
.error(errMsg
);
728 throw new Error(errMsg
);
731 private initialize(): void {
732 this.stationInfo
= this.buildStationInfo();
733 this.configuration
= this.getTemplateChargingStationConfiguration();
734 delete this.stationInfo
.Configuration
;
735 this.bootNotificationRequest
= {
736 chargePointModel
: this.stationInfo
.chargePointModel
,
737 chargePointVendor
: this.stationInfo
.chargePointVendor
,
738 ...(!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && {
739 chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
,
741 ...(!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && {
742 firmwareVersion
: this.stationInfo
.firmwareVersion
,
745 // Build connectors if needed
746 const maxConnectors
= this.getMaxNumberOfConnectors();
747 if (maxConnectors
<= 0) {
749 `${this.logPrefix()} Charging station template ${
750 this.stationTemplateFile
751 } with ${maxConnectors} connectors`
754 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
755 if (templateMaxConnectors
<= 0) {
757 `${this.logPrefix()} Charging station template ${
758 this.stationTemplateFile
759 } with no connector configuration`
762 if (!this.stationInfo
.Connectors
[0]) {
764 `${this.logPrefix()} Charging station template ${
765 this.stationTemplateFile
766 } with no connector Id 0 configuration`
772 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
773 !this.stationInfo
.randomConnectors
776 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
777 this.stationTemplateFile
778 }, forcing random connector configurations affectation`
780 this.stationInfo
.randomConnectors
= true;
782 const connectorsConfigHash
= crypto
783 .createHash('sha256')
784 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
786 const connectorsConfigChanged
=
787 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
788 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
789 connectorsConfigChanged
&& this.connectors
.clear();
790 this.connectorsConfigurationHash
= connectorsConfigHash
;
791 // Add connector Id 0
792 let lastConnector
= '0';
793 for (lastConnector
in this.stationInfo
.Connectors
) {
794 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
796 lastConnectorId
=== 0 &&
797 this.getUseConnectorId0() &&
798 this.stationInfo
.Connectors
[lastConnector
]
802 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
804 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
805 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
806 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
810 // Generate all connectors
812 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
814 for (let index
= 1; index
<= maxConnectors
; index
++) {
815 const randConnectorId
= this.stationInfo
.randomConnectors
816 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
820 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
822 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
823 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
824 this.getConnectorStatus(index
).chargingProfiles
= [];
829 // Avoid duplication of connectors related information
830 delete this.stationInfo
.Connectors
;
831 // Initialize transaction attributes on connectors
832 for (const connectorId
of this.connectors
.keys()) {
833 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
834 this.initializeConnectorStatus(connectorId
);
837 this.wsConfiguredConnectionUrl
= new URL(
838 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
840 switch (this.getOcppVersion()) {
841 case OCPPVersion
.VERSION_16
:
842 this.ocppIncomingRequestService
=
843 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
844 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
846 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
850 this.handleUnsupportedVersion(this.getOcppVersion());
854 this.initOcppParameters();
855 if (this.stationInfo
.autoRegister
) {
856 this.bootNotificationResponse
= {
857 currentTime
: new Date().toISOString(),
858 interval
: this.getHeartbeatInterval() / 1000,
859 status: RegistrationStatus
.ACCEPTED
,
862 this.stationInfo
.powerDivider
= this.getPowerDivider();
863 if (this.getEnableStatistics()) {
864 this.performanceStatistics
= PerformanceStatistics
.getInstance(
866 this.stationInfo
.chargingStationId
,
872 private initOcppParameters(): void {
874 this.getSupervisionUrlOcppConfiguration() &&
875 !this.getConfigurationKey(
876 this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
879 this.addConfigurationKey(
880 VendorDefaultParametersKey
.ConnectionUrl
,
881 this.getConfiguredSupervisionUrl().href
,
885 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
886 this.addConfigurationKey(
887 StandardParametersKey
.SupportedFeatureProfiles
,
888 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
891 this.addConfigurationKey(
892 StandardParametersKey
.NumberOfConnectors
,
893 this.getNumberOfConnectors().toString(),
896 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
897 this.addConfigurationKey(
898 StandardParametersKey
.MeterValuesSampledData
,
899 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
902 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
903 const connectorPhaseRotation
= [];
904 for (const connectorId
of this.connectors
.keys()) {
906 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
907 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
908 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
909 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
911 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
912 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
913 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
914 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
917 this.addConfigurationKey(
918 StandardParametersKey
.ConnectorPhaseRotation
,
919 connectorPhaseRotation
.toString()
922 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
923 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
926 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
927 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(
928 SupportedFeatureProfiles
.Local_Auth_List_Management
931 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
933 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
934 this.addConfigurationKey(
935 StandardParametersKey
.ConnectionTimeOut
,
936 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
941 private async onOpen(): Promise
<void> {
943 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
945 if (!this.isInAcceptedState()) {
946 // Send BootNotification
947 let registrationRetryCount
= 0;
949 this.bootNotificationResponse
= (await this.ocppRequestService
.sendMessageHandler(
950 RequestCommand
.BOOT_NOTIFICATION
,
952 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
953 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
954 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
955 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
956 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
957 iccid
: this.bootNotificationRequest
.iccid
,
958 imsi
: this.bootNotificationRequest
.imsi
,
959 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
960 meterType
: this.bootNotificationRequest
.meterType
,
962 { skipBufferingOnError
: true }
963 )) as BootNotificationResponse
;
964 if (!this.isInAcceptedState()) {
965 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
967 this.bootNotificationResponse
?.interval
968 ? this.bootNotificationResponse
.interval
* 1000
969 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
973 !this.isInAcceptedState() &&
974 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
975 this.getRegistrationMaxRetries() === -1)
978 if (this.isInAcceptedState()) {
979 await this.startMessageSequence();
980 this.stopped
&& (this.stopped
= false);
981 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
982 this.flushMessageBuffer();
986 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
989 this.autoReconnectRetryCount
= 0;
990 this.wsConnectionRestarted
= false;
993 private async onClose(code
: number, reason
: string): Promise
<void> {
996 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
997 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
999 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1001 )}' and reason '${reason}'`
1003 this.autoReconnectRetryCount
= 0;
1008 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1010 )}' and reason '${reason}'`
1012 await this.reconnect(code
);
1017 private async onMessage(data
: Data
): Promise
<void> {
1018 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1021 '' as IncomingRequestCommand
,
1025 let responseCallback
: (
1026 payload
: JsonType
| string,
1027 requestPayload
: JsonType
| OCPPError
1029 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1030 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1031 let requestPayload
: JsonType
| OCPPError
;
1032 let cachedRequest
: CachedRequest
;
1035 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
1036 if (Utils
.isIterable(request
)) {
1037 // Parse the message
1038 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
1040 throw new OCPPError(
1041 ErrorType
.PROTOCOL_ERROR
,
1042 'Incoming request is not iterable',
1046 // Check the Type of message
1047 switch (messageType
) {
1049 case MessageType
.CALL_MESSAGE
:
1050 if (this.getEnableStatistics()) {
1051 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1054 await this.ocppIncomingRequestService
.handleRequest(
1061 case MessageType
.CALL_RESULT_MESSAGE
:
1063 cachedRequest
= this.requests
.get(messageId
);
1064 if (Utils
.isIterable(cachedRequest
)) {
1065 [responseCallback
, , , requestPayload
] = cachedRequest
;
1067 throw new OCPPError(
1068 ErrorType
.PROTOCOL_ERROR
,
1069 `Cached request for message id ${messageId} response is not iterable`,
1073 if (!responseCallback
) {
1075 throw new OCPPError(
1076 ErrorType
.INTERNAL_ERROR
,
1077 `Response for unknown message id ${messageId}`,
1081 responseCallback(commandName
, requestPayload
);
1084 case MessageType
.CALL_ERROR_MESSAGE
:
1085 cachedRequest
= this.requests
.get(messageId
);
1086 if (Utils
.isIterable(cachedRequest
)) {
1087 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1089 throw new OCPPError(
1090 ErrorType
.PROTOCOL_ERROR
,
1091 `Cached request for message id ${messageId} error response is not iterable`
1094 if (!rejectCallback
) {
1096 throw new OCPPError(
1097 ErrorType
.INTERNAL_ERROR
,
1098 `Error response for unknown message id ${messageId}`,
1103 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
1108 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1109 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1110 logger
.error(errMsg
);
1111 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1116 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1119 this.requests
.get(messageId
),
1123 messageType
=== MessageType
.CALL_MESSAGE
&&
1124 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1128 private onPing(): void {
1129 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1132 private onPong(): void {
1133 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1136 private onError(error
: WSError
): void {
1137 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1140 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
1141 return this.stationInfo
.Configuration
?? ({} as ChargingStationConfiguration
);
1144 private getAuthorizationFile(): string | undefined {
1146 this.stationInfo
.authorizationFile
&&
1148 path
.resolve(__dirname
, '../'),
1150 path
.basename(this.stationInfo
.authorizationFile
)
1155 private getAuthorizedTags(): string[] {
1156 let authorizedTags
: string[] = [];
1157 const authorizationFile
= this.getAuthorizationFile();
1158 if (authorizationFile
) {
1160 // Load authorization file
1161 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
1162 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
1163 fs
.closeSync(fileDescriptor
);
1165 FileUtils
.handleFileException(
1169 error
as NodeJS
.ErrnoException
1175 ' No authorization file given in template file ' +
1176 this.stationTemplateFile
1179 return authorizedTags
;
1182 private getUseConnectorId0(): boolean | undefined {
1183 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1184 ? this.stationInfo
.useConnectorId0
1188 private getNumberOfRunningTransactions(): number {
1190 for (const connectorId
of this.connectors
.keys()) {
1191 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1199 private getConnectionTimeout(): number | undefined {
1200 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1202 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1203 Constants
.DEFAULT_CONNECTION_TIMEOUT
1206 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1209 // -1 for unlimited, 0 for disabling
1210 private getAutoReconnectMaxRetries(): number | undefined {
1211 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1212 return this.stationInfo
.autoReconnectMaxRetries
;
1214 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1215 return Configuration
.getAutoReconnectMaxRetries();
1221 private getRegistrationMaxRetries(): number | undefined {
1222 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1223 return this.stationInfo
.registrationMaxRetries
;
1228 private getPowerDivider(): number {
1229 let powerDivider
= this.getNumberOfConnectors();
1230 if (this.stationInfo
.powerSharedByConnectors
) {
1231 powerDivider
= this.getNumberOfRunningTransactions();
1233 return powerDivider
;
1236 private getTemplateMaxNumberOfConnectors(): number {
1237 return Object.keys(this.stationInfo
.Connectors
).length
;
1240 private getMaxNumberOfConnectors(): number {
1241 let maxConnectors
: number;
1242 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1243 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1244 // Distribute evenly the number of connectors
1245 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1246 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1247 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1249 maxConnectors
= this.stationInfo
.Connectors
[0]
1250 ? this.getTemplateMaxNumberOfConnectors() - 1
1251 : this.getTemplateMaxNumberOfConnectors();
1253 return maxConnectors
;
1256 private async startMessageSequence(): Promise
<void> {
1257 if (this.stationInfo
.autoRegister
) {
1258 await this.ocppRequestService
.sendMessageHandler(
1259 RequestCommand
.BOOT_NOTIFICATION
,
1261 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1262 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1263 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1264 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1265 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1266 iccid
: this.bootNotificationRequest
.iccid
,
1267 imsi
: this.bootNotificationRequest
.imsi
,
1268 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1269 meterType
: this.bootNotificationRequest
.meterType
,
1271 { skipBufferingOnError
: true }
1274 // Start WebSocket ping
1275 this.startWebSocketPing();
1277 this.startHeartbeat();
1278 // Initialize connectors status
1279 for (const connectorId
of this.connectors
.keys()) {
1280 if (connectorId
=== 0) {
1284 !this.getConnectorStatus(connectorId
)?.status &&
1285 this.getConnectorStatus(connectorId
)?.bootStatus
1287 // Send status in template at startup
1288 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1290 status: this.getConnectorStatus(connectorId
).bootStatus
,
1291 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1293 this.getConnectorStatus(connectorId
).status =
1294 this.getConnectorStatus(connectorId
).bootStatus
;
1297 this.getConnectorStatus(connectorId
)?.status &&
1298 this.getConnectorStatus(connectorId
)?.bootStatus
1300 // Send status in template after reset
1301 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1303 status: this.getConnectorStatus(connectorId
).bootStatus
,
1304 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1306 this.getConnectorStatus(connectorId
).status =
1307 this.getConnectorStatus(connectorId
).bootStatus
;
1308 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1309 // Send previous status at template reload
1310 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1312 status: this.getConnectorStatus(connectorId
).status,
1313 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1316 // Send default status
1317 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STATUS_NOTIFICATION
, {
1319 status: ChargePointStatus
.AVAILABLE
,
1320 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1322 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1326 this.startAutomaticTransactionGenerator();
1329 private startAutomaticTransactionGenerator() {
1330 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1331 if (!this.automaticTransactionGenerator
) {
1332 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1334 if (!this.automaticTransactionGenerator
.started
) {
1335 this.automaticTransactionGenerator
.start();
1340 private async stopMessageSequence(
1341 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1343 // Stop WebSocket ping
1344 this.stopWebSocketPing();
1346 this.stopHeartbeat();
1349 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1350 this.automaticTransactionGenerator
?.started
1352 this.automaticTransactionGenerator
.stop();
1354 for (const connectorId
of this.connectors
.keys()) {
1355 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1356 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1358 this.getBeginEndMeterValues() &&
1359 this.getOcppStrictCompliance() &&
1360 !this.getOutOfOrderEndMeterValues()
1362 // FIXME: Implement OCPP version agnostic helpers
1363 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1366 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1368 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.METER_VALUES
, {
1371 meterValue
: transactionEndMeterValue
,
1374 await this.ocppRequestService
.sendMessageHandler(RequestCommand
.STOP_TRANSACTION
, {
1376 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1377 idTag
: this.getTransactionIdTag(transactionId
),
1385 private startWebSocketPing(): void {
1386 const webSocketPingInterval
: number = this.getConfigurationKey(
1387 StandardParametersKey
.WebSocketPingInterval
1389 ? Utils
.convertToInt(
1390 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1393 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1394 this.webSocketPingSetInterval
= setInterval(() => {
1395 if (this.isWebSocketConnectionOpened()) {
1396 this.wsConnection
.ping((): void => {
1397 /* This is intentional */
1400 }, webSocketPingInterval
* 1000);
1403 ' WebSocket ping started every ' +
1404 Utils
.formatDurationSeconds(webSocketPingInterval
)
1406 } else if (this.webSocketPingSetInterval
) {
1409 ' WebSocket ping every ' +
1410 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1415 `${this.logPrefix()} WebSocket ping interval set to ${
1416 webSocketPingInterval
1417 ? Utils.formatDurationSeconds(webSocketPingInterval)
1418 : webSocketPingInterval
1419 }, not starting the WebSocket ping`
1424 private stopWebSocketPing(): void {
1425 if (this.webSocketPingSetInterval
) {
1426 clearInterval(this.webSocketPingSetInterval
);
1430 private warnDeprecatedTemplateKey(
1431 template
: ChargingStationTemplate
,
1433 chargingStationId
: string,
1436 if (!Utils
.isUndefined(template
[key
])) {
1437 const logPrefixStr
= ` ${chargingStationId} |`;
1439 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1440 this.stationTemplateFile
1441 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1446 private convertDeprecatedTemplateKey(
1447 template
: ChargingStationTemplate
,
1448 deprecatedKey
: string,
1451 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1452 template
[key
] = template
[deprecatedKey
] as unknown
;
1453 delete template
[deprecatedKey
];
1457 private getConfiguredSupervisionUrl(): URL
{
1458 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1459 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1461 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1463 switch (Configuration
.getSupervisionUrlDistribution()) {
1464 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1465 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1467 case SupervisionUrlDistribution
.RANDOM
:
1469 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1471 case SupervisionUrlDistribution
.SEQUENTIAL
:
1472 if (this.index
<= supervisionUrls
.length
) {
1473 urlIndex
= this.index
- 1;
1476 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1482 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1483 SupervisionUrlDistribution.ROUND_ROBIN
1486 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1489 return new URL(supervisionUrls
[urlIndex
]);
1491 return new URL(supervisionUrls
as string);
1494 private getHeartbeatInterval(): number | undefined {
1495 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
1496 if (HeartbeatInterval
) {
1497 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1499 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
1500 if (HeartBeatInterval
) {
1501 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1503 !this.stationInfo
.autoRegister
&&
1505 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1506 Constants.DEFAULT_HEARTBEAT_INTERVAL
1509 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1512 private stopHeartbeat(): void {
1513 if (this.heartbeatSetInterval
) {
1514 clearInterval(this.heartbeatSetInterval
);
1518 private openWSConnection(
1519 options
: ClientOptions
& ClientRequestArgs
= this.stationInfo
.wsOptions
,
1520 forceCloseOpened
= false
1522 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1524 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1525 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1527 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1529 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1530 this.wsConnection
.close();
1532 let protocol
: string;
1533 switch (this.getOcppVersion()) {
1534 case OCPPVersion
.VERSION_16
:
1535 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1538 this.handleUnsupportedVersion(this.getOcppVersion());
1541 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1543 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1547 private stopMeterValues(connectorId
: number) {
1548 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1549 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1553 private startAuthorizationFileMonitoring(): void {
1554 const authorizationFile
= this.getAuthorizationFile();
1555 if (authorizationFile
) {
1557 fs
.watch(authorizationFile
, (event
, filename
) => {
1558 if (filename
&& event
=== 'change') {
1562 ' Authorization file ' +
1564 ' have changed, reload'
1566 // Initialize authorizedTags
1567 this.authorizedTags
= this.getAuthorizedTags();
1569 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
1574 FileUtils
.handleFileException(
1578 error
as NodeJS
.ErrnoException
1584 ' No authorization file given in template file ' +
1585 this.stationTemplateFile
+
1586 '. Not monitoring changes'
1591 private startStationTemplateFileMonitoring(): void {
1593 fs
.watch(this.stationTemplateFile
, (event
, filename
): void => {
1594 if (filename
&& event
=== 'change') {
1599 this.stationTemplateFile
+
1600 ' have changed, reload'
1606 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1607 this.automaticTransactionGenerator
1609 this.automaticTransactionGenerator
.stop();
1611 this.startAutomaticTransactionGenerator();
1612 if (this.getEnableStatistics()) {
1613 this.performanceStatistics
.restart();
1615 this.performanceStatistics
.stop();
1617 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1620 this.logPrefix() + ' Charging station template file monitoring error: %j',
1627 FileUtils
.handleFileException(
1630 this.stationTemplateFile
,
1631 error
as NodeJS
.ErrnoException
1636 private getReconnectExponentialDelay(): boolean | undefined {
1637 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1638 ? this.stationInfo
.reconnectExponentialDelay
1642 private async reconnect(code
: number): Promise
<void> {
1643 // Stop WebSocket ping
1644 this.stopWebSocketPing();
1646 this.stopHeartbeat();
1647 // Stop the ATG if needed
1649 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1650 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1651 this.automaticTransactionGenerator
?.started
1653 this.automaticTransactionGenerator
.stop();
1656 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1657 this.getAutoReconnectMaxRetries() === -1
1659 this.autoReconnectRetryCount
++;
1660 const reconnectDelay
= this.getReconnectExponentialDelay()
1661 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1662 : this.getConnectionTimeout() * 1000;
1663 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1665 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1668 )}ms, timeout ${reconnectTimeout}ms`
1670 await Utils
.sleep(reconnectDelay
);
1673 ' WebSocket: reconnecting try #' +
1674 this.autoReconnectRetryCount
.toString()
1676 this.openWSConnection(
1677 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
1680 this.wsConnectionRestarted
= true;
1681 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1683 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1684 this.autoReconnectRetryCount
1685 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1690 private initializeConnectorStatus(connectorId
: number): void {
1691 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1692 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1693 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1694 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1695 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1696 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;