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