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