Fix connectors status at reset.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
c0560973 1import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/RequestResponses';
e118beaa 2import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
84d4e562 3import ChargingStationTemplate, { PowerOutType, VoltageOut } from '../types/ChargingStationTemplate';
10570d97 4import Connectors, { Connector } from '../types/Connectors';
6af9012e 5import { PerformanceObserver, performance } from 'perf_hooks';
c0560973 6import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests';
136c90ba 7import WebSocket, { MessageEvent } from 'ws';
3f40bc9c 8
6af9012e 9import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
c0560973
JB
10import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
11import { ChargingProfile } from '../types/ocpp/ChargingProfile';
9ac86a7e 12import ChargingStationInfo from '../types/ChargingStationInfo';
6af9012e 13import Configuration from '../utils/Configuration';
63b48f77 14import Constants from '../utils/Constants';
d2a64eb5 15import { MessageType } from '../types/ocpp/MessageType';
c0560973
JB
16import { MeterValueMeasurand } from '../types/ocpp/MeterValues';
17import OCPP16IncomingRequestService from './ocpp/1.6/OCCP16IncomingRequestService';
18import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
19import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
63b48f77 20import OCPPError from './OcppError';
c0560973
JB
21import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
22import OCPPRequestService from './ocpp/OCPPRequestService';
23import { OCPPVersion } from '../types/ocpp/OCPPVersion';
24import { StandardParametersKey } from '../types/ocpp/Configuration';
6af9012e 25import Statistics from '../utils/Statistics';
c0560973 26import { StopTransactionReason } from '../types/ocpp/Transaction';
6af9012e 27import Utils from '../utils/Utils';
32a1eb7a 28import { WebSocketCloseEventStatusCode } from '../types/WebSocket';
3f40bc9c
JB
29import crypto from 'crypto';
30import fs from 'fs';
6af9012e 31import logger from '../utils/Logger';
3f40bc9c
JB
32
33export default class ChargingStation {
c0560973
JB
34 public stationTemplateFile: string;
35 public authorizedTags: string[];
ad2f27c3
JB
36 public stationInfo: ChargingStationInfo;
37 public connectors: Connectors;
c0560973
JB
38 public configuration: ChargingStationConfiguration;
39 public hasStopped: boolean;
40 public wsConnection: WebSocket;
41 public requests: Requests;
42 public messageQueue: string[];
ad2f27c3 43 public statistics: Statistics;
c0560973
JB
44 public heartbeatSetInterval: NodeJS.Timeout;
45 public ocppIncomingRequestService: OCPPIncomingRequestService;
46 public ocppRequestService: OCPPRequestService;
ad2f27c3 47 private index: number;
ad2f27c3
JB
48 private bootNotificationRequest: BootNotificationRequest;
49 private bootNotificationResponse: BootNotificationResponse;
ad2f27c3
JB
50 private connectorsConfigurationHash: string;
51 private supervisionUrl: string;
52 private wsConnectionUrl: string;
ad2f27c3
JB
53 private hasSocketRestarted: boolean;
54 private autoReconnectRetryCount: number;
ad2f27c3 55 private automaticTransactionGeneration: AutomaticTransactionGenerator;
ad2f27c3 56 private performanceObserver: PerformanceObserver;
c0560973 57 private webSocketPingSetInterval: NodeJS.Timeout;
6af9012e
JB
58
59 constructor(index: number, stationTemplateFile: string) {
ad2f27c3
JB
60 this.index = index;
61 this.stationTemplateFile = stationTemplateFile;
62 this.connectors = {} as Connectors;
c0560973 63 this.initialize();
2e6f5966 64
ad2f27c3
JB
65 this.hasStopped = false;
66 this.hasSocketRestarted = false;
67 this.autoReconnectRetryCount = 0;
2e6f5966 68
ad2f27c3
JB
69 this.requests = {} as Requests;
70 this.messageQueue = [] as string[];
2e6f5966 71
c0560973
JB
72 this.authorizedTags = this.getAuthorizedTags();
73 }
74
75 public logPrefix(): string {
76 return Utils.logPrefix(` ${this.stationInfo.chargingStationId}:`);
77 }
78
79 public getRandomTagId(): string {
80 const index = Math.floor(Math.random() * this.authorizedTags.length);
81 return this.authorizedTags[index];
82 }
83
84 public hasAuthorizedTags(): boolean {
85 return !Utils.isEmptyArray(this.authorizedTags);
86 }
87
88 public getEnableStatistics(): boolean {
89 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
90 }
91
92 public getNumberOfPhases(): number {
93 switch (this.getPowerOutType()) {
94 case PowerOutType.AC:
95 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
96 case PowerOutType.DC:
97 return 0;
98 }
99 }
100
101 public isWebSocketOpen(): boolean {
102 return this.wsConnection?.readyState === WebSocket.OPEN;
103 }
104
105 public isRegistered(): boolean {
106 return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
107 }
108
109 public isChargingStationAvailable(): boolean {
110 return this.getConnector(0).availability === AvailabilityType.OPERATIVE;
111 }
112
113 public isConnectorAvailable(id: number): boolean {
114 return this.getConnector(id).availability === AvailabilityType.OPERATIVE;
115 }
116
117 public getConnector(id: number): Connector {
118 return this.connectors[id];
119 }
120
121 public getPowerOutType(): PowerOutType {
122 return !Utils.isUndefined(this.stationInfo.powerOutType) ? this.stationInfo.powerOutType : PowerOutType.AC;
123 }
124
125 public getVoltageOut(): number {
126 const errMsg = `${this.logPrefix()} Unknown ${this.getPowerOutType()} powerOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
127 let defaultVoltageOut: number;
128 switch (this.getPowerOutType()) {
129 case PowerOutType.AC:
130 defaultVoltageOut = VoltageOut.VOLTAGE_230;
131 break;
132 case PowerOutType.DC:
133 defaultVoltageOut = VoltageOut.VOLTAGE_400;
134 break;
135 default:
136 logger.error(errMsg);
137 throw Error(errMsg);
138 }
139 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
140 }
141
142 public getTransactionIdTag(transactionId: number): string {
143 for (const connector in this.connectors) {
144 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
145 return this.getConnector(Utils.convertToInt(connector)).idTag;
146 }
147 }
148 }
149
150 public getTransactionMeterStop(transactionId: number): number {
151 for (const connector in this.connectors) {
152 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
153 return this.getConnector(Utils.convertToInt(connector)).lastEnergyActiveImportRegisterValue;
154 }
155 }
156 }
157
158 public getAuthorizeRemoteTxRequests(): boolean {
159 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
160 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
161 }
162
163 public getLocalAuthListEnabled(): boolean {
164 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
165 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
166 }
167
168 public restartWebSocketPing(): void {
169 // Stop WebSocket ping
170 this.stopWebSocketPing();
171 // Start WebSocket ping
172 this.startWebSocketPing();
173 }
174
175 public startHeartbeat(): void {
176 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
177 this.heartbeatSetInterval = setInterval(async () => {
178 await this.ocppRequestService.sendHeartbeat();
179 }, this.getHeartbeatInterval());
180 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
181 } else if (this.heartbeatSetInterval) {
182 logger.info(this.logPrefix() + ' Heartbeat every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) + ' already started');
183 } else {
184 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
185 }
186 }
187
188 public restartHeartbeat(): void {
189 // Stop heartbeat
190 this.stopHeartbeat();
191 // Start heartbeat
192 this.startHeartbeat();
193 }
194
195 public startMeterValues(connectorId: number, interval: number): void {
196 if (connectorId === 0) {
197 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
198 return;
199 }
200 if (!this.getConnector(connectorId)) {
201 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
202 return;
203 }
204 if (!this.getConnector(connectorId)?.transactionStarted) {
205 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
206 return;
207 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
208 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
209 return;
210 }
211 if (interval > 0) {
212 this.getConnector(connectorId).transactionSetInterval = setInterval(async () => {
213 if (this.getEnableStatistics()) {
214 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
215 this.performanceObserver.observe({
216 entryTypes: ['function'],
217 });
218 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
219 } else {
220 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
221 }
222 }, interval);
223 } else {
224 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
225 }
226 }
227
228 public start(): void {
229 this.openWSConnection();
230 // Monitor authorization file
231 this.startAuthorizationFileMonitoring();
232 // Monitor station template file
233 this.startStationTemplateFileMonitoring();
234 // Handle Socket incoming messages
235 this.wsConnection.on('message', this.onMessage.bind(this));
236 // Handle Socket error
237 this.wsConnection.on('error', this.onError.bind(this));
238 // Handle Socket close
239 this.wsConnection.on('close', this.onClose.bind(this));
240 // Handle Socket opening connection
241 this.wsConnection.on('open', this.onOpen.bind(this));
242 // Handle Socket ping
243 this.wsConnection.on('ping', this.onPing.bind(this));
244 // Handle Socket pong
245 this.wsConnection.on('pong', this.onPong.bind(this));
246 }
247
248 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
249 // Stop message sequence
250 await this.stopMessageSequence(reason);
251 for (const connector in this.connectors) {
252 if (Utils.convertToInt(connector) > 0) {
253 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
254 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
255 }
256 }
257 if (this.isWebSocketOpen()) {
258 this.wsConnection.close();
259 }
260 this.bootNotificationResponse = null;
261 this.hasStopped = true;
262 }
263
264 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey {
265 const configurationKey: ConfigurationKey = this.configuration.configurationKey.find((configElement) => {
266 if (caseInsensitive) {
267 return configElement.key.toLowerCase() === key.toLowerCase();
268 }
269 return configElement.key === key;
270 });
271 return configurationKey;
272 }
273
274 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
275 const keyFound = this.getConfigurationKey(key);
276 if (!keyFound) {
277 this.configuration.configurationKey.push({
278 key,
279 readonly,
280 value,
281 visible,
282 reboot,
283 });
284 } else {
285 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
286 }
287 }
288
289 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
290 const keyFound = this.getConfigurationKey(key);
291 if (keyFound) {
292 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
293 this.configuration.configurationKey[keyIndex].value = value;
294 } else {
295 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
296 }
297 }
298
299 public setChargingProfile(connectorId: number, cp: ChargingProfile): boolean {
300 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
301 this.getConnector(connectorId).chargingProfiles.forEach((chargingProfile: ChargingProfile, index: number) => {
302 if (chargingProfile.chargingProfileId === cp.chargingProfileId
303 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
304 this.getConnector(connectorId).chargingProfiles[index] = cp;
305 return true;
306 }
307 });
308 }
309 this.getConnector(connectorId).chargingProfiles.push(cp);
310 return true;
311 }
312
313 public resetTransactionOnConnector(connectorId: number): void {
314 this.initTransactionOnConnector(connectorId);
315 if (this.getConnector(connectorId)?.transactionSetInterval) {
316 clearInterval(this.getConnector(connectorId).transactionSetInterval);
317 }
2e6f5966
JB
318 }
319
c0560973 320 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
ef6076c1
J
321 // In case of multiple instances: add instance index to charging station id
322 let instanceIndex = process.env.CF_INSTANCE_INDEX ? process.env.CF_INSTANCE_INDEX : 0;
323 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
5fdab605 324 const idSuffix = stationTemplate.nameSuffix ? stationTemplate.nameSuffix : '';
ad2f27c3 325 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
5ad8570f
JB
326 }
327
c0560973 328 private buildStationInfo(): ChargingStationInfo {
9ac86a7e 329 let stationTemplateFromFile: ChargingStationTemplate;
5ad8570f
JB
330 try {
331 // Load template file
ad2f27c3 332 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
9ac86a7e 333 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
5ad8570f
JB
334 fs.closeSync(fileDescriptor);
335 } catch (error) {
ad2f27c3 336 logger.error('Template file ' + this.stationTemplateFile + ' loading error: %j', error);
cdd9fed5 337 throw error;
5ad8570f 338 }
9ac86a7e 339 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
0a60c33c 340 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
9ac86a7e
JB
341 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
342 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
5ad8570f 343 } else {
9ac86a7e 344 stationInfo.maxPower = stationTemplateFromFile.power as number;
5ad8570f 345 }
c0560973 346 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
9ac86a7e
JB
347 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
348 return stationInfo;
5ad8570f
JB
349 }
350
c0560973
JB
351 private getOCPPVersion(): OCPPVersion {
352 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
353 }
354
355 private handleUnsupportedVersion(version: OCPPVersion) {
356 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
357 logger.error(errMsg);
358 throw new Error(errMsg);
359 }
360
361 private initialize(): void {
362 this.stationInfo = this.buildStationInfo();
ad2f27c3
JB
363 this.bootNotificationRequest = {
364 chargePointModel: this.stationInfo.chargePointModel,
365 chargePointVendor: this.stationInfo.chargePointVendor,
366 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
367 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
2e6f5966 368 };
c0560973
JB
369 this.configuration = this.getTemplateChargingStationConfiguration();
370 this.supervisionUrl = this.getSupervisionURL();
ad2f27c3 371 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
0a60c33c 372 // Build connectors if needed
c0560973 373 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 374 if (maxConnectors <= 0) {
c0560973 375 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
7abfea5f 376 }
c0560973 377 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
7abfea5f 378 if (templateMaxConnectors <= 0) {
c0560973 379 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
593cf3f9 380 }
ad2f27c3 381 if (!this.stationInfo.Connectors[0]) {
c0560973 382 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
7abfea5f
JB
383 }
384 // Sanity check
ad2f27c3 385 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
c0560973 386 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
ad2f27c3 387 this.stationInfo.randomConnectors = true;
6ecb15e4 388 }
ad2f27c3 389 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
de1f5008 390 // FIXME: Handle shrinking the number of connectors
ad2f27c3
JB
391 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
392 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 393 // Add connector Id 0
6af9012e 394 let lastConnector = '0';
ad2f27c3 395 for (lastConnector in this.stationInfo.Connectors) {
c0560973 396 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
ad2f27c3
JB
397 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
398 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
418106c8
JB
399 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
400 this.connectors[lastConnector].chargingProfiles = [];
401 }
0a60c33c
JB
402 }
403 }
0a60c33c 404 // Generate all connectors
ad2f27c3 405 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
7abfea5f 406 for (let index = 1; index <= maxConnectors; index++) {
ad2f27c3
JB
407 const randConnectorID = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
408 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorID]);
409 this.connectors[index].availability = AvailabilityType.OPERATIVE;
418106c8
JB
410 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
411 this.connectors[index].chargingProfiles = [];
412 }
7abfea5f 413 }
0a60c33c
JB
414 }
415 }
d4a73fb7 416 // Avoid duplication of connectors related information
ad2f27c3 417 delete this.stationInfo.Connectors;
0a60c33c 418 // Initialize transaction attributes on connectors
ad2f27c3 419 for (const connector in this.connectors) {
593cf3f9 420 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
c0560973 421 this.initTransactionOnConnector(Utils.convertToInt(connector));
0a60c33c
JB
422 }
423 }
c0560973
JB
424 switch (this.getOCPPVersion()) {
425 case OCPPVersion.VERSION_16:
426 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
427 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
428 break;
429 default:
430 this.handleUnsupportedVersion(this.getOCPPVersion());
431 break;
432 }
7abfea5f 433 // OCPP parameters
c0560973
JB
434 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
435 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
436 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
7abfea5f 437 }
c0560973 438 this.stationInfo.powerDivider = this.getPowerDivider();
8bce55bf 439 if (this.getEnableStatistics()) {
418106c8 440 this.statistics = new Statistics(this.stationInfo.chargingStationId);
ad2f27c3 441 this.performanceObserver = new PerformanceObserver((list) => {
8bce55bf 442 const entry = list.getEntries()[0];
ad2f27c3
JB
443 this.statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
444 this.performanceObserver.disconnect();
8bce55bf
JB
445 });
446 }
7dde0b73
JB
447 }
448
c0560973
JB
449 private async onOpen(): Promise<void> {
450 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
451 if (!this.isRegistered()) {
452 // Send BootNotification
453 let registrationRetryCount = 0;
454 do {
455 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
456 if (!this.isRegistered()) {
457 registrationRetryCount++;
458 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
459 }
460 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
461 }
462 if (this.isRegistered()) {
463 await this.startMessageSequence();
3ba49ba9 464 this.hasStopped && (this.hasStopped = false);
c0560973
JB
465 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
466 if (!Utils.isEmptyArray(this.messageQueue)) {
467 this.messageQueue.forEach((message, index) => {
468 this.messageQueue.splice(index, 1);
469 this.wsConnection.send(message);
470 });
471 }
2e6f5966
JB
472 }
473 } else {
c0560973 474 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
2e6f5966 475 }
c0560973
JB
476 this.autoReconnectRetryCount = 0;
477 this.hasSocketRestarted = false;
2e6f5966
JB
478 }
479
c0560973
JB
480 private async onClose(closeEvent): Promise<void> {
481 switch (closeEvent) {
482 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
483 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
484 logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
485 this.autoReconnectRetryCount = 0;
486 break;
487 default: // Abnormal close
488 logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
489 await this.reconnect(closeEvent);
490 break;
491 }
2e6f5966
JB
492 }
493
c0560973
JB
494 private async onMessage(messageEvent: MessageEvent): Promise<void> {
495 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
496 let responseCallback: (payload?: Record<string, unknown> | string, requestPayload?: Record<string, unknown>) => void;
497 let rejectCallback: (error: OCPPError) => void;
498 let requestPayload: Record<string, unknown>;
499 let errMsg: string;
500 try {
501 // Parse the message
502 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
5ad8570f 503
c0560973
JB
504 // Check the Type of message
505 switch (messageType) {
506 // Incoming Message
507 case MessageType.CALL_MESSAGE:
508 if (this.getEnableStatistics()) {
509 this.statistics.addMessage(commandName, messageType);
510 }
511 // Process the call
512 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
513 break;
514 // Outcome Message
515 case MessageType.CALL_RESULT_MESSAGE:
516 // Respond
517 if (Utils.isIterable(this.requests[messageId])) {
518 [responseCallback, , requestPayload] = this.requests[messageId];
519 } else {
520 throw new Error(`Response request for message id ${messageId} is not iterable`);
521 }
522 if (!responseCallback) {
523 // Error
524 throw new Error(`Response request for unknown message id ${messageId}`);
525 }
526 delete this.requests[messageId];
527 responseCallback(commandName, requestPayload);
528 break;
529 // Error Message
530 case MessageType.CALL_ERROR_MESSAGE:
531 if (!this.requests[messageId]) {
532 // Error
533 throw new Error(`Error request for unknown message id ${messageId}`);
534 }
535 if (Utils.isIterable(this.requests[messageId])) {
536 [, rejectCallback] = this.requests[messageId];
537 } else {
538 throw new Error(`Error request for message id ${messageId} is not iterable`);
539 }
540 delete this.requests[messageId];
541 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
542 break;
543 // Error
544 default:
545 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
546 logger.error(errMsg);
547 throw new Error(errMsg);
548 }
549 } catch (error) {
550 // Log
551 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
552 // Send error
553 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
554 }
2328be1e
JB
555 }
556
c0560973
JB
557 private onPing(): void {
558 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
559 }
560
561 private onPong(): void {
562 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
563 }
564
565 private async onError(errorEvent): Promise<void> {
566 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
567 // pragma switch (errorEvent.code) {
568 // case 'ECONNREFUSED':
569 // await this._reconnect(errorEvent);
570 // break;
571 // }
572 }
573
574 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
575 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
576 }
577
578 private getAuthorizationFile(): string {
579 return this.stationInfo.authorizationFile && this.stationInfo.authorizationFile;
580 }
581
582 private getAuthorizedTags(): string[] {
583 let authorizedTags: string[] = [];
584 const authorizationFile = this.getAuthorizationFile();
585 if (authorizationFile) {
586 try {
587 // Load authorization file
588 const fileDescriptor = fs.openSync(authorizationFile, 'r');
589 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
590 fs.closeSync(fileDescriptor);
591 } catch (error) {
592 logger.error(this.logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error);
593 throw error;
594 }
595 } else {
596 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
8c4da341 597 }
c0560973
JB
598 return authorizedTags;
599 }
600
601 private getUseConnectorId0(): boolean {
602 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
8bce55bf
JB
603 }
604
c0560973 605 private getNumberOfRunningTransactions(): number {
6ecb15e4 606 let trxCount = 0;
ad2f27c3 607 for (const connector in this.connectors) {
593cf3f9 608 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
6ecb15e4
JB
609 trxCount++;
610 }
611 }
612 return trxCount;
613 }
614
1f761b9a 615 // 0 for disabling
c0560973 616 private getConnectionTimeout(): number {
ad2f27c3
JB
617 if (!Utils.isUndefined(this.stationInfo.connectionTimeout)) {
618 return this.stationInfo.connectionTimeout;
3574dfd3
JB
619 }
620 if (!Utils.isUndefined(Configuration.getConnectionTimeout())) {
621 return Configuration.getConnectionTimeout();
622 }
623 return 30;
624 }
625
1f761b9a 626 // -1 for unlimited, 0 for disabling
c0560973 627 private getAutoReconnectMaxRetries(): number {
ad2f27c3
JB
628 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
629 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
630 }
631 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
632 return Configuration.getAutoReconnectMaxRetries();
633 }
634 return -1;
635 }
636
ec977daf 637 // 0 for disabling
c0560973 638 private getRegistrationMaxRetries(): number {
ad2f27c3
JB
639 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
640 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
641 }
642 return -1;
643 }
644
c0560973
JB
645 private getPowerDivider(): number {
646 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 647 if (this.stationInfo.powerSharedByConnectors) {
c0560973 648 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
649 }
650 return powerDivider;
651 }
652
c0560973 653 private getTemplateMaxNumberOfConnectors(): number {
ad2f27c3 654 return Object.keys(this.stationInfo.Connectors).length;
7abfea5f
JB
655 }
656
c0560973 657 private getMaxNumberOfConnectors(): number {
5ad8570f 658 let maxConnectors = 0;
ad2f27c3
JB
659 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
660 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 661 // Distribute evenly the number of connectors
ad2f27c3
JB
662 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
663 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
664 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 665 } else {
c0560973 666 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
667 }
668 return maxConnectors;
2e6f5966
JB
669 }
670
c0560973 671 private getNumberOfConnectors(): number {
ad2f27c3 672 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
6ecb15e4
JB
673 }
674
c0560973 675 private async startMessageSequence(): Promise<void> {
136c90ba 676 // Start WebSocket ping
c0560973 677 this.startWebSocketPing();
5ad8570f 678 // Start heartbeat
c0560973 679 this.startHeartbeat();
0a60c33c 680 // Initialize connectors status
ad2f27c3 681 for (const connector in this.connectors) {
593cf3f9
JB
682 if (Utils.convertToInt(connector) === 0) {
683 continue;
ad2f27c3 684 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
136c90ba 685 // Send status in template at startup
c0560973
JB
686 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
687 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
ad2f27c3 688 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
136c90ba 689 // Send status in template after reset
c0560973
JB
690 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
691 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
ad2f27c3 692 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
136c90ba 693 // Send previous status at template reload
c0560973 694 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
5ad8570f 695 } else {
136c90ba 696 // Send default status
c0560973
JB
697 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
698 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
699 }
700 }
0a60c33c 701 // Start the ATG
ad2f27c3
JB
702 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
703 if (!this.automaticTransactionGeneration) {
704 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
5ad8570f 705 }
ad2f27c3 706 if (this.automaticTransactionGeneration.timeToStop) {
e268356b 707 await this.automaticTransactionGeneration.start();
5ad8570f
JB
708 }
709 }
8bce55bf 710 if (this.getEnableStatistics()) {
ad2f27c3 711 this.statistics.start();
8bce55bf 712 }
5ad8570f
JB
713 }
714
c0560973 715 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
136c90ba 716 // Stop WebSocket ping
c0560973 717 this.stopWebSocketPing();
79411696 718 // Stop heartbeat
c0560973 719 this.stopHeartbeat();
79411696 720 // Stop the ATG
ad2f27c3
JB
721 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
722 this.automaticTransactionGeneration &&
723 !this.automaticTransactionGeneration.timeToStop) {
724 await this.automaticTransactionGeneration.stop(reason);
79411696 725 } else {
ad2f27c3 726 for (const connector in this.connectors) {
593cf3f9 727 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
c0560973
JB
728 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
729 await this.ocppRequestService.sendStopTransaction(transactionId, this.getTransactionMeterStop(transactionId), this.getTransactionIdTag(transactionId), reason);
79411696
JB
730 }
731 }
732 }
733 }
734
c0560973
JB
735 private startWebSocketPing(): void {
736 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) : 0;
ad2f27c3
JB
737 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
738 this.webSocketPingSetInterval = setInterval(() => {
c0560973 739 if (this.isWebSocketOpen()) {
ad2f27c3 740 this.wsConnection.ping((): void => { });
136c90ba
JB
741 }
742 }, webSocketPingInterval * 1000);
c0560973 743 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
ad2f27c3 744 } else if (this.webSocketPingSetInterval) {
c0560973 745 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
136c90ba 746 } else {
c0560973 747 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
136c90ba
JB
748 }
749 }
750
c0560973 751 private stopWebSocketPing(): void {
ad2f27c3
JB
752 if (this.webSocketPingSetInterval) {
753 clearInterval(this.webSocketPingSetInterval);
754 this.webSocketPingSetInterval = null;
136c90ba
JB
755 }
756 }
757
c0560973
JB
758 private getSupervisionURL(): string {
759 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
760 let indexUrl = 0;
761 if (!Utils.isEmptyArray(supervisionUrls)) {
762 if (Configuration.getDistributeStationsToTenantsEqually()) {
763 indexUrl = this.index % supervisionUrls.length;
764 } else {
765 // Get a random url
766 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
767 }
768 return supervisionUrls[indexUrl];
769 }
770 return supervisionUrls as string;
136c90ba
JB
771 }
772
c0560973
JB
773 private getHeartbeatInterval(): number {
774 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
775 if (HeartbeatInterval) {
776 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
777 }
778 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
779 if (HeartBeatInterval) {
780 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c
JB
781 }
782 }
783
c0560973 784 private stopHeartbeat(): void {
ad2f27c3
JB
785 if (this.heartbeatSetInterval) {
786 clearInterval(this.heartbeatSetInterval);
787 this.heartbeatSetInterval = null;
7dde0b73 788 }
5ad8570f
JB
789 }
790
c0560973
JB
791 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
792 if (Utils.isUndefined(options)) {
793 options = {} as WebSocket.ClientOptions;
794 }
795 if (Utils.isUndefined(options.handshakeTimeout)) {
796 options.handshakeTimeout = this.getConnectionTimeout() * 1000;
797 }
798 if (this.isWebSocketOpen() && forceCloseOpened) {
799 this.wsConnection.close();
800 }
801 let protocol;
802 switch (this.getOCPPVersion()) {
803 case OCPPVersion.VERSION_16:
804 protocol = 'ocpp' + OCPPVersion.VERSION_16;
805 break;
806 default:
807 this.handleUnsupportedVersion(this.getOCPPVersion());
808 break;
809 }
810 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
811 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
136c90ba
JB
812 }
813
c0560973
JB
814 private startAuthorizationFileMonitoring(): void {
815 fs.watch(this.getAuthorizationFile()).on('change', (e) => {
5ad8570f 816 try {
c0560973 817 logger.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
adeb9b56 818 // Initialize authorizedTags
c0560973 819 this.authorizedTags = this.getAuthorizedTags();
5ad8570f 820 } catch (error) {
c0560973 821 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
5ad8570f
JB
822 }
823 });
824 }
825
c0560973 826 private startStationTemplateFileMonitoring(): void {
e268356b 827 fs.watch(this.stationTemplateFile).on('change', async (e): Promise<void> => {
5ad8570f 828 try {
c0560973 829 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
5ad8570f 830 // Initialize
c0560973 831 this.initialize();
ef6076c1 832 // Stop the ATG
ad2f27c3
JB
833 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
834 this.automaticTransactionGeneration) {
e268356b 835 await this.automaticTransactionGeneration.stop();
79411696 836 }
ef6076c1 837 // Start the ATG
ad2f27c3
JB
838 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
839 if (!this.automaticTransactionGeneration) {
840 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
ef6076c1 841 }
ad2f27c3 842 if (this.automaticTransactionGeneration.timeToStop) {
e268356b 843 await this.automaticTransactionGeneration.start();
ef6076c1
J
844 }
845 }
136c90ba 846 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
5ad8570f 847 } catch (error) {
c0560973 848 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
5ad8570f
JB
849 }
850 });
851 }
852
c0560973
JB
853 private getReconnectExponentialDelay(): boolean {
854 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
5ad8570f
JB
855 }
856
c0560973 857 private async reconnect(error): Promise<void> {
136c90ba 858 // Stop heartbeat
c0560973 859 this.stopHeartbeat();
5ad8570f 860 // Stop the ATG if needed
ad2f27c3
JB
861 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
862 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
863 this.automaticTransactionGeneration &&
864 !this.automaticTransactionGeneration.timeToStop) {
865 this.automaticTransactionGeneration.stop().catch(() => { });
866 }
c0560973 867 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
ad2f27c3 868 this.autoReconnectRetryCount++;
c0560973
JB
869 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
870 logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
032d6efc 871 await Utils.sleep(reconnectDelay);
c0560973
JB
872 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
873 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
ad2f27c3 874 this.hasSocketRestarted = true;
c0560973
JB
875 } else if (this.getAutoReconnectMaxRetries() !== -1) {
876 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
5ad8570f
JB
877 }
878 }
879
c0560973 880 private initTransactionOnConnector(connectorId: number): void {
8bce55bf
JB
881 this.getConnector(connectorId).transactionStarted = false;
882 this.getConnector(connectorId).transactionId = null;
883 this.getConnector(connectorId).idTag = null;
884 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
0a60c33c 885 }
7dde0b73
JB
886}
887