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