Fix connectors status at reset.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/RequestResponses';
2 import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
3 import ChargingStationTemplate, { PowerOutType, VoltageOut } from '../types/ChargingStationTemplate';
4 import Connectors, { Connector } from '../types/Connectors';
5 import { PerformanceObserver, performance } from 'perf_hooks';
6 import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests';
7 import WebSocket, { MessageEvent } from 'ws';
8
9 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
10 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
11 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
12 import ChargingStationInfo from '../types/ChargingStationInfo';
13 import Configuration from '../utils/Configuration';
14 import Constants from '../utils/Constants';
15 import { MessageType } from '../types/ocpp/MessageType';
16 import { MeterValueMeasurand } from '../types/ocpp/MeterValues';
17 import OCPP16IncomingRequestService from './ocpp/1.6/OCCP16IncomingRequestService';
18 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
19 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
20 import OCPPError from './OcppError';
21 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
22 import OCPPRequestService from './ocpp/OCPPRequestService';
23 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
24 import { StandardParametersKey } from '../types/ocpp/Configuration';
25 import Statistics from '../utils/Statistics';
26 import { StopTransactionReason } from '../types/ocpp/Transaction';
27 import Utils from '../utils/Utils';
28 import { WebSocketCloseEventStatusCode } from '../types/WebSocket';
29 import crypto from 'crypto';
30 import fs from 'fs';
31 import logger from '../utils/Logger';
32
33 export default class ChargingStation {
34 public stationTemplateFile: string;
35 public authorizedTags: string[];
36 public stationInfo: ChargingStationInfo;
37 public connectors: Connectors;
38 public configuration: ChargingStationConfiguration;
39 public hasStopped: boolean;
40 public wsConnection: WebSocket;
41 public requests: Requests;
42 public messageQueue: string[];
43 public statistics: Statistics;
44 public heartbeatSetInterval: NodeJS.Timeout;
45 public ocppIncomingRequestService: OCPPIncomingRequestService;
46 public ocppRequestService: OCPPRequestService;
47 private index: number;
48 private bootNotificationRequest: BootNotificationRequest;
49 private bootNotificationResponse: BootNotificationResponse;
50 private connectorsConfigurationHash: string;
51 private supervisionUrl: string;
52 private wsConnectionUrl: string;
53 private hasSocketRestarted: boolean;
54 private autoReconnectRetryCount: number;
55 private automaticTransactionGeneration: AutomaticTransactionGenerator;
56 private performanceObserver: PerformanceObserver;
57 private webSocketPingSetInterval: NodeJS.Timeout;
58
59 constructor(index: number, stationTemplateFile: string) {
60 this.index = index;
61 this.stationTemplateFile = stationTemplateFile;
62 this.connectors = {} as Connectors;
63 this.initialize();
64
65 this.hasStopped = false;
66 this.hasSocketRestarted = false;
67 this.autoReconnectRetryCount = 0;
68
69 this.requests = {} as Requests;
70 this.messageQueue = [] as string[];
71
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 }
318 }
319
320 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
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 : '';
324 const idSuffix = stationTemplate.nameSuffix ? stationTemplate.nameSuffix : '';
325 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
326 }
327
328 private buildStationInfo(): ChargingStationInfo {
329 let stationTemplateFromFile: ChargingStationTemplate;
330 try {
331 // Load template file
332 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
333 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
334 fs.closeSync(fileDescriptor);
335 } catch (error) {
336 logger.error('Template file ' + this.stationTemplateFile + ' loading error: %j', error);
337 throw error;
338 }
339 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
340 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
341 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
342 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
343 } else {
344 stationInfo.maxPower = stationTemplateFromFile.power as number;
345 }
346 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
347 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
348 return stationInfo;
349 }
350
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();
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 },
368 };
369 this.configuration = this.getTemplateChargingStationConfiguration();
370 this.supervisionUrl = this.getSupervisionURL();
371 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
372 // Build connectors if needed
373 const maxConnectors = this.getMaxNumberOfConnectors();
374 if (maxConnectors <= 0) {
375 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
376 }
377 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
378 if (templateMaxConnectors <= 0) {
379 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
380 }
381 if (!this.stationInfo.Connectors[0]) {
382 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
383 }
384 // Sanity check
385 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
386 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
387 this.stationInfo.randomConnectors = true;
388 }
389 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
390 // FIXME: Handle shrinking the number of connectors
391 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
392 this.connectorsConfigurationHash = connectorsConfigHash;
393 // Add connector Id 0
394 let lastConnector = '0';
395 for (lastConnector in this.stationInfo.Connectors) {
396 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
397 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
398 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
399 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
400 this.connectors[lastConnector].chargingProfiles = [];
401 }
402 }
403 }
404 // Generate all connectors
405 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
406 for (let index = 1; index <= maxConnectors; index++) {
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;
410 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
411 this.connectors[index].chargingProfiles = [];
412 }
413 }
414 }
415 }
416 // Avoid duplication of connectors related information
417 delete this.stationInfo.Connectors;
418 // Initialize transaction attributes on connectors
419 for (const connector in this.connectors) {
420 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
421 this.initTransactionOnConnector(Utils.convertToInt(connector));
422 }
423 }
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 }
433 // OCPP parameters
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);
437 }
438 this.stationInfo.powerDivider = this.getPowerDivider();
439 if (this.getEnableStatistics()) {
440 this.statistics = new Statistics(this.stationInfo.chargingStationId);
441 this.performanceObserver = new PerformanceObserver((list) => {
442 const entry = list.getEntries()[0];
443 this.statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
444 this.performanceObserver.disconnect();
445 });
446 }
447 }
448
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();
464 this.hasStopped && (this.hasStopped = false);
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 }
472 }
473 } else {
474 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
475 }
476 this.autoReconnectRetryCount = 0;
477 this.hasSocketRestarted = false;
478 }
479
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 }
492 }
493
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;
503
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 }
555 }
556
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);
597 }
598 return authorizedTags;
599 }
600
601 private getUseConnectorId0(): boolean {
602 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
603 }
604
605 private getNumberOfRunningTransactions(): number {
606 let trxCount = 0;
607 for (const connector in this.connectors) {
608 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
609 trxCount++;
610 }
611 }
612 return trxCount;
613 }
614
615 // 0 for disabling
616 private getConnectionTimeout(): number {
617 if (!Utils.isUndefined(this.stationInfo.connectionTimeout)) {
618 return this.stationInfo.connectionTimeout;
619 }
620 if (!Utils.isUndefined(Configuration.getConnectionTimeout())) {
621 return Configuration.getConnectionTimeout();
622 }
623 return 30;
624 }
625
626 // -1 for unlimited, 0 for disabling
627 private getAutoReconnectMaxRetries(): number {
628 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
629 return this.stationInfo.autoReconnectMaxRetries;
630 }
631 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
632 return Configuration.getAutoReconnectMaxRetries();
633 }
634 return -1;
635 }
636
637 // 0 for disabling
638 private getRegistrationMaxRetries(): number {
639 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
640 return this.stationInfo.registrationMaxRetries;
641 }
642 return -1;
643 }
644
645 private getPowerDivider(): number {
646 let powerDivider = this.getNumberOfConnectors();
647 if (this.stationInfo.powerSharedByConnectors) {
648 powerDivider = this.getNumberOfRunningTransactions();
649 }
650 return powerDivider;
651 }
652
653 private getTemplateMaxNumberOfConnectors(): number {
654 return Object.keys(this.stationInfo.Connectors).length;
655 }
656
657 private getMaxNumberOfConnectors(): number {
658 let maxConnectors = 0;
659 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
660 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
661 // Distribute evenly the number of connectors
662 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
663 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
664 maxConnectors = this.stationInfo.numberOfConnectors as number;
665 } else {
666 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
667 }
668 return maxConnectors;
669 }
670
671 private getNumberOfConnectors(): number {
672 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
673 }
674
675 private async startMessageSequence(): Promise<void> {
676 // Start WebSocket ping
677 this.startWebSocketPing();
678 // Start heartbeat
679 this.startHeartbeat();
680 // Initialize connectors status
681 for (const connector in this.connectors) {
682 if (Utils.convertToInt(connector) === 0) {
683 continue;
684 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
685 // Send status in template at startup
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;
688 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
689 // Send status in template after reset
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;
692 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
693 // Send previous status at template reload
694 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
695 } else {
696 // Send default status
697 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
698 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
699 }
700 }
701 // Start the ATG
702 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
703 if (!this.automaticTransactionGeneration) {
704 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
705 }
706 if (this.automaticTransactionGeneration.timeToStop) {
707 await this.automaticTransactionGeneration.start();
708 }
709 }
710 if (this.getEnableStatistics()) {
711 this.statistics.start();
712 }
713 }
714
715 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
716 // Stop WebSocket ping
717 this.stopWebSocketPing();
718 // Stop heartbeat
719 this.stopHeartbeat();
720 // Stop the ATG
721 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
722 this.automaticTransactionGeneration &&
723 !this.automaticTransactionGeneration.timeToStop) {
724 await this.automaticTransactionGeneration.stop(reason);
725 } else {
726 for (const connector in this.connectors) {
727 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
728 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
729 await this.ocppRequestService.sendStopTransaction(transactionId, this.getTransactionMeterStop(transactionId), this.getTransactionIdTag(transactionId), reason);
730 }
731 }
732 }
733 }
734
735 private startWebSocketPing(): void {
736 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) : 0;
737 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
738 this.webSocketPingSetInterval = setInterval(() => {
739 if (this.isWebSocketOpen()) {
740 this.wsConnection.ping((): void => { });
741 }
742 }, webSocketPingInterval * 1000);
743 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
744 } else if (this.webSocketPingSetInterval) {
745 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
746 } else {
747 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
748 }
749 }
750
751 private stopWebSocketPing(): void {
752 if (this.webSocketPingSetInterval) {
753 clearInterval(this.webSocketPingSetInterval);
754 this.webSocketPingSetInterval = null;
755 }
756 }
757
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;
771 }
772
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;
781 }
782 }
783
784 private stopHeartbeat(): void {
785 if (this.heartbeatSetInterval) {
786 clearInterval(this.heartbeatSetInterval);
787 this.heartbeatSetInterval = null;
788 }
789 }
790
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);
812 }
813
814 private startAuthorizationFileMonitoring(): void {
815 fs.watch(this.getAuthorizationFile()).on('change', (e) => {
816 try {
817 logger.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
818 // Initialize authorizedTags
819 this.authorizedTags = this.getAuthorizedTags();
820 } catch (error) {
821 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
822 }
823 });
824 }
825
826 private startStationTemplateFileMonitoring(): void {
827 fs.watch(this.stationTemplateFile).on('change', async (e): Promise<void> => {
828 try {
829 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
830 // Initialize
831 this.initialize();
832 // Stop the ATG
833 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
834 this.automaticTransactionGeneration) {
835 await this.automaticTransactionGeneration.stop();
836 }
837 // Start the ATG
838 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
839 if (!this.automaticTransactionGeneration) {
840 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
841 }
842 if (this.automaticTransactionGeneration.timeToStop) {
843 await this.automaticTransactionGeneration.start();
844 }
845 }
846 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
847 } catch (error) {
848 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
849 }
850 });
851 }
852
853 private getReconnectExponentialDelay(): boolean {
854 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
855 }
856
857 private async reconnect(error): Promise<void> {
858 // Stop heartbeat
859 this.stopHeartbeat();
860 // Stop the ATG if needed
861 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
862 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
863 this.automaticTransactionGeneration &&
864 !this.automaticTransactionGeneration.timeToStop) {
865 this.automaticTransactionGeneration.stop().catch(() => { });
866 }
867 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
868 this.autoReconnectRetryCount++;
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`);
871 await Utils.sleep(reconnectDelay);
872 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
873 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
874 this.hasSocketRestarted = true;
875 } else if (this.getAutoReconnectMaxRetries() !== -1) {
876 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
877 }
878 }
879
880 private initTransactionOnConnector(connectorId: number): void {
881 this.getConnector(connectorId).transactionStarted = false;
882 this.getConnector(connectorId).transactionId = null;
883 this.getConnector(connectorId).idTag = null;
884 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
885 }
886 }
887