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