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