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