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'; | |
bc464bb1 | 40 | import getLogger 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; |
1629a152 | 55 | private readonly id: string; |
9e23580d | 56 | private readonly index: number; |
6e0964c8 JB |
57 | private bootNotificationRequest!: BootNotificationRequest; |
58 | private bootNotificationResponse!: BootNotificationResponse | null; | |
59 | private connectorsConfigurationHash!: string; | |
a472cf2b | 60 | private ocppIncomingRequestService!: OCPPIncomingRequestService; |
8e242273 | 61 | private readonly messageBuffer: Set<string>; |
12fc74d6 | 62 | private wsConfiguredConnectionUrl!: URL; |
265e4266 | 63 | private wsConnectionRestarted: boolean; |
a472cf2b | 64 | private stopped: boolean; |
ad2f27c3 | 65 | private autoReconnectRetryCount: number; |
265e4266 | 66 | private automaticTransactionGenerator!: AutomaticTransactionGenerator; |
6e0964c8 | 67 | private webSocketPingSetInterval!: NodeJS.Timeout; |
6af9012e JB |
68 | |
69 | constructor(index: number, stationTemplateFile: string) { | |
1629a152 | 70 | this.id = Utils.generateUUID(); |
ad2f27c3 JB |
71 | this.index = index; |
72 | this.stationTemplateFile = stationTemplateFile; | |
734d790d | 73 | this.connectors = new Map<number, ConnectorStatus>(); |
c0560973 | 74 | this.initialize(); |
2e6f5966 | 75 | |
265e4266 JB |
76 | this.stopped = false; |
77 | this.wsConnectionRestarted = false; | |
ad2f27c3 | 78 | this.autoReconnectRetryCount = 0; |
2e6f5966 | 79 | |
32b02249 | 80 | this.requests = new Map<string, CachedRequest>(); |
8e242273 | 81 | this.messageBuffer = new Set<string>(); |
2e6f5966 | 82 | |
c0560973 JB |
83 | this.authorizedTags = this.getAuthorizedTags(); |
84 | } | |
85 | ||
12fc74d6 | 86 | get wsConnectionUrl(): URL { |
1f5df42a | 87 | return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl).value + '/' + this.stationInfo.chargingStationId) : this.wsConfiguredConnectionUrl; |
12fc74d6 JB |
88 | } |
89 | ||
c0560973 | 90 | public logPrefix(): string { |
54b1efe0 | 91 | return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`); |
c0560973 JB |
92 | } |
93 | ||
802cfa13 JB |
94 | public getBootNotificationRequest(): BootNotificationRequest { |
95 | return this.bootNotificationRequest; | |
96 | } | |
97 | ||
f4bf2abd | 98 | public getRandomIdTag(): string { |
c37528f1 | 99 | const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length); |
c0560973 JB |
100 | return this.authorizedTags[index]; |
101 | } | |
102 | ||
103 | public hasAuthorizedTags(): boolean { | |
104 | return !Utils.isEmptyArray(this.authorizedTags); | |
105 | } | |
106 | ||
6e0964c8 | 107 | public getEnableStatistics(): boolean | undefined { |
c0560973 JB |
108 | return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true; |
109 | } | |
110 | ||
a7fc8211 JB |
111 | public getMayAuthorizeAtRemoteStart(): boolean | undefined { |
112 | return this.stationInfo.mayAuthorizeAtRemoteStart ?? true; | |
113 | } | |
114 | ||
6e0964c8 | 115 | public getNumberOfPhases(): number | undefined { |
7decf1b6 | 116 | switch (this.getCurrentOutType()) { |
4c2b4904 | 117 | case CurrentType.AC: |
c0560973 | 118 | return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3; |
4c2b4904 | 119 | case CurrentType.DC: |
c0560973 JB |
120 | return 0; |
121 | } | |
122 | } | |
123 | ||
d5bff457 | 124 | public isWebSocketConnectionOpened(): boolean { |
e58068fd | 125 | return this?.wsConnection?.readyState === OPEN; |
c0560973 JB |
126 | } |
127 | ||
672fed6e JB |
128 | public getRegistrationStatus(): RegistrationStatus { |
129 | return this?.bootNotificationResponse?.status; | |
130 | } | |
131 | ||
73c4266d JB |
132 | public isInUnknownState(): boolean { |
133 | return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status); | |
134 | } | |
135 | ||
16cd35ad JB |
136 | public isInPendingState(): boolean { |
137 | return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING; | |
138 | } | |
139 | ||
140 | public isInAcceptedState(): boolean { | |
e58068fd | 141 | return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; |
c0560973 JB |
142 | } |
143 | ||
16cd35ad JB |
144 | public isInRejectedState(): boolean { |
145 | return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED; | |
146 | } | |
147 | ||
148 | public isRegistered(): boolean { | |
73c4266d | 149 | return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState()); |
16cd35ad JB |
150 | } |
151 | ||
c0560973 | 152 | public isChargingStationAvailable(): boolean { |
734d790d | 153 | return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE; |
c0560973 JB |
154 | } |
155 | ||
156 | public isConnectorAvailable(id: number): boolean { | |
734d790d | 157 | return this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE; |
c0560973 JB |
158 | } |
159 | ||
54544ef1 JB |
160 | public getNumberOfConnectors(): number { |
161 | return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size; | |
162 | } | |
163 | ||
734d790d JB |
164 | public getConnectorStatus(id: number): ConnectorStatus { |
165 | return this.connectors.get(id); | |
c0560973 JB |
166 | } |
167 | ||
4c2b4904 JB |
168 | public getCurrentOutType(): CurrentType | undefined { |
169 | return this.stationInfo.currentOutType ?? CurrentType.AC; | |
c0560973 JB |
170 | } |
171 | ||
672fed6e JB |
172 | public getOcppStrictCompliance(): boolean { |
173 | return this.stationInfo.ocppStrictCompliance ?? false; | |
174 | } | |
175 | ||
6e0964c8 | 176 | public getVoltageOut(): number | undefined { |
7decf1b6 | 177 | const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`; |
c0560973 | 178 | let defaultVoltageOut: number; |
7decf1b6 | 179 | switch (this.getCurrentOutType()) { |
4c2b4904 JB |
180 | case CurrentType.AC: |
181 | defaultVoltageOut = Voltage.VOLTAGE_230; | |
c0560973 | 182 | break; |
4c2b4904 JB |
183 | case CurrentType.DC: |
184 | defaultVoltageOut = Voltage.VOLTAGE_400; | |
c0560973 JB |
185 | break; |
186 | default: | |
bc464bb1 | 187 | getLogger().error(errMsg); |
290d006c | 188 | throw new Error(errMsg); |
c0560973 JB |
189 | } |
190 | return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut; | |
191 | } | |
192 | ||
6e0964c8 | 193 | public getTransactionIdTag(transactionId: number): string | undefined { |
734d790d JB |
194 | for (const connectorId of this.connectors.keys()) { |
195 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { | |
196 | return this.getConnectorStatus(connectorId).transactionIdTag; | |
c0560973 JB |
197 | } |
198 | } | |
199 | } | |
200 | ||
6ed92bc1 JB |
201 | public getOutOfOrderEndMeterValues(): boolean { |
202 | return this.stationInfo.outOfOrderEndMeterValues ?? false; | |
203 | } | |
204 | ||
205 | public getBeginEndMeterValues(): boolean { | |
206 | return this.stationInfo.beginEndMeterValues ?? false; | |
207 | } | |
208 | ||
209 | public getMeteringPerTransaction(): boolean { | |
210 | return this.stationInfo.meteringPerTransaction ?? true; | |
211 | } | |
212 | ||
fd0c36fa JB |
213 | public getTransactionDataMeterValues(): boolean { |
214 | return this.stationInfo.transactionDataMeterValues ?? false; | |
215 | } | |
216 | ||
9ccca265 JB |
217 | public getMainVoltageMeterValues(): boolean { |
218 | return this.stationInfo.mainVoltageMeterValues ?? true; | |
219 | } | |
220 | ||
6b10669b JB |
221 | public getPhaseLineToLineVoltageMeterValues(): boolean { |
222 | return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false; | |
9bd87386 JB |
223 | } |
224 | ||
6ed92bc1 JB |
225 | public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { |
226 | if (this.getMeteringPerTransaction()) { | |
734d790d JB |
227 | for (const connectorId of this.connectors.keys()) { |
228 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { | |
229 | return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue; | |
6ed92bc1 JB |
230 | } |
231 | } | |
232 | } | |
734d790d JB |
233 | for (const connectorId of this.connectors.keys()) { |
234 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { | |
235 | return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue; | |
c0560973 JB |
236 | } |
237 | } | |
238 | } | |
239 | ||
6ed92bc1 JB |
240 | public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined { |
241 | if (this.getMeteringPerTransaction()) { | |
734d790d | 242 | return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue; |
6ed92bc1 | 243 | } |
734d790d | 244 | return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue; |
6ed92bc1 JB |
245 | } |
246 | ||
c0560973 JB |
247 | public getAuthorizeRemoteTxRequests(): boolean { |
248 | const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests); | |
249 | return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; | |
250 | } | |
251 | ||
252 | public getLocalAuthListEnabled(): boolean { | |
253 | const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled); | |
254 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; | |
255 | } | |
256 | ||
257 | public restartWebSocketPing(): void { | |
258 | // Stop WebSocket ping | |
259 | this.stopWebSocketPing(); | |
260 | // Start WebSocket ping | |
261 | this.startWebSocketPing(); | |
262 | } | |
263 | ||
9ccca265 JB |
264 | public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, |
265 | phase?: MeterValuePhase): SampledValueTemplate | undefined { | |
266 | if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) { | |
bc464bb1 | 267 | getLogger().warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
9bd87386 JB |
268 | return; |
269 | } | |
270 | if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { | |
bc464bb1 | 271 | getLogger().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 |
272 | return; |
273 | } | |
734d790d | 274 | const sampledValueTemplates: SampledValueTemplate[] = this.getConnectorStatus(connectorId).MeterValues; |
9ccca265 | 275 | for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) { |
290d006c | 276 | if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) { |
bc464bb1 | 277 | getLogger().warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
47e22477 | 278 | } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand |
32b02249 | 279 | && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
9ccca265 JB |
280 | return sampledValueTemplates[index]; |
281 | } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand | |
32b02249 | 282 | && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
9ccca265 JB |
283 | return sampledValueTemplates[index]; |
284 | } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER | |
32b02249 | 285 | && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) { |
9ccca265 JB |
286 | return sampledValueTemplates[index]; |
287 | } | |
288 | } | |
9bd87386 | 289 | if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { |
7d75bee1 | 290 | const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`; |
bc464bb1 | 291 | getLogger().error(errorMsg); |
de96acad | 292 | throw new Error(errorMsg); |
9ccca265 | 293 | } |
bc464bb1 | 294 | getLogger().debug(`${this.logPrefix()} No MeterValues for measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
9ccca265 JB |
295 | } |
296 | ||
e644918b JB |
297 | public getAutomaticTransactionGeneratorRequireAuthorize(): boolean { |
298 | return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true; | |
299 | } | |
300 | ||
c0560973 JB |
301 | public startHeartbeat(): void { |
302 | if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) { | |
71623267 JB |
303 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
304 | this.heartbeatSetInterval = setInterval(async (): Promise<void> => { | |
c0560973 JB |
305 | await this.ocppRequestService.sendHeartbeat(); |
306 | }, this.getHeartbeatInterval()); | |
bc464bb1 | 307 | getLogger().info(this.logPrefix() + ' Heartbeat started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())); |
c0560973 | 308 | } else if (this.heartbeatSetInterval) { |
bc464bb1 | 309 | getLogger().info(this.logPrefix() + ' Heartbeat already started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())); |
c0560973 | 310 | } else { |
bc464bb1 | 311 | getLogger().error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`); |
c0560973 JB |
312 | } |
313 | } | |
314 | ||
315 | public restartHeartbeat(): void { | |
316 | // Stop heartbeat | |
317 | this.stopHeartbeat(); | |
318 | // Start heartbeat | |
319 | this.startHeartbeat(); | |
320 | } | |
321 | ||
322 | public startMeterValues(connectorId: number, interval: number): void { | |
323 | if (connectorId === 0) { | |
bc464bb1 | 324 | getLogger().error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`); |
c0560973 JB |
325 | return; |
326 | } | |
734d790d | 327 | if (!this.getConnectorStatus(connectorId)) { |
bc464bb1 | 328 | getLogger().error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`); |
c0560973 JB |
329 | return; |
330 | } | |
734d790d | 331 | if (!this.getConnectorStatus(connectorId)?.transactionStarted) { |
bc464bb1 | 332 | getLogger().error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`); |
c0560973 | 333 | return; |
734d790d | 334 | } else if (this.getConnectorStatus(connectorId)?.transactionStarted && !this.getConnectorStatus(connectorId)?.transactionId) { |
bc464bb1 | 335 | getLogger().error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`); |
c0560973 JB |
336 | return; |
337 | } | |
338 | if (interval > 0) { | |
71623267 | 339 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
734d790d JB |
340 | this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => { |
341 | await this.ocppRequestService.sendMeterValues(connectorId, this.getConnectorStatus(connectorId).transactionId, interval); | |
c0560973 JB |
342 | }, interval); |
343 | } else { | |
bc464bb1 | 344 | getLogger().error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`); |
c0560973 JB |
345 | } |
346 | } | |
347 | ||
348 | public start(): void { | |
7874b0b1 JB |
349 | if (this.getEnableStatistics()) { |
350 | this.performanceStatistics.start(); | |
351 | } | |
c0560973 JB |
352 | this.openWSConnection(); |
353 | // Monitor authorization file | |
354 | this.startAuthorizationFileMonitoring(); | |
355 | // Monitor station template file | |
356 | this.startStationTemplateFileMonitoring(); | |
8bf88613 | 357 | // Handle WebSocket message |
c0560973 | 358 | this.wsConnection.on('message', this.onMessage.bind(this)); |
5dc8b1b5 | 359 | // Handle WebSocket error |
c0560973 | 360 | this.wsConnection.on('error', this.onError.bind(this)); |
5dc8b1b5 | 361 | // Handle WebSocket close |
c0560973 | 362 | this.wsConnection.on('close', this.onClose.bind(this)); |
8bf88613 | 363 | // Handle WebSocket open |
c0560973 | 364 | this.wsConnection.on('open', this.onOpen.bind(this)); |
5dc8b1b5 | 365 | // Handle WebSocket ping |
c0560973 | 366 | this.wsConnection.on('ping', this.onPing.bind(this)); |
5dc8b1b5 | 367 | // Handle WebSocket pong |
c0560973 | 368 | this.wsConnection.on('pong', this.onPong.bind(this)); |
ee0f106b | 369 | parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STARTED, data: { id: this.stationInfo.chargingStationId } }); |
c0560973 JB |
370 | } |
371 | ||
372 | public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { | |
373 | // Stop message sequence | |
374 | await this.stopMessageSequence(reason); | |
734d790d JB |
375 | for (const connectorId of this.connectors.keys()) { |
376 | if (connectorId > 0) { | |
377 | await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.UNAVAILABLE); | |
378 | this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE; | |
c0560973 JB |
379 | } |
380 | } | |
d5bff457 | 381 | if (this.isWebSocketConnectionOpened()) { |
c0560973 JB |
382 | this.wsConnection.close(); |
383 | } | |
7874b0b1 JB |
384 | if (this.getEnableStatistics()) { |
385 | this.performanceStatistics.stop(); | |
386 | } | |
c0560973 | 387 | this.bootNotificationResponse = null; |
ee0f106b | 388 | parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STOPPED, data: { id: this.stationInfo.chargingStationId } }); |
265e4266 | 389 | this.stopped = true; |
c0560973 JB |
390 | } |
391 | ||
6e0964c8 | 392 | public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined { |
7874b0b1 | 393 | return this.configuration.configurationKey.find((configElement) => { |
c0560973 JB |
394 | if (caseInsensitive) { |
395 | return configElement.key.toLowerCase() === key.toLowerCase(); | |
396 | } | |
397 | return configElement.key === key; | |
398 | }); | |
c0560973 JB |
399 | } |
400 | ||
12fc74d6 | 401 | public addConfigurationKey(key: string | StandardParametersKey, value: string, options: { readonly?: boolean, visible?: boolean, reboot?: boolean } = { readonly: false, visible: true, reboot: false }): void { |
c0560973 | 402 | const keyFound = this.getConfigurationKey(key); |
12fc74d6 JB |
403 | const readonly = options.readonly; |
404 | const visible = options.visible; | |
405 | const reboot = options.reboot; | |
c0560973 JB |
406 | if (!keyFound) { |
407 | this.configuration.configurationKey.push({ | |
408 | key, | |
409 | readonly, | |
410 | value, | |
411 | visible, | |
412 | reboot, | |
413 | }); | |
414 | } else { | |
bc464bb1 | 415 | getLogger().error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound); |
c0560973 JB |
416 | } |
417 | } | |
418 | ||
419 | public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void { | |
420 | const keyFound = this.getConfigurationKey(key); | |
421 | if (keyFound) { | |
422 | const keyIndex = this.configuration.configurationKey.indexOf(keyFound); | |
423 | this.configuration.configurationKey[keyIndex].value = value; | |
424 | } else { | |
bc464bb1 | 425 | getLogger().error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value }); |
c0560973 JB |
426 | } |
427 | } | |
428 | ||
a7fc8211 JB |
429 | public setChargingProfile(connectorId: number, cp: ChargingProfile): void { |
430 | let cpReplaced = false; | |
734d790d JB |
431 | if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { |
432 | this.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => { | |
c0560973 | 433 | if (chargingProfile.chargingProfileId === cp.chargingProfileId |
32b02249 | 434 | || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) { |
734d790d | 435 | this.getConnectorStatus(connectorId).chargingProfiles[index] = cp; |
a7fc8211 | 436 | cpReplaced = true; |
c0560973 JB |
437 | } |
438 | }); | |
439 | } | |
734d790d | 440 | !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp); |
c0560973 JB |
441 | } |
442 | ||
a2653482 JB |
443 | public resetConnectorStatus(connectorId: number): void { |
444 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; | |
445 | this.getConnectorStatus(connectorId).idTagAuthorized = false; | |
446 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; | |
734d790d | 447 | this.getConnectorStatus(connectorId).transactionStarted = false; |
a2653482 | 448 | delete this.getConnectorStatus(connectorId).localAuthorizeIdTag; |
734d790d JB |
449 | delete this.getConnectorStatus(connectorId).authorizeIdTag; |
450 | delete this.getConnectorStatus(connectorId).transactionId; | |
451 | delete this.getConnectorStatus(connectorId).transactionIdTag; | |
452 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
453 | delete this.getConnectorStatus(connectorId).transactionBeginMeterValue; | |
dd119a6b | 454 | this.stopMeterValues(connectorId); |
2e6f5966 JB |
455 | } |
456 | ||
8e242273 JB |
457 | public bufferMessage(message: string): void { |
458 | this.messageBuffer.add(message); | |
3ba2381e JB |
459 | } |
460 | ||
8e242273 JB |
461 | private flushMessageBuffer() { |
462 | if (this.messageBuffer.size > 0) { | |
463 | this.messageBuffer.forEach((message) => { | |
aef1b33a | 464 | // TODO: evaluate the need to track performance |
77f00f84 | 465 | this.wsConnection.send(message); |
8e242273 | 466 | this.messageBuffer.delete(message); |
77f00f84 JB |
467 | }); |
468 | } | |
469 | } | |
470 | ||
1f5df42a JB |
471 | private getSupervisionUrlOcppConfiguration(): boolean { |
472 | return this.stationInfo.supervisionUrlOcppConfiguration ?? false; | |
12fc74d6 JB |
473 | } |
474 | ||
c0560973 | 475 | private getChargingStationId(stationTemplate: ChargingStationTemplate): string { |
ef6076c1 | 476 | // In case of multiple instances: add instance index to charging station id |
203bc097 | 477 | const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; |
9ccca265 | 478 | const idSuffix = stationTemplate.nameSuffix ?? ''; |
ad2f27c3 | 479 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix; |
5ad8570f JB |
480 | } |
481 | ||
c0560973 | 482 | private buildStationInfo(): ChargingStationInfo { |
9ac86a7e | 483 | let stationTemplateFromFile: ChargingStationTemplate; |
5ad8570f JB |
484 | try { |
485 | // Load template file | |
ad2f27c3 | 486 | const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r'); |
9ac86a7e | 487 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate; |
5ad8570f JB |
488 | fs.closeSync(fileDescriptor); |
489 | } catch (error) { | |
88184022 | 490 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException); |
5ad8570f | 491 | } |
2dcfe98e JB |
492 | const chargingStationId = this.getChargingStationId(stationTemplateFromFile); |
493 | // Deprecation template keys section | |
494 | this.warnDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', chargingStationId, 'Use \'supervisionUrls\' instead'); | |
495 | this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls'); | |
510f0fa5 | 496 | const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo; |
cd8dd457 | 497 | stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {}; |
0a60c33c | 498 | if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { |
9ac86a7e | 499 | stationTemplateFromFile.power = stationTemplateFromFile.power as number[]; |
c37528f1 | 500 | const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplateFromFile.power.length); |
510f0fa5 JB |
501 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT |
502 | ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000 | |
503 | : stationTemplateFromFile.power[powerArrayRandomIndex]; | |
5ad8570f | 504 | } else { |
510f0fa5 JB |
505 | stationTemplateFromFile.power = stationTemplateFromFile.power as number; |
506 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT | |
fd0c36fa | 507 | ? stationTemplateFromFile.power * 1000 |
510f0fa5 | 508 | : stationTemplateFromFile.power; |
5ad8570f | 509 | } |
fd0c36fa JB |
510 | delete stationInfo.power; |
511 | delete stationInfo.powerUnit; | |
2dcfe98e | 512 | stationInfo.chargingStationId = chargingStationId; |
9ac86a7e JB |
513 | stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
514 | return stationInfo; | |
5ad8570f JB |
515 | } |
516 | ||
1f5df42a | 517 | private getOcppVersion(): OCPPVersion { |
c0560973 JB |
518 | return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16; |
519 | } | |
520 | ||
521 | private handleUnsupportedVersion(version: OCPPVersion) { | |
522 | const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`; | |
bc464bb1 | 523 | getLogger().error(errMsg); |
c0560973 JB |
524 | throw new Error(errMsg); |
525 | } | |
526 | ||
527 | private initialize(): void { | |
528 | this.stationInfo = this.buildStationInfo(); | |
37486900 | 529 | this.configuration = this.getTemplateChargingStationConfiguration(); |
798010fa | 530 | delete this.stationInfo.Configuration; |
ad2f27c3 JB |
531 | this.bootNotificationRequest = { |
532 | chargePointModel: this.stationInfo.chargePointModel, | |
533 | chargePointVendor: this.stationInfo.chargePointVendor, | |
534 | ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix }, | |
535 | ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion }, | |
2e6f5966 | 536 | }; |
0a60c33c | 537 | // Build connectors if needed |
c0560973 | 538 | const maxConnectors = this.getMaxNumberOfConnectors(); |
6ecb15e4 | 539 | if (maxConnectors <= 0) { |
bc464bb1 | 540 | getLogger().warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`); |
7abfea5f | 541 | } |
c0560973 | 542 | const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors(); |
7abfea5f | 543 | if (templateMaxConnectors <= 0) { |
bc464bb1 | 544 | getLogger().warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`); |
593cf3f9 | 545 | } |
ad2f27c3 | 546 | if (!this.stationInfo.Connectors[0]) { |
bc464bb1 | 547 | getLogger().warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`); |
7abfea5f JB |
548 | } |
549 | // Sanity check | |
ad2f27c3 | 550 | if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) { |
bc464bb1 | 551 | getLogger().warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`); |
ad2f27c3 | 552 | this.stationInfo.randomConnectors = true; |
6ecb15e4 | 553 | } |
ad2f27c3 | 554 | const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); |
54544ef1 JB |
555 | const connectorsConfigChanged = this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; |
556 | if (this.connectors?.size === 0 || connectorsConfigChanged) { | |
734d790d | 557 | connectorsConfigChanged && (this.connectors.clear()); |
ad2f27c3 | 558 | this.connectorsConfigurationHash = connectorsConfigHash; |
7abfea5f | 559 | // Add connector Id 0 |
6af9012e | 560 | let lastConnector = '0'; |
ad2f27c3 | 561 | for (lastConnector in this.stationInfo.Connectors) { |
734d790d JB |
562 | const lastConnectorId = Utils.convertToInt(lastConnector); |
563 | if (lastConnectorId === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) { | |
564 | this.connectors.set(lastConnectorId, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])); | |
565 | this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; | |
566 | if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { | |
567 | this.getConnectorStatus(lastConnectorId).chargingProfiles = []; | |
418106c8 | 568 | } |
0a60c33c JB |
569 | } |
570 | } | |
0a60c33c | 571 | // Generate all connectors |
ad2f27c3 | 572 | if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { |
7abfea5f | 573 | for (let index = 1; index <= maxConnectors; index++) { |
72740232 | 574 | const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) : index; |
734d790d JB |
575 | this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])); |
576 | this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; | |
577 | if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { | |
578 | this.getConnectorStatus(index).chargingProfiles = []; | |
418106c8 | 579 | } |
7abfea5f | 580 | } |
0a60c33c JB |
581 | } |
582 | } | |
d4a73fb7 | 583 | // Avoid duplication of connectors related information |
ad2f27c3 | 584 | delete this.stationInfo.Connectors; |
0a60c33c | 585 | // Initialize transaction attributes on connectors |
734d790d JB |
586 | for (const connectorId of this.connectors.keys()) { |
587 | if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) { | |
a2653482 | 588 | this.initializeConnectorStatus(connectorId); |
0a60c33c JB |
589 | } |
590 | } | |
1f5df42a JB |
591 | this.wsConfiguredConnectionUrl = new URL(this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId); |
592 | switch (this.getOcppVersion()) { | |
c0560973 JB |
593 | case OCPPVersion.VERSION_16: |
594 | this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this); | |
595 | this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this)); | |
596 | break; | |
597 | default: | |
1f5df42a | 598 | this.handleUnsupportedVersion(this.getOcppVersion()); |
c0560973 JB |
599 | break; |
600 | } | |
7abfea5f | 601 | // OCPP parameters |
1f5df42a | 602 | this.initOcppParameters(); |
47e22477 JB |
603 | if (this.stationInfo.autoRegister) { |
604 | this.bootNotificationResponse = { | |
605 | currentTime: new Date().toISOString(), | |
606 | interval: this.getHeartbeatInterval() / 1000, | |
607 | status: RegistrationStatus.ACCEPTED | |
608 | }; | |
609 | } | |
147d0e0f JB |
610 | this.stationInfo.powerDivider = this.getPowerDivider(); |
611 | if (this.getEnableStatistics()) { | |
2a370053 | 612 | this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId, this.wsConnectionUrl); |
147d0e0f JB |
613 | } |
614 | } | |
615 | ||
1f5df42a JB |
616 | private initOcppParameters(): void { |
617 | if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl)) { | |
618 | this.addConfigurationKey(VendorDefaultParametersKey.ConnectionUrl, this.getConfiguredSupervisionUrl().href, { reboot: true }); | |
12fc74d6 | 619 | } |
36f6a92e JB |
620 | if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { |
621 | this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`); | |
622 | } | |
12fc74d6 | 623 | this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), { readonly: true }); |
c0560973 JB |
624 | if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { |
625 | this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER); | |
7abfea5f | 626 | } |
7e1dc878 JB |
627 | if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) { |
628 | const connectorPhaseRotation = []; | |
734d790d | 629 | for (const connectorId of this.connectors.keys()) { |
7e1dc878 | 630 | // AC/DC |
734d790d JB |
631 | if (connectorId === 0 && this.getNumberOfPhases() === 0) { |
632 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
633 | } else if (connectorId > 0 && this.getNumberOfPhases() === 0) { | |
634 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
7e1dc878 | 635 | // AC |
734d790d JB |
636 | } else if (connectorId > 0 && this.getNumberOfPhases() === 1) { |
637 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
638 | } else if (connectorId > 0 && this.getNumberOfPhases() === 3) { | |
639 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
7e1dc878 JB |
640 | } |
641 | } | |
642 | this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString()); | |
643 | } | |
36f6a92e JB |
644 | if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) { |
645 | this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); | |
646 | } | |
647 | if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) | |
32b02249 | 648 | && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) { |
36f6a92e JB |
649 | this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false'); |
650 | } | |
147d0e0f JB |
651 | if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
652 | this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString()); | |
8bce55bf | 653 | } |
7dde0b73 JB |
654 | } |
655 | ||
c0560973 | 656 | private async onOpen(): Promise<void> { |
bc464bb1 | 657 | getLogger().info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`); |
672fed6e | 658 | if (!this.isInAcceptedState()) { |
c0560973 JB |
659 | // Send BootNotification |
660 | let registrationRetryCount = 0; | |
661 | do { | |
43d673d9 JB |
662 | this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, |
663 | this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion); | |
672fed6e JB |
664 | if (!this.isInAcceptedState()) { |
665 | this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; | |
c0560973 JB |
666 | await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL); |
667 | } | |
672fed6e | 668 | } while (!this.isInAcceptedState() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1)); |
c7db4718 | 669 | } |
16cd35ad | 670 | if (this.isInAcceptedState()) { |
c0560973 | 671 | await this.startMessageSequence(); |
265e4266 JB |
672 | this.stopped && (this.stopped = false); |
673 | if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) { | |
caad9d6b JB |
674 | this.flushMessageBuffer(); |
675 | } | |
2e6f5966 | 676 | } else { |
bc464bb1 | 677 | getLogger().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: |
bc464bb1 | 688 | getLogger().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: | |
bc464bb1 | 693 | getLogger().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}`; | |
bc464bb1 | 757 | getLogger().error(errMsg); |
14763b46 | 758 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); |
c0560973 JB |
759 | } |
760 | } catch (error) { | |
761 | // Log | |
bc464bb1 | 762 | getLogger().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 { |
bc464bb1 | 769 | getLogger().debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); |
c0560973 JB |
770 | } |
771 | ||
772 | private onPong(): void { | |
bc464bb1 | 773 | getLogger().debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); |
c0560973 JB |
774 | } |
775 | ||
16b0d4e7 | 776 | private async onError(error: WSError): Promise<void> { |
bc464bb1 | 777 | getLogger().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 { | |
bc464bb1 | 806 | getLogger().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> { |
6114e6f1 JB |
879 | if (this.stationInfo.autoRegister) { |
880 | await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, | |
881 | this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion); | |
882 | } | |
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); | |
bc464bb1 | 954 | getLogger().info(this.logPrefix() + ' WebSocket ping started every ' + Utils.formatDurationSeconds(webSocketPingInterval)); |
ad2f27c3 | 955 | } else if (this.webSocketPingSetInterval) { |
bc464bb1 | 956 | getLogger().info(this.logPrefix() + ' WebSocket ping every ' + Utils.formatDurationSeconds(webSocketPingInterval) + ' already started'); |
136c90ba | 957 | } else { |
bc464bb1 | 958 | getLogger().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])) { | |
bc464bb1 | 970 | getLogger().warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key '${key}' usage in file '${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}`); |
2dcfe98e JB |
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 { | |
bc464bb1 | 998 | getLogger().warn(`${this.logPrefix()} No more configured supervision urls available, using the first one`); |
2dcfe98e JB |
999 | } |
1000 | break; | |
1001 | default: | |
bc464bb1 | 1002 | getLogger().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 | } |
bc464bb1 | 1020 | !this.stationInfo.autoRegister && getLogger().warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`); |
47e22477 | 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); | |
bc464bb1 | 1048 | getLogger().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 { | |
bc464bb1 | 1064 | getLogger().debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload'); |
3ec10737 JB |
1065 | // Initialize authorizedTags |
1066 | this.authorizedTags = this.getAuthorizedTags(); | |
1067 | } catch (error) { | |
bc464bb1 | 1068 | getLogger().error(this.logPrefix() + ' Authorization file monitoring error: %j', error); |
3ec10737 | 1069 | } |
23132a44 JB |
1070 | } |
1071 | }); | |
5ad8570f | 1072 | } catch (error) { |
88184022 | 1073 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException); |
5ad8570f | 1074 | } |
23132a44 | 1075 | } else { |
bc464bb1 | 1076 | getLogger().info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes'); |
23132a44 | 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 { | |
bc464bb1 | 1085 | getLogger().debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload'); |
3ec10737 JB |
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) { | |
bc464bb1 | 1101 | getLogger().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; |
bc464bb1 | 1130 | getLogger().error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`); |
032d6efc | 1131 | await Utils.sleep(reconnectDelay); |
bc464bb1 | 1132 | getLogger().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) { |
bc464bb1 | 1136 | getLogger().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 |