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