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