Commit | Line | Data |
---|---|---|
b4d34251 JB |
1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
32b02249 | 3 | import { AvailabilityType, BootNotificationRequest, CachedRequest, IncomingRequest, IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests'; |
efa43e52 | 4 | import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses'; |
e118beaa | 5 | import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration'; |
4c2b4904 | 6 | import ChargingStationTemplate, { CurrentType, PowerUnits, Voltage } from '../types/ChargingStationTemplate'; |
7e1dc878 | 7 | import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles } from '../types/ocpp/Configuration'; |
734d790d | 8 | import { ConnectorStatus, SampledValueTemplate } from '../types/Connectors'; |
9ccca265 | 9 | import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues'; |
16b0d4e7 | 10 | import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket'; |
58fad749 | 11 | import WebSocket, { ClientOptions, Data, OPEN } from 'ws'; |
3f40bc9c | 12 | |
6af9012e | 13 | import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; |
c0560973 JB |
14 | import { ChargePointStatus } from '../types/ocpp/ChargePointStatus'; |
15 | import { ChargingProfile } from '../types/ocpp/ChargingProfile'; | |
9ac86a7e | 16 | import ChargingStationInfo from '../types/ChargingStationInfo'; |
15042c5f | 17 | import { ClientRequestArgs } from 'http'; |
6af9012e | 18 | import Configuration from '../utils/Configuration'; |
63b48f77 | 19 | import Constants from '../utils/Constants'; |
14763b46 | 20 | import { ErrorType } from '../types/ocpp/ErrorType'; |
23132a44 | 21 | import FileUtils from '../utils/FileUtils'; |
d2a64eb5 | 22 | import { MessageType } from '../types/ocpp/MessageType'; |
e7171280 | 23 | import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService'; |
c0560973 JB |
24 | import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService'; |
25 | import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService'; | |
14763b46 | 26 | import OCPPError from './ocpp/OCPPError'; |
c0560973 JB |
27 | import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService'; |
28 | import OCPPRequestService from './ocpp/OCPPRequestService'; | |
29 | import { OCPPVersion } from '../types/ocpp/OCPPVersion'; | |
a6b3c6c3 | 30 | import PerformanceStatistics from '../performance/PerformanceStatistics'; |
c0560973 | 31 | import { StopTransactionReason } from '../types/ocpp/Transaction'; |
57939a9d | 32 | import { URL } from 'url'; |
6af9012e | 33 | import Utils from '../utils/Utils'; |
3f40bc9c JB |
34 | import crypto from 'crypto'; |
35 | import fs from 'fs'; | |
6af9012e | 36 | import logger from '../utils/Logger'; |
bf1866b2 | 37 | import path from 'path'; |
3f40bc9c JB |
38 | |
39 | export default class ChargingStation { | |
c0560973 JB |
40 | public stationTemplateFile: string; |
41 | public authorizedTags: string[]; | |
6e0964c8 | 42 | public stationInfo!: ChargingStationInfo; |
734d790d | 43 | public connectors: Map<number, ConnectorStatus>; |
6e0964c8 | 44 | public configuration!: ChargingStationConfiguration; |
6e0964c8 | 45 | public wsConnection!: WebSocket; |
32b02249 | 46 | public requests: Map<string, CachedRequest>; |
6e0964c8 JB |
47 | public performanceStatistics!: PerformanceStatistics; |
48 | public heartbeatSetInterval!: NodeJS.Timeout; | |
6e0964c8 | 49 | public ocppRequestService!: OCPPRequestService; |
ad2f27c3 | 50 | private index: number; |
6e0964c8 JB |
51 | private bootNotificationRequest!: BootNotificationRequest; |
52 | private bootNotificationResponse!: BootNotificationResponse | null; | |
53 | private connectorsConfigurationHash!: string; | |
a472cf2b JB |
54 | private ocppIncomingRequestService!: OCPPIncomingRequestService; |
55 | private messageQueue: string[]; | |
57939a9d | 56 | private wsConnectionUrl!: URL; |
265e4266 | 57 | private wsConnectionRestarted: boolean; |
a472cf2b | 58 | private stopped: boolean; |
ad2f27c3 | 59 | private autoReconnectRetryCount: number; |
265e4266 | 60 | private automaticTransactionGenerator!: AutomaticTransactionGenerator; |
6e0964c8 | 61 | private webSocketPingSetInterval!: NodeJS.Timeout; |
6af9012e JB |
62 | |
63 | constructor(index: number, stationTemplateFile: string) { | |
ad2f27c3 JB |
64 | this.index = index; |
65 | this.stationTemplateFile = stationTemplateFile; | |
734d790d | 66 | this.connectors = new Map<number, ConnectorStatus>(); |
c0560973 | 67 | this.initialize(); |
2e6f5966 | 68 | |
265e4266 JB |
69 | this.stopped = false; |
70 | this.wsConnectionRestarted = false; | |
ad2f27c3 | 71 | this.autoReconnectRetryCount = 0; |
2e6f5966 | 72 | |
32b02249 | 73 | this.requests = new Map<string, CachedRequest>(); |
16b0d4e7 | 74 | this.messageQueue = new Array<string>(); |
2e6f5966 | 75 | |
c0560973 JB |
76 | this.authorizedTags = this.getAuthorizedTags(); |
77 | } | |
78 | ||
79 | public logPrefix(): string { | |
54b1efe0 | 80 | return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`); |
c0560973 JB |
81 | } |
82 | ||
802cfa13 JB |
83 | public getBootNotificationRequest(): BootNotificationRequest { |
84 | return this.bootNotificationRequest; | |
85 | } | |
86 | ||
f4bf2abd | 87 | public getRandomIdTag(): string { |
c37528f1 | 88 | const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length); |
c0560973 JB |
89 | return this.authorizedTags[index]; |
90 | } | |
91 | ||
92 | public hasAuthorizedTags(): boolean { | |
93 | return !Utils.isEmptyArray(this.authorizedTags); | |
94 | } | |
95 | ||
6e0964c8 | 96 | public getEnableStatistics(): boolean | undefined { |
c0560973 JB |
97 | return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true; |
98 | } | |
99 | ||
a7fc8211 JB |
100 | public getMayAuthorizeAtRemoteStart(): boolean | undefined { |
101 | return this.stationInfo.mayAuthorizeAtRemoteStart ?? true; | |
102 | } | |
103 | ||
6e0964c8 | 104 | public getNumberOfPhases(): number | undefined { |
7decf1b6 | 105 | switch (this.getCurrentOutType()) { |
4c2b4904 | 106 | case CurrentType.AC: |
c0560973 | 107 | return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3; |
4c2b4904 | 108 | case CurrentType.DC: |
c0560973 JB |
109 | return 0; |
110 | } | |
111 | } | |
112 | ||
d5bff457 | 113 | public isWebSocketConnectionOpened(): boolean { |
58fad749 | 114 | return this.wsConnection?.readyState === OPEN; |
c0560973 JB |
115 | } |
116 | ||
117 | public isRegistered(): boolean { | |
118 | return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; | |
119 | } | |
120 | ||
121 | public isChargingStationAvailable(): boolean { | |
734d790d | 122 | return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE; |
c0560973 JB |
123 | } |
124 | ||
125 | public isConnectorAvailable(id: number): boolean { | |
734d790d | 126 | return this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE; |
c0560973 JB |
127 | } |
128 | ||
734d790d JB |
129 | public getConnectorStatus(id: number): ConnectorStatus { |
130 | return this.connectors.get(id); | |
c0560973 JB |
131 | } |
132 | ||
4c2b4904 JB |
133 | public getCurrentOutType(): CurrentType | undefined { |
134 | return this.stationInfo.currentOutType ?? CurrentType.AC; | |
c0560973 JB |
135 | } |
136 | ||
6e0964c8 | 137 | public getVoltageOut(): number | undefined { |
7decf1b6 | 138 | const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`; |
c0560973 | 139 | let defaultVoltageOut: number; |
7decf1b6 | 140 | switch (this.getCurrentOutType()) { |
4c2b4904 JB |
141 | case CurrentType.AC: |
142 | defaultVoltageOut = Voltage.VOLTAGE_230; | |
c0560973 | 143 | break; |
4c2b4904 JB |
144 | case CurrentType.DC: |
145 | defaultVoltageOut = Voltage.VOLTAGE_400; | |
c0560973 JB |
146 | break; |
147 | default: | |
148 | logger.error(errMsg); | |
290d006c | 149 | throw new Error(errMsg); |
c0560973 JB |
150 | } |
151 | return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut; | |
152 | } | |
153 | ||
6e0964c8 | 154 | public getTransactionIdTag(transactionId: number): string | undefined { |
734d790d JB |
155 | for (const connectorId of this.connectors.keys()) { |
156 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { | |
157 | return this.getConnectorStatus(connectorId).transactionIdTag; | |
c0560973 JB |
158 | } |
159 | } | |
160 | } | |
161 | ||
6ed92bc1 JB |
162 | public getOutOfOrderEndMeterValues(): boolean { |
163 | return this.stationInfo.outOfOrderEndMeterValues ?? false; | |
164 | } | |
165 | ||
166 | public getBeginEndMeterValues(): boolean { | |
167 | return this.stationInfo.beginEndMeterValues ?? false; | |
168 | } | |
169 | ||
170 | public getMeteringPerTransaction(): boolean { | |
171 | return this.stationInfo.meteringPerTransaction ?? true; | |
172 | } | |
173 | ||
fd0c36fa JB |
174 | public getTransactionDataMeterValues(): boolean { |
175 | return this.stationInfo.transactionDataMeterValues ?? false; | |
176 | } | |
177 | ||
9ccca265 JB |
178 | public getMainVoltageMeterValues(): boolean { |
179 | return this.stationInfo.mainVoltageMeterValues ?? true; | |
180 | } | |
181 | ||
6b10669b JB |
182 | public getPhaseLineToLineVoltageMeterValues(): boolean { |
183 | return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false; | |
9bd87386 JB |
184 | } |
185 | ||
6ed92bc1 JB |
186 | public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { |
187 | if (this.getMeteringPerTransaction()) { | |
734d790d JB |
188 | for (const connectorId of this.connectors.keys()) { |
189 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { | |
190 | return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue; | |
6ed92bc1 JB |
191 | } |
192 | } | |
193 | } | |
734d790d JB |
194 | for (const connectorId of this.connectors.keys()) { |
195 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { | |
196 | return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue; | |
c0560973 JB |
197 | } |
198 | } | |
199 | } | |
200 | ||
6ed92bc1 JB |
201 | public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined { |
202 | if (this.getMeteringPerTransaction()) { | |
734d790d | 203 | return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue; |
6ed92bc1 | 204 | } |
734d790d | 205 | return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue; |
6ed92bc1 JB |
206 | } |
207 | ||
c0560973 JB |
208 | public getAuthorizeRemoteTxRequests(): boolean { |
209 | const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests); | |
210 | return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; | |
211 | } | |
212 | ||
213 | public getLocalAuthListEnabled(): boolean { | |
214 | const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled); | |
215 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; | |
216 | } | |
217 | ||
218 | public restartWebSocketPing(): void { | |
219 | // Stop WebSocket ping | |
220 | this.stopWebSocketPing(); | |
221 | // Start WebSocket ping | |
222 | this.startWebSocketPing(); | |
223 | } | |
224 | ||
9ccca265 JB |
225 | public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, |
226 | phase?: MeterValuePhase): SampledValueTemplate | undefined { | |
227 | if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) { | |
7d75bee1 | 228 | logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
9bd87386 JB |
229 | return; |
230 | } | |
231 | if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { | |
7d75bee1 | 232 | logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`); |
9ccca265 JB |
233 | return; |
234 | } | |
734d790d | 235 | const sampledValueTemplates: SampledValueTemplate[] = this.getConnectorStatus(connectorId).MeterValues; |
9ccca265 | 236 | for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) { |
290d006c | 237 | if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) { |
7d75bee1 | 238 | logger.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
47e22477 | 239 | } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand |
32b02249 | 240 | && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
9ccca265 JB |
241 | return sampledValueTemplates[index]; |
242 | } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand | |
32b02249 | 243 | && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
9ccca265 JB |
244 | return sampledValueTemplates[index]; |
245 | } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER | |
32b02249 | 246 | && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) { |
9ccca265 JB |
247 | return sampledValueTemplates[index]; |
248 | } | |
249 | } | |
9bd87386 | 250 | if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { |
7d75bee1 | 251 | const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`; |
de96acad JB |
252 | logger.error(errorMsg); |
253 | throw new Error(errorMsg); | |
9ccca265 | 254 | } |
7d75bee1 | 255 | logger.debug(`${this.logPrefix()} No MeterValues for measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
9ccca265 JB |
256 | } |
257 | ||
e644918b JB |
258 | public getAutomaticTransactionGeneratorRequireAuthorize(): boolean { |
259 | return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true; | |
260 | } | |
261 | ||
c0560973 JB |
262 | public startHeartbeat(): void { |
263 | if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) { | |
71623267 JB |
264 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
265 | this.heartbeatSetInterval = setInterval(async (): Promise<void> => { | |
c0560973 JB |
266 | await this.ocppRequestService.sendHeartbeat(); |
267 | }, this.getHeartbeatInterval()); | |
d7d1db72 | 268 | logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())); |
c0560973 | 269 | } else if (this.heartbeatSetInterval) { |
d7d1db72 | 270 | logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())); |
c0560973 | 271 | } else { |
d7d1db72 | 272 | logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`); |
c0560973 JB |
273 | } |
274 | } | |
275 | ||
276 | public restartHeartbeat(): void { | |
277 | // Stop heartbeat | |
278 | this.stopHeartbeat(); | |
279 | // Start heartbeat | |
280 | this.startHeartbeat(); | |
281 | } | |
282 | ||
283 | public startMeterValues(connectorId: number, interval: number): void { | |
284 | if (connectorId === 0) { | |
285 | logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`); | |
286 | return; | |
287 | } | |
734d790d | 288 | if (!this.getConnectorStatus(connectorId)) { |
c0560973 JB |
289 | logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`); |
290 | return; | |
291 | } | |
734d790d | 292 | if (!this.getConnectorStatus(connectorId)?.transactionStarted) { |
c0560973 JB |
293 | logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`); |
294 | return; | |
734d790d | 295 | } else if (this.getConnectorStatus(connectorId)?.transactionStarted && !this.getConnectorStatus(connectorId)?.transactionId) { |
c0560973 JB |
296 | logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`); |
297 | return; | |
298 | } | |
299 | if (interval > 0) { | |
71623267 | 300 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
734d790d JB |
301 | this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => { |
302 | await this.ocppRequestService.sendMeterValues(connectorId, this.getConnectorStatus(connectorId).transactionId, interval); | |
c0560973 JB |
303 | }, interval); |
304 | } else { | |
d7d1db72 | 305 | logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`); |
c0560973 JB |
306 | } |
307 | } | |
308 | ||
309 | public start(): void { | |
7874b0b1 JB |
310 | if (this.getEnableStatistics()) { |
311 | this.performanceStatistics.start(); | |
312 | } | |
c0560973 JB |
313 | this.openWSConnection(); |
314 | // Monitor authorization file | |
315 | this.startAuthorizationFileMonitoring(); | |
316 | // Monitor station template file | |
317 | this.startStationTemplateFileMonitoring(); | |
8bf88613 | 318 | // Handle WebSocket message |
c0560973 | 319 | this.wsConnection.on('message', this.onMessage.bind(this)); |
5dc8b1b5 | 320 | // Handle WebSocket error |
c0560973 | 321 | this.wsConnection.on('error', this.onError.bind(this)); |
5dc8b1b5 | 322 | // Handle WebSocket close |
c0560973 | 323 | this.wsConnection.on('close', this.onClose.bind(this)); |
8bf88613 | 324 | // Handle WebSocket open |
c0560973 | 325 | this.wsConnection.on('open', this.onOpen.bind(this)); |
5dc8b1b5 | 326 | // Handle WebSocket ping |
c0560973 | 327 | this.wsConnection.on('ping', this.onPing.bind(this)); |
5dc8b1b5 | 328 | // Handle WebSocket pong |
c0560973 JB |
329 | this.wsConnection.on('pong', this.onPong.bind(this)); |
330 | } | |
331 | ||
332 | public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { | |
333 | // Stop message sequence | |
334 | await this.stopMessageSequence(reason); | |
734d790d JB |
335 | for (const connectorId of this.connectors.keys()) { |
336 | if (connectorId > 0) { | |
337 | await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.UNAVAILABLE); | |
338 | this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE; | |
c0560973 JB |
339 | } |
340 | } | |
d5bff457 | 341 | if (this.isWebSocketConnectionOpened()) { |
c0560973 JB |
342 | this.wsConnection.close(); |
343 | } | |
7874b0b1 JB |
344 | if (this.getEnableStatistics()) { |
345 | this.performanceStatistics.stop(); | |
346 | } | |
c0560973 | 347 | this.bootNotificationResponse = null; |
265e4266 | 348 | this.stopped = true; |
c0560973 JB |
349 | } |
350 | ||
6e0964c8 | 351 | public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined { |
7874b0b1 | 352 | return this.configuration.configurationKey.find((configElement) => { |
c0560973 JB |
353 | if (caseInsensitive) { |
354 | return configElement.key.toLowerCase() === key.toLowerCase(); | |
355 | } | |
356 | return configElement.key === key; | |
357 | }); | |
c0560973 JB |
358 | } |
359 | ||
360 | public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void { | |
361 | const keyFound = this.getConfigurationKey(key); | |
362 | if (!keyFound) { | |
363 | this.configuration.configurationKey.push({ | |
364 | key, | |
365 | readonly, | |
366 | value, | |
367 | visible, | |
368 | reboot, | |
369 | }); | |
370 | } else { | |
371 | logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound); | |
372 | } | |
373 | } | |
374 | ||
375 | public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void { | |
376 | const keyFound = this.getConfigurationKey(key); | |
377 | if (keyFound) { | |
378 | const keyIndex = this.configuration.configurationKey.indexOf(keyFound); | |
379 | this.configuration.configurationKey[keyIndex].value = value; | |
380 | } else { | |
381 | logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value }); | |
382 | } | |
383 | } | |
384 | ||
a7fc8211 JB |
385 | public setChargingProfile(connectorId: number, cp: ChargingProfile): void { |
386 | let cpReplaced = false; | |
734d790d JB |
387 | if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { |
388 | this.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => { | |
c0560973 | 389 | if (chargingProfile.chargingProfileId === cp.chargingProfileId |
32b02249 | 390 | || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) { |
734d790d | 391 | this.getConnectorStatus(connectorId).chargingProfiles[index] = cp; |
a7fc8211 | 392 | cpReplaced = true; |
c0560973 JB |
393 | } |
394 | }); | |
395 | } | |
734d790d | 396 | !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp); |
c0560973 JB |
397 | } |
398 | ||
399 | public resetTransactionOnConnector(connectorId: number): void { | |
734d790d JB |
400 | this.getConnectorStatus(connectorId).authorized = false; |
401 | this.getConnectorStatus(connectorId).transactionStarted = false; | |
402 | delete this.getConnectorStatus(connectorId).authorizeIdTag; | |
403 | delete this.getConnectorStatus(connectorId).transactionId; | |
404 | delete this.getConnectorStatus(connectorId).transactionIdTag; | |
405 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
406 | delete this.getConnectorStatus(connectorId).transactionBeginMeterValue; | |
dd119a6b | 407 | this.stopMeterValues(connectorId); |
2e6f5966 JB |
408 | } |
409 | ||
77f00f84 | 410 | public addToMessageQueue(message: string): void { |
3ba2381e | 411 | let dups = false; |
cb31c873 | 412 | // Handle dups in message queue |
3ba2381e | 413 | for (const bufferedMessage of this.messageQueue) { |
cb31c873 | 414 | // Message already in the queue |
3ba2381e JB |
415 | if (message === bufferedMessage) { |
416 | dups = true; | |
417 | break; | |
418 | } | |
419 | } | |
420 | if (!dups) { | |
cb31c873 | 421 | // Queue message |
3ba2381e JB |
422 | this.messageQueue.push(message); |
423 | } | |
424 | } | |
425 | ||
77f00f84 JB |
426 | private flushMessageQueue() { |
427 | if (!Utils.isEmptyArray(this.messageQueue)) { | |
428 | this.messageQueue.forEach((message, index) => { | |
429 | this.messageQueue.splice(index, 1); | |
aef1b33a | 430 | // TODO: evaluate the need to track performance |
77f00f84 JB |
431 | this.wsConnection.send(message); |
432 | }); | |
433 | } | |
434 | } | |
435 | ||
c0560973 | 436 | private getChargingStationId(stationTemplate: ChargingStationTemplate): string { |
ef6076c1 | 437 | // In case of multiple instances: add instance index to charging station id |
203bc097 | 438 | const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; |
9ccca265 | 439 | const idSuffix = stationTemplate.nameSuffix ?? ''; |
ad2f27c3 | 440 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix; |
5ad8570f JB |
441 | } |
442 | ||
c0560973 | 443 | private buildStationInfo(): ChargingStationInfo { |
9ac86a7e | 444 | let stationTemplateFromFile: ChargingStationTemplate; |
5ad8570f JB |
445 | try { |
446 | // Load template file | |
ad2f27c3 | 447 | const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r'); |
9ac86a7e | 448 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate; |
5ad8570f JB |
449 | fs.closeSync(fileDescriptor); |
450 | } catch (error) { | |
23132a44 | 451 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error); |
5ad8570f | 452 | } |
510f0fa5 | 453 | const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo; |
0a60c33c | 454 | if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { |
9ac86a7e | 455 | stationTemplateFromFile.power = stationTemplateFromFile.power as number[]; |
c37528f1 | 456 | const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplateFromFile.power.length); |
510f0fa5 JB |
457 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT |
458 | ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000 | |
459 | : stationTemplateFromFile.power[powerArrayRandomIndex]; | |
5ad8570f | 460 | } else { |
510f0fa5 JB |
461 | stationTemplateFromFile.power = stationTemplateFromFile.power as number; |
462 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT | |
fd0c36fa | 463 | ? stationTemplateFromFile.power * 1000 |
510f0fa5 | 464 | : stationTemplateFromFile.power; |
5ad8570f | 465 | } |
fd0c36fa JB |
466 | delete stationInfo.power; |
467 | delete stationInfo.powerUnit; | |
c0560973 | 468 | stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile); |
9ac86a7e JB |
469 | stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
470 | return stationInfo; | |
5ad8570f JB |
471 | } |
472 | ||
c0560973 JB |
473 | private getOCPPVersion(): OCPPVersion { |
474 | return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16; | |
475 | } | |
476 | ||
477 | private handleUnsupportedVersion(version: OCPPVersion) { | |
478 | const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`; | |
479 | logger.error(errMsg); | |
480 | throw new Error(errMsg); | |
481 | } | |
482 | ||
483 | private initialize(): void { | |
484 | this.stationInfo = this.buildStationInfo(); | |
ad2f27c3 JB |
485 | this.bootNotificationRequest = { |
486 | chargePointModel: this.stationInfo.chargePointModel, | |
487 | chargePointVendor: this.stationInfo.chargePointVendor, | |
488 | ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix }, | |
489 | ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion }, | |
2e6f5966 | 490 | }; |
c0560973 | 491 | this.configuration = this.getTemplateChargingStationConfiguration(); |
57939a9d | 492 | this.wsConnectionUrl = new URL(this.getSupervisionURL().href + '/' + this.stationInfo.chargingStationId); |
0a60c33c | 493 | // Build connectors if needed |
c0560973 | 494 | const maxConnectors = this.getMaxNumberOfConnectors(); |
6ecb15e4 | 495 | if (maxConnectors <= 0) { |
c0560973 | 496 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`); |
7abfea5f | 497 | } |
c0560973 | 498 | const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors(); |
7abfea5f | 499 | if (templateMaxConnectors <= 0) { |
c0560973 | 500 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`); |
593cf3f9 | 501 | } |
ad2f27c3 | 502 | if (!this.stationInfo.Connectors[0]) { |
c0560973 | 503 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`); |
7abfea5f JB |
504 | } |
505 | // Sanity check | |
ad2f27c3 | 506 | if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) { |
c0560973 | 507 | logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`); |
ad2f27c3 | 508 | this.stationInfo.randomConnectors = true; |
6ecb15e4 | 509 | } |
ad2f27c3 | 510 | const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); |
734d790d JB |
511 | const connectorsConfigChanged = this.connectors.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; |
512 | if (!this.connectors || this.connectors.size === 0 || connectorsConfigChanged) { | |
513 | connectorsConfigChanged && (this.connectors.clear()); | |
ad2f27c3 | 514 | this.connectorsConfigurationHash = connectorsConfigHash; |
7abfea5f | 515 | // Add connector Id 0 |
6af9012e | 516 | let lastConnector = '0'; |
ad2f27c3 | 517 | for (lastConnector in this.stationInfo.Connectors) { |
734d790d JB |
518 | const lastConnectorId = Utils.convertToInt(lastConnector); |
519 | if (lastConnectorId === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) { | |
520 | this.connectors.set(lastConnectorId, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])); | |
521 | this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; | |
522 | if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { | |
523 | this.getConnectorStatus(lastConnectorId).chargingProfiles = []; | |
418106c8 | 524 | } |
0a60c33c JB |
525 | } |
526 | } | |
0a60c33c | 527 | // Generate all connectors |
ad2f27c3 | 528 | if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { |
7abfea5f | 529 | for (let index = 1; index <= maxConnectors; index++) { |
72740232 | 530 | const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) : index; |
734d790d JB |
531 | this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])); |
532 | this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; | |
533 | if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { | |
534 | this.getConnectorStatus(index).chargingProfiles = []; | |
418106c8 | 535 | } |
7abfea5f | 536 | } |
0a60c33c JB |
537 | } |
538 | } | |
d4a73fb7 | 539 | // Avoid duplication of connectors related information |
ad2f27c3 | 540 | delete this.stationInfo.Connectors; |
0a60c33c | 541 | // Initialize transaction attributes on connectors |
734d790d JB |
542 | for (const connectorId of this.connectors.keys()) { |
543 | if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) { | |
544 | this.initTransactionAttributesOnConnector(connectorId); | |
0a60c33c JB |
545 | } |
546 | } | |
c0560973 JB |
547 | switch (this.getOCPPVersion()) { |
548 | case OCPPVersion.VERSION_16: | |
549 | this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this); | |
550 | this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this)); | |
551 | break; | |
552 | default: | |
553 | this.handleUnsupportedVersion(this.getOCPPVersion()); | |
554 | break; | |
555 | } | |
7abfea5f | 556 | // OCPP parameters |
147d0e0f | 557 | this.initOCPPParameters(); |
47e22477 JB |
558 | if (this.stationInfo.autoRegister) { |
559 | this.bootNotificationResponse = { | |
560 | currentTime: new Date().toISOString(), | |
561 | interval: this.getHeartbeatInterval() / 1000, | |
562 | status: RegistrationStatus.ACCEPTED | |
563 | }; | |
564 | } | |
147d0e0f JB |
565 | this.stationInfo.powerDivider = this.getPowerDivider(); |
566 | if (this.getEnableStatistics()) { | |
2a370053 | 567 | this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId, this.wsConnectionUrl); |
147d0e0f JB |
568 | } |
569 | } | |
570 | ||
571 | private initOCPPParameters(): void { | |
36f6a92e JB |
572 | if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { |
573 | this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`); | |
574 | } | |
c0560973 JB |
575 | this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true); |
576 | if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { | |
577 | this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER); | |
7abfea5f | 578 | } |
7e1dc878 JB |
579 | if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) { |
580 | const connectorPhaseRotation = []; | |
734d790d | 581 | for (const connectorId of this.connectors.keys()) { |
7e1dc878 | 582 | // AC/DC |
734d790d JB |
583 | if (connectorId === 0 && this.getNumberOfPhases() === 0) { |
584 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
585 | } else if (connectorId > 0 && this.getNumberOfPhases() === 0) { | |
586 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
7e1dc878 | 587 | // AC |
734d790d JB |
588 | } else if (connectorId > 0 && this.getNumberOfPhases() === 1) { |
589 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
590 | } else if (connectorId > 0 && this.getNumberOfPhases() === 3) { | |
591 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
7e1dc878 JB |
592 | } |
593 | } | |
594 | this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString()); | |
595 | } | |
36f6a92e JB |
596 | if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) { |
597 | this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); | |
598 | } | |
599 | if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) | |
32b02249 | 600 | && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) { |
36f6a92e JB |
601 | this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false'); |
602 | } | |
147d0e0f JB |
603 | if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
604 | this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString()); | |
8bce55bf | 605 | } |
7dde0b73 JB |
606 | } |
607 | ||
c0560973 | 608 | private async onOpen(): Promise<void> { |
e9017bfc | 609 | logger.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`); |
c0560973 JB |
610 | if (!this.isRegistered()) { |
611 | // Send BootNotification | |
612 | let registrationRetryCount = 0; | |
613 | do { | |
43d673d9 JB |
614 | this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, |
615 | this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion); | |
c0560973 JB |
616 | if (!this.isRegistered()) { |
617 | registrationRetryCount++; | |
618 | await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL); | |
619 | } | |
620 | } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1)); | |
c7db4718 JB |
621 | } |
622 | if (this.isRegistered()) { | |
c0560973 | 623 | await this.startMessageSequence(); |
265e4266 JB |
624 | this.stopped && (this.stopped = false); |
625 | if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) { | |
77f00f84 | 626 | this.flushMessageQueue(); |
2e6f5966 JB |
627 | } |
628 | } else { | |
c0560973 | 629 | logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`); |
2e6f5966 | 630 | } |
c0560973 | 631 | this.autoReconnectRetryCount = 0; |
265e4266 | 632 | this.wsConnectionRestarted = false; |
2e6f5966 JB |
633 | } |
634 | ||
6c65a295 | 635 | private async onClose(code: number, reason: string): Promise<void> { |
d09085e9 | 636 | switch (code) { |
6c65a295 JB |
637 | // Normal close |
638 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: | |
c0560973 | 639 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
5dc8b1b5 | 640 | logger.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`); |
c0560973 JB |
641 | this.autoReconnectRetryCount = 0; |
642 | break; | |
6c65a295 JB |
643 | // Abnormal close |
644 | default: | |
5dc8b1b5 | 645 | logger.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`); |
d09085e9 | 646 | await this.reconnect(code); |
c0560973 JB |
647 | break; |
648 | } | |
2e6f5966 JB |
649 | } |
650 | ||
16b0d4e7 | 651 | private async onMessage(data: Data): Promise<void> { |
c0560973 | 652 | let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}]; |
193d2c0a | 653 | let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void; |
c0560973 | 654 | let rejectCallback: (error: OCPPError) => void; |
32b02249 | 655 | let requestCommandName: RequestCommand | IncomingRequestCommand; |
c0560973 | 656 | let requestPayload: Record<string, unknown>; |
32b02249 | 657 | let cachedRequest: CachedRequest; |
c0560973 JB |
658 | let errMsg: string; |
659 | try { | |
16b0d4e7 | 660 | const request = JSON.parse(data.toString()) as IncomingRequest; |
47e22477 JB |
661 | if (Utils.isIterable(request)) { |
662 | // Parse the message | |
663 | [messageType, messageId, commandName, commandPayload, errorDetails] = request; | |
664 | } else { | |
a6b3c6c3 | 665 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming request is not iterable', commandName); |
47e22477 | 666 | } |
c0560973 JB |
667 | // Check the Type of message |
668 | switch (messageType) { | |
669 | // Incoming Message | |
670 | case MessageType.CALL_MESSAGE: | |
671 | if (this.getEnableStatistics()) { | |
aef1b33a | 672 | this.performanceStatistics.addRequestStatistic(commandName, messageType); |
c0560973 JB |
673 | } |
674 | // Process the call | |
675 | await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload); | |
676 | break; | |
677 | // Outcome Message | |
678 | case MessageType.CALL_RESULT_MESSAGE: | |
679 | // Respond | |
16b0d4e7 JB |
680 | cachedRequest = this.requests.get(messageId); |
681 | if (Utils.isIterable(cachedRequest)) { | |
32b02249 | 682 | [responseCallback, , , requestPayload] = cachedRequest; |
c0560973 | 683 | } else { |
a685c3af | 684 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} response is not iterable`, commandName); |
c0560973 JB |
685 | } |
686 | if (!responseCallback) { | |
687 | // Error | |
a685c3af | 688 | throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response for unknown message id ${messageId}`, commandName); |
c0560973 | 689 | } |
c0560973 JB |
690 | responseCallback(commandName, requestPayload); |
691 | break; | |
692 | // Error Message | |
693 | case MessageType.CALL_ERROR_MESSAGE: | |
16b0d4e7 | 694 | cachedRequest = this.requests.get(messageId); |
16b0d4e7 | 695 | if (Utils.isIterable(cachedRequest)) { |
32b02249 | 696 | [, rejectCallback, requestCommandName] = cachedRequest; |
c0560973 | 697 | } else { |
a685c3af | 698 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} error response is not iterable`); |
c0560973 | 699 | } |
32b02249 JB |
700 | if (!rejectCallback) { |
701 | // Error | |
a685c3af | 702 | throw new OCPPError(ErrorType.INTERNAL_ERROR, `Error response for unknown message id ${messageId}`, requestCommandName); |
32b02249 JB |
703 | } |
704 | rejectCallback(new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails)); | |
c0560973 JB |
705 | break; |
706 | // Error | |
707 | default: | |
708 | errMsg = `${this.logPrefix()} Wrong message type ${messageType}`; | |
709 | logger.error(errMsg); | |
14763b46 | 710 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); |
c0560973 JB |
711 | } |
712 | } catch (error) { | |
713 | // Log | |
a685c3af | 714 | logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data, this.requests.get(messageId), error); |
c0560973 | 715 | // Send error |
32b02249 | 716 | messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName); |
c0560973 | 717 | } |
2328be1e JB |
718 | } |
719 | ||
c0560973 | 720 | private onPing(): void { |
57939a9d | 721 | logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); |
c0560973 JB |
722 | } |
723 | ||
724 | private onPong(): void { | |
57939a9d | 725 | logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); |
c0560973 JB |
726 | } |
727 | ||
16b0d4e7 | 728 | private async onError(error: WSError): Promise<void> { |
5dc8b1b5 | 729 | logger.error(this.logPrefix() + ' WebSocket error: %j', error); |
16b0d4e7 | 730 | // switch (error.code) { |
c0560973 | 731 | // case 'ECONNREFUSED': |
16b0d4e7 | 732 | // await this.reconnect(error); |
c0560973 JB |
733 | // break; |
734 | // } | |
735 | } | |
736 | ||
737 | private getTemplateChargingStationConfiguration(): ChargingStationConfiguration { | |
7874b0b1 | 738 | return this.stationInfo.Configuration ?? {} as ChargingStationConfiguration; |
c0560973 JB |
739 | } |
740 | ||
6e0964c8 | 741 | private getAuthorizationFile(): string | undefined { |
bf1866b2 | 742 | return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile)); |
c0560973 JB |
743 | } |
744 | ||
745 | private getAuthorizedTags(): string[] { | |
746 | let authorizedTags: string[] = []; | |
747 | const authorizationFile = this.getAuthorizationFile(); | |
748 | if (authorizationFile) { | |
749 | try { | |
750 | // Load authorization file | |
751 | const fileDescriptor = fs.openSync(authorizationFile, 'r'); | |
752 | authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[]; | |
753 | fs.closeSync(fileDescriptor); | |
754 | } catch (error) { | |
23132a44 | 755 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error); |
c0560973 JB |
756 | } |
757 | } else { | |
758 | logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile); | |
8c4da341 | 759 | } |
c0560973 JB |
760 | return authorizedTags; |
761 | } | |
762 | ||
6e0964c8 | 763 | private getUseConnectorId0(): boolean | undefined { |
c0560973 | 764 | return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true; |
8bce55bf JB |
765 | } |
766 | ||
c0560973 | 767 | private getNumberOfRunningTransactions(): number { |
6ecb15e4 | 768 | let trxCount = 0; |
734d790d JB |
769 | for (const connectorId of this.connectors.keys()) { |
770 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { | |
6ecb15e4 JB |
771 | trxCount++; |
772 | } | |
773 | } | |
774 | return trxCount; | |
775 | } | |
776 | ||
1f761b9a | 777 | // 0 for disabling |
6e0964c8 | 778 | private getConnectionTimeout(): number | undefined { |
291cb255 JB |
779 | if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
780 | return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT; | |
781 | } | |
291cb255 | 782 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
3574dfd3 JB |
783 | } |
784 | ||
1f761b9a | 785 | // -1 for unlimited, 0 for disabling |
6e0964c8 | 786 | private getAutoReconnectMaxRetries(): number | undefined { |
ad2f27c3 JB |
787 | if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { |
788 | return this.stationInfo.autoReconnectMaxRetries; | |
3574dfd3 JB |
789 | } |
790 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { | |
791 | return Configuration.getAutoReconnectMaxRetries(); | |
792 | } | |
793 | return -1; | |
794 | } | |
795 | ||
ec977daf | 796 | // 0 for disabling |
6e0964c8 | 797 | private getRegistrationMaxRetries(): number | undefined { |
ad2f27c3 JB |
798 | if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { |
799 | return this.stationInfo.registrationMaxRetries; | |
32a1eb7a JB |
800 | } |
801 | return -1; | |
802 | } | |
803 | ||
c0560973 JB |
804 | private getPowerDivider(): number { |
805 | let powerDivider = this.getNumberOfConnectors(); | |
ad2f27c3 | 806 | if (this.stationInfo.powerSharedByConnectors) { |
c0560973 | 807 | powerDivider = this.getNumberOfRunningTransactions(); |
6ecb15e4 JB |
808 | } |
809 | return powerDivider; | |
810 | } | |
811 | ||
c0560973 | 812 | private getTemplateMaxNumberOfConnectors(): number { |
ad2f27c3 | 813 | return Object.keys(this.stationInfo.Connectors).length; |
7abfea5f JB |
814 | } |
815 | ||
c0560973 | 816 | private getMaxNumberOfConnectors(): number { |
5ad8570f | 817 | let maxConnectors = 0; |
ad2f27c3 JB |
818 | if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) { |
819 | const numberOfConnectors = this.stationInfo.numberOfConnectors as number[]; | |
6ecb15e4 | 820 | // Distribute evenly the number of connectors |
ad2f27c3 JB |
821 | maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length]; |
822 | } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) { | |
823 | maxConnectors = this.stationInfo.numberOfConnectors as number; | |
488fd3a7 | 824 | } else { |
c0560973 | 825 | maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors(); |
5ad8570f JB |
826 | } |
827 | return maxConnectors; | |
2e6f5966 JB |
828 | } |
829 | ||
c0560973 | 830 | private getNumberOfConnectors(): number { |
734d790d | 831 | return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size; |
6ecb15e4 JB |
832 | } |
833 | ||
c0560973 | 834 | private async startMessageSequence(): Promise<void> { |
136c90ba | 835 | // Start WebSocket ping |
c0560973 | 836 | this.startWebSocketPing(); |
5ad8570f | 837 | // Start heartbeat |
c0560973 | 838 | this.startHeartbeat(); |
0a60c33c | 839 | // Initialize connectors status |
734d790d JB |
840 | for (const connectorId of this.connectors.keys()) { |
841 | if (connectorId === 0) { | |
593cf3f9 | 842 | continue; |
734d790d | 843 | } else if (!this.stopped && !this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) { |
136c90ba | 844 | // Send status in template at startup |
734d790d JB |
845 | await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus); |
846 | this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus; | |
847 | } else if (this.stopped && this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) { | |
136c90ba | 848 | // Send status in template after reset |
734d790d JB |
849 | await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus); |
850 | this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus; | |
851 | } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) { | |
136c90ba | 852 | // Send previous status at template reload |
734d790d | 853 | await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).status); |
5ad8570f | 854 | } else { |
136c90ba | 855 | // Send default status |
734d790d JB |
856 | await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE); |
857 | this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE; | |
5ad8570f JB |
858 | } |
859 | } | |
0a60c33c | 860 | // Start the ATG |
dd119a6b | 861 | this.startAutomaticTransactionGenerator(); |
dd119a6b JB |
862 | } |
863 | ||
864 | private startAutomaticTransactionGenerator() { | |
ad2f27c3 | 865 | if (this.stationInfo.AutomaticTransactionGenerator.enable) { |
265e4266 JB |
866 | if (!this.automaticTransactionGenerator) { |
867 | this.automaticTransactionGenerator = new AutomaticTransactionGenerator(this); | |
5ad8570f | 868 | } |
265e4266 JB |
869 | if (!this.automaticTransactionGenerator.started) { |
870 | this.automaticTransactionGenerator.start(); | |
5ad8570f JB |
871 | } |
872 | } | |
5ad8570f JB |
873 | } |
874 | ||
c0560973 | 875 | private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
136c90ba | 876 | // Stop WebSocket ping |
c0560973 | 877 | this.stopWebSocketPing(); |
79411696 | 878 | // Stop heartbeat |
c0560973 | 879 | this.stopHeartbeat(); |
79411696 | 880 | // Stop the ATG |
ad2f27c3 | 881 | if (this.stationInfo.AutomaticTransactionGenerator.enable && |
265e4266 JB |
882 | this.automaticTransactionGenerator && |
883 | this.automaticTransactionGenerator.started) { | |
0045cef5 | 884 | this.automaticTransactionGenerator.stop(); |
79411696 | 885 | } else { |
734d790d JB |
886 | for (const connectorId of this.connectors.keys()) { |
887 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { | |
888 | const transactionId = this.getConnectorStatus(connectorId).transactionId; | |
6ed92bc1 JB |
889 | await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId), |
890 | this.getTransactionIdTag(transactionId), reason); | |
79411696 JB |
891 | } |
892 | } | |
893 | } | |
894 | } | |
895 | ||
c0560973 | 896 | private startWebSocketPing(): void { |
9cd3dfb0 JB |
897 | const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) |
898 | ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) | |
899 | : 0; | |
ad2f27c3 JB |
900 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
901 | this.webSocketPingSetInterval = setInterval(() => { | |
d5bff457 | 902 | if (this.isWebSocketConnectionOpened()) { |
0dad4bda | 903 | this.wsConnection.ping((): void => { /* This is intentional */ }); |
136c90ba JB |
904 | } |
905 | }, webSocketPingInterval * 1000); | |
d7d1db72 | 906 | logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.formatDurationSeconds(webSocketPingInterval)); |
ad2f27c3 | 907 | } else if (this.webSocketPingSetInterval) { |
d7d1db72 | 908 | logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.formatDurationSeconds(webSocketPingInterval) + ' already started'); |
136c90ba | 909 | } else { |
d7d1db72 | 910 | logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`); |
136c90ba JB |
911 | } |
912 | } | |
913 | ||
c0560973 | 914 | private stopWebSocketPing(): void { |
ad2f27c3 JB |
915 | if (this.webSocketPingSetInterval) { |
916 | clearInterval(this.webSocketPingSetInterval); | |
136c90ba JB |
917 | } |
918 | } | |
919 | ||
57939a9d | 920 | private getSupervisionURL(): URL { |
c0560973 JB |
921 | const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs()); |
922 | let indexUrl = 0; | |
923 | if (!Utils.isEmptyArray(supervisionUrls)) { | |
924 | if (Configuration.getDistributeStationsToTenantsEqually()) { | |
925 | indexUrl = this.index % supervisionUrls.length; | |
926 | } else { | |
927 | // Get a random url | |
c37528f1 | 928 | indexUrl = Math.floor(Utils.secureRandom() * supervisionUrls.length); |
c0560973 | 929 | } |
57939a9d | 930 | return new URL(supervisionUrls[indexUrl]); |
c0560973 | 931 | } |
57939a9d | 932 | return new URL(supervisionUrls as string); |
136c90ba JB |
933 | } |
934 | ||
6e0964c8 | 935 | private getHeartbeatInterval(): number | undefined { |
c0560973 JB |
936 | const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval); |
937 | if (HeartbeatInterval) { | |
938 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; | |
939 | } | |
940 | const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval); | |
941 | if (HeartBeatInterval) { | |
942 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; | |
0a60c33c | 943 | } |
47e22477 JB |
944 | !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`); |
945 | return Constants.DEFAULT_HEARTBEAT_INTERVAL; | |
0a60c33c JB |
946 | } |
947 | ||
c0560973 | 948 | private stopHeartbeat(): void { |
ad2f27c3 JB |
949 | if (this.heartbeatSetInterval) { |
950 | clearInterval(this.heartbeatSetInterval); | |
7dde0b73 | 951 | } |
5ad8570f JB |
952 | } |
953 | ||
15042c5f | 954 | private openWSConnection(options?: ClientOptions & ClientRequestArgs, forceCloseOpened = false): void { |
2891f761 JB |
955 | options = options ?? {}; |
956 | options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; | |
15042c5f JB |
957 | if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) { |
958 | options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; | |
959 | } | |
d5bff457 | 960 | if (this.isWebSocketConnectionOpened() && forceCloseOpened) { |
c0560973 JB |
961 | this.wsConnection.close(); |
962 | } | |
963 | let protocol; | |
964 | switch (this.getOCPPVersion()) { | |
965 | case OCPPVersion.VERSION_16: | |
966 | protocol = 'ocpp' + OCPPVersion.VERSION_16; | |
967 | break; | |
968 | default: | |
969 | this.handleUnsupportedVersion(this.getOCPPVersion()); | |
970 | break; | |
971 | } | |
972 | this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); | |
e9017bfc | 973 | logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()); |
136c90ba JB |
974 | } |
975 | ||
dd119a6b | 976 | private stopMeterValues(connectorId: number) { |
734d790d JB |
977 | if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { |
978 | clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval); | |
dd119a6b JB |
979 | } |
980 | } | |
981 | ||
c0560973 | 982 | private startAuthorizationFileMonitoring(): void { |
23132a44 JB |
983 | const authorizationFile = this.getAuthorizationFile(); |
984 | if (authorizationFile) { | |
5ad8570f | 985 | try { |
3ec10737 JB |
986 | fs.watch(authorizationFile, (event, filename) => { |
987 | if (filename && event === 'change') { | |
988 | try { | |
989 | logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload'); | |
990 | // Initialize authorizedTags | |
991 | this.authorizedTags = this.getAuthorizedTags(); | |
992 | } catch (error) { | |
993 | logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error); | |
994 | } | |
23132a44 JB |
995 | } |
996 | }); | |
5ad8570f | 997 | } catch (error) { |
23132a44 | 998 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error); |
5ad8570f | 999 | } |
23132a44 JB |
1000 | } else { |
1001 | logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes'); | |
1002 | } | |
5ad8570f JB |
1003 | } |
1004 | ||
c0560973 | 1005 | private startStationTemplateFileMonitoring(): void { |
23132a44 | 1006 | try { |
b809adf1 | 1007 | fs.watch(this.stationTemplateFile, (event, filename): void => { |
3ec10737 JB |
1008 | if (filename && event === 'change') { |
1009 | try { | |
1010 | logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload'); | |
1011 | // Initialize | |
1012 | this.initialize(); | |
1013 | // Restart the ATG | |
1014 | if (!this.stationInfo.AutomaticTransactionGenerator.enable && | |
32b02249 | 1015 | this.automaticTransactionGenerator) { |
0045cef5 | 1016 | this.automaticTransactionGenerator.stop(); |
3ec10737 JB |
1017 | } |
1018 | this.startAutomaticTransactionGenerator(); | |
1019 | if (this.getEnableStatistics()) { | |
1020 | this.performanceStatistics.restart(); | |
1021 | } else { | |
1022 | this.performanceStatistics.stop(); | |
1023 | } | |
1024 | // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed | |
1025 | } catch (error) { | |
1026 | logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error); | |
087a502d | 1027 | } |
79411696 | 1028 | } |
23132a44 JB |
1029 | }); |
1030 | } catch (error) { | |
1031 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error); | |
1032 | } | |
5ad8570f JB |
1033 | } |
1034 | ||
6e0964c8 | 1035 | private getReconnectExponentialDelay(): boolean | undefined { |
c0560973 | 1036 | return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false; |
5ad8570f JB |
1037 | } |
1038 | ||
d09085e9 | 1039 | private async reconnect(code: number): Promise<void> { |
7874b0b1 JB |
1040 | // Stop WebSocket ping |
1041 | this.stopWebSocketPing(); | |
136c90ba | 1042 | // Stop heartbeat |
c0560973 | 1043 | this.stopHeartbeat(); |
5ad8570f | 1044 | // Stop the ATG if needed |
ad2f27c3 JB |
1045 | if (this.stationInfo.AutomaticTransactionGenerator.enable && |
1046 | this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && | |
265e4266 JB |
1047 | this.automaticTransactionGenerator && |
1048 | this.automaticTransactionGenerator.started) { | |
0045cef5 | 1049 | this.automaticTransactionGenerator.stop(); |
ad2f27c3 | 1050 | } |
c0560973 | 1051 | if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) { |
ad2f27c3 | 1052 | this.autoReconnectRetryCount++; |
c0560973 | 1053 | const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000); |
a0f59b75 | 1054 | const reconnectTimeout = reconnectDelay - 100; |
5dc8b1b5 | 1055 | logger.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`); |
032d6efc | 1056 | await Utils.sleep(reconnectDelay); |
5dc8b1b5 | 1057 | logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString()); |
a0f59b75 | 1058 | this.openWSConnection({ handshakeTimeout: reconnectTimeout }, true); |
265e4266 | 1059 | this.wsConnectionRestarted = true; |
c0560973 | 1060 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
5dc8b1b5 | 1061 | logger.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`); |
5ad8570f JB |
1062 | } |
1063 | } | |
1064 | ||
6ed92bc1 | 1065 | private initTransactionAttributesOnConnector(connectorId: number): void { |
734d790d JB |
1066 | this.getConnectorStatus(connectorId).authorized = false; |
1067 | this.getConnectorStatus(connectorId).transactionStarted = false; | |
1068 | this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0; | |
1069 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
0a60c33c | 1070 | } |
7dde0b73 JB |
1071 | } |
1072 |