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