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