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