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