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) { | |
163547b1 | 147 | return this.getConnector(Utils.convertToInt(connector)).transactionIdTag; |
c0560973 JB |
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)) { | |
163547b1 | 222 | 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 |
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 | 377 | if (chargingProfile.chargingProfileId === cp.chargingProfileId |
8e4e1939 | 378 | || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) { |
c0560973 JB |
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 { | |
163547b1 | 389 | this.getConnector(connectorId).authorized = false; |
6ed92bc1 | 390 | this.getConnector(connectorId).transactionStarted = false; |
163547b1 | 391 | delete this.getConnector(connectorId).authorizeIdTag; |
6ed92bc1 | 392 | delete this.getConnector(connectorId).transactionId; |
163547b1 | 393 | delete this.getConnector(connectorId).transactionIdTag; |
6ed92bc1 | 394 | this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0; |
fd0c36fa | 395 | delete this.getConnector(connectorId).transactionBeginMeterValue; |
dd119a6b | 396 | this.stopMeterValues(connectorId); |
2e6f5966 JB |
397 | } |
398 | ||
77f00f84 | 399 | public addToMessageQueue(message: string): void { |
3ba2381e | 400 | let dups = false; |
cb31c873 | 401 | // Handle dups in message queue |
3ba2381e | 402 | for (const bufferedMessage of this.messageQueue) { |
cb31c873 | 403 | // Message already in the queue |
3ba2381e JB |
404 | if (message === bufferedMessage) { |
405 | dups = true; | |
406 | break; | |
407 | } | |
408 | } | |
409 | if (!dups) { | |
cb31c873 | 410 | // Queue message |
3ba2381e JB |
411 | this.messageQueue.push(message); |
412 | } | |
413 | } | |
414 | ||
77f00f84 JB |
415 | private flushMessageQueue() { |
416 | if (!Utils.isEmptyArray(this.messageQueue)) { | |
417 | this.messageQueue.forEach((message, index) => { | |
418 | this.messageQueue.splice(index, 1); | |
419 | this.wsConnection.send(message); | |
420 | }); | |
421 | } | |
422 | } | |
423 | ||
c0560973 | 424 | private getChargingStationId(stationTemplate: ChargingStationTemplate): string { |
ef6076c1 | 425 | // In case of multiple instances: add instance index to charging station id |
9ccca265 | 426 | let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; |
ef6076c1 | 427 | instanceIndex = instanceIndex > 0 ? instanceIndex : ''; |
9ccca265 | 428 | const idSuffix = stationTemplate.nameSuffix ?? ''; |
ad2f27c3 | 429 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix; |
5ad8570f JB |
430 | } |
431 | ||
c0560973 | 432 | private buildStationInfo(): ChargingStationInfo { |
9ac86a7e | 433 | let stationTemplateFromFile: ChargingStationTemplate; |
5ad8570f JB |
434 | try { |
435 | // Load template file | |
ad2f27c3 | 436 | const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r'); |
9ac86a7e | 437 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate; |
5ad8570f JB |
438 | fs.closeSync(fileDescriptor); |
439 | } catch (error) { | |
23132a44 | 440 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error); |
5ad8570f | 441 | } |
510f0fa5 | 442 | const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo; |
0a60c33c | 443 | if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { |
9ac86a7e | 444 | stationTemplateFromFile.power = stationTemplateFromFile.power as number[]; |
510f0fa5 JB |
445 | const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length); |
446 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT | |
447 | ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000 | |
448 | : stationTemplateFromFile.power[powerArrayRandomIndex]; | |
5ad8570f | 449 | } else { |
510f0fa5 JB |
450 | stationTemplateFromFile.power = stationTemplateFromFile.power as number; |
451 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT | |
fd0c36fa | 452 | ? stationTemplateFromFile.power * 1000 |
510f0fa5 | 453 | : stationTemplateFromFile.power; |
5ad8570f | 454 | } |
fd0c36fa JB |
455 | delete stationInfo.power; |
456 | delete stationInfo.powerUnit; | |
c0560973 | 457 | stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile); |
9ac86a7e JB |
458 | stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
459 | return stationInfo; | |
5ad8570f JB |
460 | } |
461 | ||
c0560973 JB |
462 | private getOCPPVersion(): OCPPVersion { |
463 | return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16; | |
464 | } | |
465 | ||
466 | private handleUnsupportedVersion(version: OCPPVersion) { | |
467 | const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`; | |
468 | logger.error(errMsg); | |
469 | throw new Error(errMsg); | |
470 | } | |
471 | ||
472 | private initialize(): void { | |
473 | this.stationInfo = this.buildStationInfo(); | |
ad2f27c3 JB |
474 | this.bootNotificationRequest = { |
475 | chargePointModel: this.stationInfo.chargePointModel, | |
476 | chargePointVendor: this.stationInfo.chargePointVendor, | |
477 | ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix }, | |
478 | ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion }, | |
2e6f5966 | 479 | }; |
c0560973 JB |
480 | this.configuration = this.getTemplateChargingStationConfiguration(); |
481 | this.supervisionUrl = this.getSupervisionURL(); | |
ad2f27c3 | 482 | this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId; |
0a60c33c | 483 | // Build connectors if needed |
c0560973 | 484 | const maxConnectors = this.getMaxNumberOfConnectors(); |
6ecb15e4 | 485 | if (maxConnectors <= 0) { |
c0560973 | 486 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`); |
7abfea5f | 487 | } |
c0560973 | 488 | const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors(); |
7abfea5f | 489 | if (templateMaxConnectors <= 0) { |
c0560973 | 490 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`); |
593cf3f9 | 491 | } |
ad2f27c3 | 492 | if (!this.stationInfo.Connectors[0]) { |
c0560973 | 493 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`); |
7abfea5f JB |
494 | } |
495 | // Sanity check | |
ad2f27c3 | 496 | if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) { |
c0560973 | 497 | logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`); |
ad2f27c3 | 498 | this.stationInfo.randomConnectors = true; |
6ecb15e4 | 499 | } |
ad2f27c3 | 500 | const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); |
de1f5008 | 501 | // FIXME: Handle shrinking the number of connectors |
ad2f27c3 JB |
502 | if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) { |
503 | this.connectorsConfigurationHash = connectorsConfigHash; | |
7abfea5f | 504 | // Add connector Id 0 |
6af9012e | 505 | let lastConnector = '0'; |
ad2f27c3 | 506 | for (lastConnector in this.stationInfo.Connectors) { |
c0560973 | 507 | if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) { |
ad2f27c3 JB |
508 | this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]); |
509 | this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE; | |
418106c8 JB |
510 | if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) { |
511 | this.connectors[lastConnector].chargingProfiles = []; | |
512 | } | |
0a60c33c JB |
513 | } |
514 | } | |
0a60c33c | 515 | // Generate all connectors |
ad2f27c3 | 516 | if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { |
7abfea5f | 517 | for (let index = 1; index <= maxConnectors; index++) { |
5a20b4fd JB |
518 | const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index; |
519 | this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]); | |
ad2f27c3 | 520 | this.connectors[index].availability = AvailabilityType.OPERATIVE; |
418106c8 JB |
521 | if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) { |
522 | this.connectors[index].chargingProfiles = []; | |
523 | } | |
7abfea5f | 524 | } |
0a60c33c JB |
525 | } |
526 | } | |
d4a73fb7 | 527 | // Avoid duplication of connectors related information |
ad2f27c3 | 528 | delete this.stationInfo.Connectors; |
0a60c33c | 529 | // Initialize transaction attributes on connectors |
ad2f27c3 | 530 | for (const connector in this.connectors) { |
593cf3f9 | 531 | if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
6ed92bc1 | 532 | this.initTransactionAttributesOnConnector(Utils.convertToInt(connector)); |
0a60c33c JB |
533 | } |
534 | } | |
c0560973 JB |
535 | switch (this.getOCPPVersion()) { |
536 | case OCPPVersion.VERSION_16: | |
537 | this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this); | |
538 | this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this)); | |
539 | break; | |
540 | default: | |
541 | this.handleUnsupportedVersion(this.getOCPPVersion()); | |
542 | break; | |
543 | } | |
7abfea5f | 544 | // OCPP parameters |
147d0e0f JB |
545 | this.initOCPPParameters(); |
546 | this.stationInfo.powerDivider = this.getPowerDivider(); | |
547 | if (this.getEnableStatistics()) { | |
548 | this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId); | |
549 | this.performanceObserver = new PerformanceObserver((list) => { | |
550 | const entry = list.getEntries()[0]; | |
551 | this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION); | |
552 | this.performanceObserver.disconnect(); | |
553 | }); | |
554 | } | |
555 | } | |
556 | ||
557 | private initOCPPParameters(): void { | |
36f6a92e JB |
558 | if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { |
559 | this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`); | |
560 | } | |
c0560973 JB |
561 | this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true); |
562 | if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { | |
563 | this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER); | |
7abfea5f | 564 | } |
7e1dc878 JB |
565 | if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) { |
566 | const connectorPhaseRotation = []; | |
567 | for (const connector in this.connectors) { | |
568 | // AC/DC | |
569 | if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) { | |
570 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`); | |
571 | } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) { | |
572 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`); | |
573 | // AC | |
574 | } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) { | |
575 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`); | |
576 | } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) { | |
577 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`); | |
578 | } | |
579 | } | |
580 | this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString()); | |
581 | } | |
36f6a92e JB |
582 | if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) { |
583 | this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); | |
584 | } | |
585 | if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) | |
586 | && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) { | |
587 | this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false'); | |
588 | } | |
147d0e0f JB |
589 | if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
590 | this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString()); | |
8bce55bf | 591 | } |
7dde0b73 JB |
592 | } |
593 | ||
c0560973 JB |
594 | private async onOpen(): Promise<void> { |
595 | logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`); | |
596 | if (!this.isRegistered()) { | |
597 | // Send BootNotification | |
598 | let registrationRetryCount = 0; | |
599 | do { | |
43d673d9 JB |
600 | this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, |
601 | this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion); | |
c0560973 JB |
602 | if (!this.isRegistered()) { |
603 | registrationRetryCount++; | |
604 | await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL); | |
605 | } | |
606 | } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1)); | |
c7db4718 JB |
607 | } |
608 | if (this.isRegistered()) { | |
c0560973 | 609 | await this.startMessageSequence(); |
3ba49ba9 | 610 | this.hasStopped && (this.hasStopped = false); |
c0560973 | 611 | if (this.hasSocketRestarted && this.isWebSocketOpen()) { |
77f00f84 | 612 | this.flushMessageQueue(); |
2e6f5966 JB |
613 | } |
614 | } else { | |
c0560973 | 615 | logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`); |
2e6f5966 | 616 | } |
c0560973 JB |
617 | this.autoReconnectRetryCount = 0; |
618 | this.hasSocketRestarted = false; | |
2e6f5966 JB |
619 | } |
620 | ||
6e0964c8 | 621 | private async onClose(closeEvent: any): Promise<void> { |
c0560973 JB |
622 | switch (closeEvent) { |
623 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close | |
624 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: | |
625 | logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`); | |
626 | this.autoReconnectRetryCount = 0; | |
627 | break; | |
628 | default: // Abnormal close | |
629 | logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`); | |
630 | await this.reconnect(closeEvent); | |
631 | break; | |
632 | } | |
2e6f5966 JB |
633 | } |
634 | ||
c0560973 JB |
635 | private async onMessage(messageEvent: MessageEvent): Promise<void> { |
636 | let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}]; | |
193d2c0a | 637 | let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void; |
c0560973 JB |
638 | let rejectCallback: (error: OCPPError) => void; |
639 | let requestPayload: Record<string, unknown>; | |
640 | let errMsg: string; | |
641 | try { | |
642 | // Parse the message | |
643 | [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest; | |
c0560973 JB |
644 | // Check the Type of message |
645 | switch (messageType) { | |
646 | // Incoming Message | |
647 | case MessageType.CALL_MESSAGE: | |
648 | if (this.getEnableStatistics()) { | |
54b1efe0 | 649 | this.performanceStatistics.addMessage(commandName, messageType); |
c0560973 JB |
650 | } |
651 | // Process the call | |
652 | await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload); | |
653 | break; | |
654 | // Outcome Message | |
655 | case MessageType.CALL_RESULT_MESSAGE: | |
656 | // Respond | |
657 | if (Utils.isIterable(this.requests[messageId])) { | |
658 | [responseCallback, , requestPayload] = this.requests[messageId]; | |
659 | } else { | |
660 | throw new Error(`Response request for message id ${messageId} is not iterable`); | |
661 | } | |
662 | if (!responseCallback) { | |
663 | // Error | |
664 | throw new Error(`Response request for unknown message id ${messageId}`); | |
665 | } | |
666 | delete this.requests[messageId]; | |
667 | responseCallback(commandName, requestPayload); | |
668 | break; | |
669 | // Error Message | |
670 | case MessageType.CALL_ERROR_MESSAGE: | |
671 | if (!this.requests[messageId]) { | |
672 | // Error | |
673 | throw new Error(`Error request for unknown message id ${messageId}`); | |
674 | } | |
675 | if (Utils.isIterable(this.requests[messageId])) { | |
676 | [, rejectCallback] = this.requests[messageId]; | |
677 | } else { | |
678 | throw new Error(`Error request for message id ${messageId} is not iterable`); | |
679 | } | |
680 | delete this.requests[messageId]; | |
681 | rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails)); | |
682 | break; | |
683 | // Error | |
684 | default: | |
685 | errMsg = `${this.logPrefix()} Wrong message type ${messageType}`; | |
686 | logger.error(errMsg); | |
687 | throw new Error(errMsg); | |
688 | } | |
689 | } catch (error) { | |
690 | // Log | |
691 | logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]); | |
692 | // Send error | |
693 | messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName); | |
694 | } | |
2328be1e JB |
695 | } |
696 | ||
c0560973 JB |
697 | private onPing(): void { |
698 | logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server'); | |
699 | } | |
700 | ||
701 | private onPong(): void { | |
702 | logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server'); | |
703 | } | |
704 | ||
6e0964c8 | 705 | private async onError(errorEvent: any): Promise<void> { |
c0560973 | 706 | logger.error(this.logPrefix() + ' Socket error: %j', errorEvent); |
0a44f741 | 707 | // switch (errorEvent.code) { |
c0560973 JB |
708 | // case 'ECONNREFUSED': |
709 | // await this._reconnect(errorEvent); | |
710 | // break; | |
711 | // } | |
712 | } | |
713 | ||
714 | private getTemplateChargingStationConfiguration(): ChargingStationConfiguration { | |
715 | return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration; | |
716 | } | |
717 | ||
6e0964c8 | 718 | private getAuthorizationFile(): string | undefined { |
bf1866b2 | 719 | return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile)); |
c0560973 JB |
720 | } |
721 | ||
722 | private getAuthorizedTags(): string[] { | |
723 | let authorizedTags: string[] = []; | |
724 | const authorizationFile = this.getAuthorizationFile(); | |
725 | if (authorizationFile) { | |
726 | try { | |
727 | // Load authorization file | |
728 | const fileDescriptor = fs.openSync(authorizationFile, 'r'); | |
729 | authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[]; | |
730 | fs.closeSync(fileDescriptor); | |
731 | } catch (error) { | |
23132a44 | 732 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error); |
c0560973 JB |
733 | } |
734 | } else { | |
735 | logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile); | |
8c4da341 | 736 | } |
c0560973 JB |
737 | return authorizedTags; |
738 | } | |
739 | ||
6e0964c8 | 740 | private getUseConnectorId0(): boolean | undefined { |
c0560973 | 741 | return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true; |
8bce55bf JB |
742 | } |
743 | ||
c0560973 | 744 | private getNumberOfRunningTransactions(): number { |
6ecb15e4 | 745 | let trxCount = 0; |
ad2f27c3 | 746 | for (const connector in this.connectors) { |
593cf3f9 | 747 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
6ecb15e4 JB |
748 | trxCount++; |
749 | } | |
750 | } | |
751 | return trxCount; | |
752 | } | |
753 | ||
1f761b9a | 754 | // 0 for disabling |
6e0964c8 | 755 | private getConnectionTimeout(): number | undefined { |
291cb255 JB |
756 | if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
757 | return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT; | |
758 | } | |
291cb255 | 759 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
3574dfd3 JB |
760 | } |
761 | ||
1f761b9a | 762 | // -1 for unlimited, 0 for disabling |
6e0964c8 | 763 | private getAutoReconnectMaxRetries(): number | undefined { |
ad2f27c3 JB |
764 | if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { |
765 | return this.stationInfo.autoReconnectMaxRetries; | |
3574dfd3 JB |
766 | } |
767 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { | |
768 | return Configuration.getAutoReconnectMaxRetries(); | |
769 | } | |
770 | return -1; | |
771 | } | |
772 | ||
ec977daf | 773 | // 0 for disabling |
6e0964c8 | 774 | private getRegistrationMaxRetries(): number | undefined { |
ad2f27c3 JB |
775 | if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { |
776 | return this.stationInfo.registrationMaxRetries; | |
32a1eb7a JB |
777 | } |
778 | return -1; | |
779 | } | |
780 | ||
c0560973 JB |
781 | private getPowerDivider(): number { |
782 | let powerDivider = this.getNumberOfConnectors(); | |
ad2f27c3 | 783 | if (this.stationInfo.powerSharedByConnectors) { |
c0560973 | 784 | powerDivider = this.getNumberOfRunningTransactions(); |
6ecb15e4 JB |
785 | } |
786 | return powerDivider; | |
787 | } | |
788 | ||
c0560973 | 789 | private getTemplateMaxNumberOfConnectors(): number { |
ad2f27c3 | 790 | return Object.keys(this.stationInfo.Connectors).length; |
7abfea5f JB |
791 | } |
792 | ||
c0560973 | 793 | private getMaxNumberOfConnectors(): number { |
5ad8570f | 794 | let maxConnectors = 0; |
ad2f27c3 JB |
795 | if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) { |
796 | const numberOfConnectors = this.stationInfo.numberOfConnectors as number[]; | |
6ecb15e4 | 797 | // Distribute evenly the number of connectors |
ad2f27c3 JB |
798 | maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length]; |
799 | } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) { | |
800 | maxConnectors = this.stationInfo.numberOfConnectors as number; | |
488fd3a7 | 801 | } else { |
c0560973 | 802 | maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors(); |
5ad8570f JB |
803 | } |
804 | return maxConnectors; | |
2e6f5966 JB |
805 | } |
806 | ||
c0560973 | 807 | private getNumberOfConnectors(): number { |
ad2f27c3 | 808 | return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length; |
6ecb15e4 JB |
809 | } |
810 | ||
c0560973 | 811 | private async startMessageSequence(): Promise<void> { |
136c90ba | 812 | // Start WebSocket ping |
c0560973 | 813 | this.startWebSocketPing(); |
5ad8570f | 814 | // Start heartbeat |
c0560973 | 815 | this.startHeartbeat(); |
0a60c33c | 816 | // Initialize connectors status |
ad2f27c3 | 817 | for (const connector in this.connectors) { |
593cf3f9 JB |
818 | if (Utils.convertToInt(connector) === 0) { |
819 | continue; | |
ad2f27c3 | 820 | } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) { |
136c90ba | 821 | // Send status in template at startup |
c0560973 JB |
822 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
823 | this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus; | |
ad2f27c3 | 824 | } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) { |
136c90ba | 825 | // Send status in template after reset |
c0560973 JB |
826 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
827 | this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus; | |
ad2f27c3 | 828 | } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) { |
136c90ba | 829 | // Send previous status at template reload |
c0560973 | 830 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status); |
5ad8570f | 831 | } else { |
136c90ba | 832 | // Send default status |
c0560973 JB |
833 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE); |
834 | this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE; | |
5ad8570f JB |
835 | } |
836 | } | |
0a60c33c | 837 | // Start the ATG |
dd119a6b JB |
838 | this.startAutomaticTransactionGenerator(); |
839 | if (this.getEnableStatistics()) { | |
840 | this.performanceStatistics.start(); | |
841 | } | |
842 | } | |
843 | ||
844 | private startAutomaticTransactionGenerator() { | |
ad2f27c3 JB |
845 | if (this.stationInfo.AutomaticTransactionGenerator.enable) { |
846 | if (!this.automaticTransactionGeneration) { | |
847 | this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this); | |
5ad8570f | 848 | } |
ad2f27c3 | 849 | if (this.automaticTransactionGeneration.timeToStop) { |
a1256107 JB |
850 | // The ATG might sleep |
851 | void this.automaticTransactionGeneration.start(); | |
5ad8570f JB |
852 | } |
853 | } | |
5ad8570f JB |
854 | } |
855 | ||
c0560973 | 856 | private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
136c90ba | 857 | // Stop WebSocket ping |
c0560973 | 858 | this.stopWebSocketPing(); |
79411696 | 859 | // Stop heartbeat |
c0560973 | 860 | this.stopHeartbeat(); |
79411696 | 861 | // Stop the ATG |
ad2f27c3 JB |
862 | if (this.stationInfo.AutomaticTransactionGenerator.enable && |
863 | this.automaticTransactionGeneration && | |
864 | !this.automaticTransactionGeneration.timeToStop) { | |
865 | await this.automaticTransactionGeneration.stop(reason); | |
79411696 | 866 | } else { |
ad2f27c3 | 867 | for (const connector in this.connectors) { |
593cf3f9 | 868 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
c0560973 | 869 | const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId; |
6ed92bc1 JB |
870 | await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId), |
871 | this.getTransactionIdTag(transactionId), reason); | |
79411696 JB |
872 | } |
873 | } | |
874 | } | |
875 | } | |
876 | ||
c0560973 | 877 | private startWebSocketPing(): void { |
9cd3dfb0 JB |
878 | const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) |
879 | ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) | |
880 | : 0; | |
ad2f27c3 JB |
881 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
882 | this.webSocketPingSetInterval = setInterval(() => { | |
c0560973 | 883 | if (this.isWebSocketOpen()) { |
ad2f27c3 | 884 | this.wsConnection.ping((): void => { }); |
136c90ba JB |
885 | } |
886 | }, webSocketPingInterval * 1000); | |
c0560973 | 887 | logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval)); |
ad2f27c3 | 888 | } else if (this.webSocketPingSetInterval) { |
c0560973 | 889 | logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started'); |
136c90ba | 890 | } else { |
c0560973 | 891 | logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`); |
136c90ba JB |
892 | } |
893 | } | |
894 | ||
c0560973 | 895 | private stopWebSocketPing(): void { |
ad2f27c3 JB |
896 | if (this.webSocketPingSetInterval) { |
897 | clearInterval(this.webSocketPingSetInterval); | |
136c90ba JB |
898 | } |
899 | } | |
900 | ||
c0560973 JB |
901 | private getSupervisionURL(): string { |
902 | const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs()); | |
903 | let indexUrl = 0; | |
904 | if (!Utils.isEmptyArray(supervisionUrls)) { | |
905 | if (Configuration.getDistributeStationsToTenantsEqually()) { | |
906 | indexUrl = this.index % supervisionUrls.length; | |
907 | } else { | |
908 | // Get a random url | |
909 | indexUrl = Math.floor(Math.random() * supervisionUrls.length); | |
910 | } | |
911 | return supervisionUrls[indexUrl]; | |
912 | } | |
913 | return supervisionUrls as string; | |
136c90ba JB |
914 | } |
915 | ||
6e0964c8 | 916 | private getHeartbeatInterval(): number | undefined { |
c0560973 JB |
917 | const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval); |
918 | if (HeartbeatInterval) { | |
919 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; | |
920 | } | |
921 | const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval); | |
922 | if (HeartBeatInterval) { | |
923 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; | |
0a60c33c JB |
924 | } |
925 | } | |
926 | ||
c0560973 | 927 | private stopHeartbeat(): void { |
ad2f27c3 JB |
928 | if (this.heartbeatSetInterval) { |
929 | clearInterval(this.heartbeatSetInterval); | |
7dde0b73 | 930 | } |
5ad8570f JB |
931 | } |
932 | ||
c0560973 | 933 | private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void { |
ee6fd7d1 JB |
934 | options ?? {} as WebSocket.ClientOptions; |
935 | options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; | |
c0560973 JB |
936 | if (this.isWebSocketOpen() && forceCloseOpened) { |
937 | this.wsConnection.close(); | |
938 | } | |
939 | let protocol; | |
940 | switch (this.getOCPPVersion()) { | |
941 | case OCPPVersion.VERSION_16: | |
942 | protocol = 'ocpp' + OCPPVersion.VERSION_16; | |
943 | break; | |
944 | default: | |
945 | this.handleUnsupportedVersion(this.getOCPPVersion()); | |
946 | break; | |
947 | } | |
948 | this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); | |
949 | logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl); | |
136c90ba JB |
950 | } |
951 | ||
dd119a6b JB |
952 | private stopMeterValues(connectorId: number) { |
953 | if (this.getConnector(connectorId)?.transactionSetInterval) { | |
954 | clearInterval(this.getConnector(connectorId).transactionSetInterval); | |
955 | } | |
956 | } | |
957 | ||
c0560973 | 958 | private startAuthorizationFileMonitoring(): void { |
23132a44 JB |
959 | const authorizationFile = this.getAuthorizationFile(); |
960 | if (authorizationFile) { | |
5ad8570f | 961 | try { |
fd0c36fa | 962 | fs.watch(authorizationFile).on('change', () => { |
23132a44 JB |
963 | try { |
964 | logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload'); | |
965 | // Initialize authorizedTags | |
966 | this.authorizedTags = this.getAuthorizedTags(); | |
967 | } catch (error) { | |
968 | logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error); | |
969 | } | |
970 | }); | |
5ad8570f | 971 | } catch (error) { |
23132a44 | 972 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error); |
5ad8570f | 973 | } |
23132a44 JB |
974 | } else { |
975 | logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes'); | |
976 | } | |
5ad8570f JB |
977 | } |
978 | ||
c0560973 | 979 | private startStationTemplateFileMonitoring(): void { |
23132a44 | 980 | try { |
fd0c36fa JB |
981 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
982 | fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => { | |
23132a44 JB |
983 | try { |
984 | logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload'); | |
985 | // Initialize | |
986 | this.initialize(); | |
987 | // Stop the ATG | |
988 | if (!this.stationInfo.AutomaticTransactionGenerator.enable && | |
ad2f27c3 | 989 | this.automaticTransactionGeneration) { |
23132a44 JB |
990 | await this.automaticTransactionGeneration.stop(); |
991 | } | |
992 | // Start the ATG | |
993 | this.startAutomaticTransactionGenerator(); | |
994 | // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed | |
995 | } catch (error) { | |
996 | logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error); | |
79411696 | 997 | } |
23132a44 JB |
998 | }); |
999 | } catch (error) { | |
1000 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error); | |
1001 | } | |
5ad8570f JB |
1002 | } |
1003 | ||
6e0964c8 | 1004 | private getReconnectExponentialDelay(): boolean | undefined { |
c0560973 | 1005 | return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false; |
5ad8570f JB |
1006 | } |
1007 | ||
6e0964c8 | 1008 | private async reconnect(error: any): Promise<void> { |
136c90ba | 1009 | // Stop heartbeat |
c0560973 | 1010 | this.stopHeartbeat(); |
5ad8570f | 1011 | // Stop the ATG if needed |
ad2f27c3 JB |
1012 | if (this.stationInfo.AutomaticTransactionGenerator.enable && |
1013 | this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && | |
1014 | this.automaticTransactionGeneration && | |
1015 | !this.automaticTransactionGeneration.timeToStop) { | |
dd119a6b | 1016 | await this.automaticTransactionGeneration.stop(); |
ad2f27c3 | 1017 | } |
c0560973 | 1018 | if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) { |
ad2f27c3 | 1019 | this.autoReconnectRetryCount++; |
c0560973 JB |
1020 | const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000); |
1021 | logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`); | |
032d6efc | 1022 | await Utils.sleep(reconnectDelay); |
c0560973 JB |
1023 | logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString()); |
1024 | this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 }); | |
ad2f27c3 | 1025 | this.hasSocketRestarted = true; |
c0560973 JB |
1026 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
1027 | logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`); | |
5ad8570f JB |
1028 | } |
1029 | } | |
1030 | ||
6ed92bc1 | 1031 | private initTransactionAttributesOnConnector(connectorId: number): void { |
163547b1 | 1032 | this.getConnector(connectorId).authorized = false; |
8bce55bf | 1033 | this.getConnector(connectorId).transactionStarted = false; |
6ed92bc1 JB |
1034 | this.getConnector(connectorId).energyActiveImportRegisterValue = 0; |
1035 | this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
0a60c33c | 1036 | } |
7dde0b73 JB |
1037 | } |
1038 |