85045f7eb0aec2b391f9f6d041cdfe6ee95b8174
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 import { AuthorizationStatus, StartTransactionResponse, StopTransactionReason, StopTransactionResponse } from '../types/ocpp/1.6/Transaction';
2 import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
3 import ChargingStationTemplate, { PowerOutType } from '../types/ChargingStationTemplate';
4 import { ConfigurationResponse, DefaultRequestResponse, UnlockResponse } from '../types/ocpp/1.6/RequestResponses';
5 import Connectors, { Connector } from '../types/Connectors';
6 import MeterValue, { MeterValueLocation, MeterValueMeasurand, MeterValuePhase, MeterValueUnit } from '../types/ocpp/1.6/MeterValue';
7 import { PerformanceObserver, performance } from 'perf_hooks';
8 import WebSocket, { MessageEvent } from 'ws';
9
10 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
11 import { ChargePointErrorCode } from '../types/ocpp/1.6/ChargePointErrorCode';
12 import { ChargePointStatus } from '../types/ocpp/1.6/ChargePointStatus';
13 import ChargingStationInfo from '../types/ChargingStationInfo';
14 import Configuration from '../utils/Configuration';
15 import Constants from '../utils/Constants';
16 import ElectricUtils from '../utils/ElectricUtils';
17 import MeasurandValues from '../types/MeasurandValues';
18 import OCPPError from './OcppError';
19 import Requests from '../types/ocpp/1.6/Requests';
20 import Statistics from '../utils/Statistics';
21 import Utils from '../utils/Utils';
22 import crypto from 'crypto';
23 import fs from 'fs';
24 import logger from '../utils/Logger';
25
26 export default class ChargingStation {
27 private _index: number;
28 private _stationTemplateFile: string;
29 private _stationInfo: ChargingStationInfo;
30 private _bootNotificationMessage: {
31 chargePointModel: string,
32 chargePointVendor: string,
33 chargeBoxSerialNumber?: string,
34 firmwareVersion?: string,
35 };
36
37 private _connectors: Connectors;
38 private _configuration: ChargingStationConfiguration;
39 private _connectorsConfigurationHash: string;
40 private _supervisionUrl: string;
41 private _wsConnectionUrl: string;
42 private _wsConnection: WebSocket;
43 private _hasStopped: boolean;
44 private _hasSocketRestarted: boolean;
45 private _autoReconnectRetryCount: number;
46 private _autoReconnectMaxRetries: number;
47 private _autoReconnectTimeout: number;
48 private _requests: Requests;
49 private _messageQueue: string[];
50 private _automaticTransactionGeneration: AutomaticTransactionGenerator;
51 private _authorizedTags: string[];
52 private _heartbeatInterval: number;
53 private _heartbeatSetInterval: NodeJS.Timeout;
54 private _webSocketPingSetInterval: NodeJS.Timeout;
55 private _statistics: Statistics;
56 private _performanceObserver: PerformanceObserver;
57
58 constructor(index: number, stationTemplateFile: string) {
59 this._index = index;
60 this._stationTemplateFile = stationTemplateFile;
61 this._connectors = {} as Connectors;
62 this._initialize();
63
64 this._hasStopped = false;
65 this._hasSocketRestarted = false;
66 this._autoReconnectRetryCount = 0;
67 this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited
68 this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // Ms, zero for disabling
69
70 this._requests = {} as Requests;
71 this._messageQueue = [] as string[];
72
73 this._authorizedTags = this._loadAndGetAuthorizedTags();
74 }
75
76 _getStationName(stationTemplate: ChargingStationTemplate): string {
77 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index.toString()).substr(('000000000' + this._index.toString()).length - 4);
78 }
79
80 _buildStationInfo(): ChargingStationInfo {
81 let stationTemplateFromFile: ChargingStationTemplate;
82 try {
83 // Load template file
84 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
85 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
86 fs.closeSync(fileDescriptor);
87 } catch (error) {
88 logger.error('Template file ' + this._stationTemplateFile + ' loading error: %j', error);
89 throw error;
90 }
91 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
92 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
93 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
94 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
95 } else {
96 stationInfo.maxPower = stationTemplateFromFile.power as number;
97 }
98 stationInfo.name = this._getStationName(stationTemplateFromFile);
99 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
100 return stationInfo;
101 }
102
103 get stationInfo(): ChargingStationInfo {
104 return this._stationInfo;
105 }
106
107 _initialize(): void {
108 this._stationInfo = this._buildStationInfo();
109 this._bootNotificationMessage = {
110 chargePointModel: this._stationInfo.chargePointModel,
111 chargePointVendor: this._stationInfo.chargePointVendor,
112 ...!Utils.isUndefined(this._stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this._stationInfo.chargeBoxSerialNumberPrefix },
113 ...!Utils.isUndefined(this._stationInfo.firmwareVersion) && { firmwareVersion: this._stationInfo.firmwareVersion },
114 };
115 this._configuration = this._getTemplateChargingStationConfiguration();
116 this._supervisionUrl = this._getSupervisionURL();
117 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
118 // Build connectors if needed
119 const maxConnectors = this._getMaxNumberOfConnectors();
120 if (maxConnectors <= 0) {
121 logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
122 }
123 const templateMaxConnectors = this._getTemplateMaxNumberOfConnectors();
124 if (templateMaxConnectors <= 0) {
125 logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`);
126 }
127 // Sanity check
128 if (maxConnectors > (this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this._stationInfo.randomConnectors) {
129 logger.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
130 this._stationInfo.randomConnectors = true;
131 }
132 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this._stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
133 // FIXME: Handle shrinking the number of connectors
134 if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) {
135 this._connectorsConfigurationHash = connectorsConfigHash;
136 // Add connector Id 0
137 let lastConnector = '0';
138 for (lastConnector in this._stationInfo.Connectors) {
139 if (Utils.convertToInt(lastConnector) === 0 && this._stationInfo.useConnectorId0 && this._stationInfo.Connectors[lastConnector]) {
140 this._connectors[lastConnector] = Utils.cloneObject(this._stationInfo.Connectors[lastConnector]) as Connector;
141 }
142 }
143 // Generate all connectors
144 if ((this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
145 for (let index = 1; index <= maxConnectors; index++) {
146 const randConnectorID = this._stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
147 this._connectors[index] = Utils.cloneObject(this._stationInfo.Connectors[randConnectorID]) as Connector;
148 }
149 }
150 }
151 // Avoid duplication of connectors related information
152 delete this._stationInfo.Connectors;
153 // Initialize transaction attributes on connectors
154 for (const connector in this._connectors) {
155 if (!this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
156 this._initTransactionOnConnector(Utils.convertToInt(connector));
157 }
158 }
159 // OCPP parameters
160 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors().toString(), true);
161 if (!this._getConfigurationKey('MeterValuesSampledData')) {
162 this._addConfigurationKey('MeterValuesSampledData', MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
163 }
164 this._stationInfo.powerDivider = this._getPowerDivider();
165 if (this.getEnableStatistics()) {
166 this._statistics = Statistics.getInstance();
167 this._statistics.objName = this._stationInfo.name;
168 this._performanceObserver = new PerformanceObserver((list) => {
169 const entry = list.getEntries()[0];
170 this._statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
171 this._performanceObserver.disconnect();
172 });
173 }
174 }
175
176 get connectors(): Connectors {
177 return this._connectors;
178 }
179
180 get statistics(): Statistics {
181 return this._statistics;
182 }
183
184 _logPrefix(): string {
185 return Utils.logPrefix(` ${this._stationInfo.name}:`);
186 }
187
188 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
189 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {} as ChargingStationConfiguration;
190 }
191
192 _getAuthorizationFile(): string {
193 return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile;
194 }
195
196 _loadAndGetAuthorizedTags(): string[] {
197 let authorizedTags: string[] = [];
198 const authorizationFile = this._getAuthorizationFile();
199 if (authorizationFile) {
200 try {
201 // Load authorization file
202 const fileDescriptor = fs.openSync(authorizationFile, 'r');
203 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
204 fs.closeSync(fileDescriptor);
205 } catch (error) {
206 logger.error(this._logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error);
207 throw error;
208 }
209 } else {
210 logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile);
211 }
212 return authorizedTags;
213 }
214
215 getRandomTagId(): string {
216 const index = Math.floor(Math.random() * this._authorizedTags.length);
217 return this._authorizedTags[index];
218 }
219
220 hasAuthorizedTags(): boolean {
221 return !Utils.isEmptyArray(this._authorizedTags);
222 }
223
224 getEnableStatistics(): boolean {
225 return !Utils.isUndefined(this._stationInfo.enableStatistics) ? this._stationInfo.enableStatistics : true;
226 }
227
228 _getNumberOfPhases(): number {
229 switch (this._getPowerOutType()) {
230 case PowerOutType.AC:
231 return !Utils.isUndefined(this._stationInfo.numberOfPhases) ? Utils.convertToInt(this._stationInfo.numberOfPhases) : 3;
232 case PowerOutType.DC:
233 return 0;
234 }
235 }
236
237 _getNumberOfRunningTransactions(): number {
238 let trxCount = 0;
239 for (const connector in this._connectors) {
240 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
241 trxCount++;
242 }
243 }
244 return trxCount;
245 }
246
247 _getPowerDivider(): number {
248 let powerDivider = this._getNumberOfConnectors();
249 if (this._stationInfo.powerSharedByConnectors) {
250 powerDivider = this._getNumberOfRunningTransactions();
251 }
252 return powerDivider;
253 }
254
255 getConnector(id: number): Connector {
256 return this._connectors[id];
257 }
258
259 _getTemplateMaxNumberOfConnectors(): number {
260 return Object.keys(this._stationInfo.Connectors).length;
261 }
262
263 _getMaxNumberOfConnectors(): number {
264 let maxConnectors = 0;
265 if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) {
266 const numberOfConnectors = this._stationInfo.numberOfConnectors as number[];
267 // Distribute evenly the number of connectors
268 maxConnectors = numberOfConnectors[(this._index - 1) % numberOfConnectors.length];
269 } else if (!Utils.isUndefined(this._stationInfo.numberOfConnectors)) {
270 maxConnectors = this._stationInfo.numberOfConnectors as number;
271 } else {
272 maxConnectors = this._stationInfo.Connectors[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
273 }
274 return maxConnectors;
275 }
276
277 _getNumberOfConnectors(): number {
278 return this._connectors[0] ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length;
279 }
280
281 _getVoltageOut(): number {
282 const errMsg = `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
283 let defaultVoltageOut: number;
284 switch (this._getPowerOutType()) {
285 case PowerOutType.AC:
286 defaultVoltageOut = 230;
287 break;
288 case PowerOutType.DC:
289 defaultVoltageOut = 400;
290 break;
291 default:
292 logger.error(errMsg);
293 throw Error(errMsg);
294 }
295 return !Utils.isUndefined(this._stationInfo.voltageOut) ? Utils.convertToInt(this._stationInfo.voltageOut) : defaultVoltageOut;
296 }
297
298 _getTransactionidTag(transactionId: number): string {
299 for (const connector in this._connectors) {
300 if (this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
301 return this.getConnector(Utils.convertToInt(connector)).idTag;
302 }
303 }
304 }
305
306 _getPowerOutType(): PowerOutType {
307 return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : PowerOutType.AC;
308 }
309
310 _getSupervisionURL(): string {
311 const supervisionUrls = Utils.cloneObject(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()) as string | string[];
312 let indexUrl = 0;
313 if (!Utils.isEmptyArray(supervisionUrls)) {
314 if (Configuration.getDistributeStationsToTenantsEqually()) {
315 indexUrl = this._index % supervisionUrls.length;
316 } else {
317 // Get a random url
318 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
319 }
320 return supervisionUrls[indexUrl];
321 }
322 return supervisionUrls as string;
323 }
324
325 _getAuthorizeRemoteTxRequests(): boolean {
326 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
327 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
328 }
329
330 _getLocalAuthListEnabled(): boolean {
331 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
332 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
333 }
334
335 async _startMessageSequence(): Promise<void> {
336 // Start WebSocket ping
337 this._startWebSocketPing();
338 // Start heartbeat
339 this._startHeartbeat();
340 // Initialize connectors status
341 for (const connector in this._connectors) {
342 if (!this._hasStopped && !this.getConnector(Utils.convertToInt(connector)).status && this.getConnector(Utils.convertToInt(connector)).bootStatus) {
343 // Send status in template at startup
344 await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
345 } else if (this._hasStopped && this.getConnector(Utils.convertToInt(connector)).bootStatus) {
346 // Send status in template after reset
347 await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
348 } else if (!this._hasStopped && this.getConnector(Utils.convertToInt(connector)).status) {
349 // Send previous status at template reload
350 await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
351 } else {
352 // Send default status
353 await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
354 }
355 }
356 // Start the ATG
357 if (this._stationInfo.AutomaticTransactionGenerator.enable) {
358 if (!this._automaticTransactionGeneration) {
359 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
360 }
361 if (this._automaticTransactionGeneration.timeToStop) {
362 this._automaticTransactionGeneration.start();
363 }
364 }
365 if (this.getEnableStatistics()) {
366 this._statistics.start();
367 }
368 }
369
370 async _stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
371 // Stop WebSocket ping
372 this._stopWebSocketPing();
373 // Stop heartbeat
374 this._stopHeartbeat();
375 // Stop the ATG
376 if (this._stationInfo.AutomaticTransactionGenerator.enable &&
377 this._automaticTransactionGeneration &&
378 !this._automaticTransactionGeneration.timeToStop) {
379 await this._automaticTransactionGeneration.stop(reason);
380 } else {
381 for (const connector in this._connectors) {
382 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
383 await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason);
384 }
385 }
386 }
387 }
388
389 _startWebSocketPing(): void {
390 const webSocketPingInterval: number = this._getConfigurationKey('WebSocketPingInterval') ? Utils.convertToInt(this._getConfigurationKey('WebSocketPingInterval').value) : 0;
391 if (webSocketPingInterval > 0 && !this._webSocketPingSetInterval) {
392 this._webSocketPingSetInterval = setInterval(() => {
393 if (this._wsConnection?.readyState === WebSocket.OPEN) {
394 this._wsConnection.ping((): void => {});
395 }
396 }, webSocketPingInterval * 1000);
397 logger.info(this._logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
398 } else if (this._webSocketPingSetInterval) {
399 logger.info(this._logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
400 } else {
401 logger.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
402 }
403 }
404
405 _stopWebSocketPing(): void {
406 if (this._webSocketPingSetInterval) {
407 clearInterval(this._webSocketPingSetInterval);
408 this._webSocketPingSetInterval = null;
409 }
410 }
411
412 _restartWebSocketPing(): void {
413 // Stop WebSocket ping
414 this._stopWebSocketPing();
415 // Start WebSocket ping
416 this._startWebSocketPing();
417 }
418
419 _startHeartbeat(): void {
420 if (this._heartbeatInterval && this._heartbeatInterval > 0 && !this._heartbeatSetInterval) {
421 this._heartbeatSetInterval = setInterval(async () => {
422 await this.sendHeartbeat();
423 }, this._heartbeatInterval);
424 logger.info(this._logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this._heartbeatInterval));
425 } else if (this._heartbeatSetInterval) {
426 logger.info(this._logPrefix() + ' Heartbeat every ' + Utils.milliSecondsToHHMMSS(this._heartbeatInterval) + ' already started');
427 } else {
428 logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval ? Utils.milliSecondsToHHMMSS(this._heartbeatInterval) : this._heartbeatInterval}, not starting the heartbeat`);
429 }
430 }
431
432 _stopHeartbeat(): void {
433 if (this._heartbeatSetInterval) {
434 clearInterval(this._heartbeatSetInterval);
435 this._heartbeatSetInterval = null;
436 }
437 }
438
439 _restartHeartbeat(): void {
440 // Stop heartbeat
441 this._stopHeartbeat();
442 // Start heartbeat
443 this._startHeartbeat();
444 }
445
446 _startAuthorizationFileMonitoring(): void {
447 // eslint-disable-next-line @typescript-eslint/no-unused-vars
448 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
449 try {
450 logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
451 // Initialize _authorizedTags
452 this._authorizedTags = this._loadAndGetAuthorizedTags();
453 } catch (error) {
454 logger.error(this._logPrefix() + ' Authorization file monitoring error: %j', error);
455 }
456 });
457 }
458
459 _startStationTemplateFileMonitoring(): void {
460 // eslint-disable-next-line @typescript-eslint/no-unused-vars
461 fs.watchFile(this._stationTemplateFile, (current, previous) => {
462 try {
463 logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
464 // Initialize
465 this._initialize();
466 if (!this._stationInfo.AutomaticTransactionGenerator.enable &&
467 this._automaticTransactionGeneration) {
468 this._automaticTransactionGeneration.stop().catch(() => { });
469 }
470 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
471 } catch (error) {
472 logger.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error);
473 }
474 });
475 }
476
477 _startMeterValues(connectorId: number, interval: number): void {
478 if (!this.getConnector(connectorId).transactionStarted) {
479 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
480 return;
481 } else if (this.getConnector(connectorId).transactionStarted && !this.getConnector(connectorId).transactionId) {
482 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
483 return;
484 }
485 if (interval > 0) {
486 this.getConnector(connectorId).transactionSetInterval = setInterval(async () => {
487 if (this.getEnableStatistics()) {
488 const sendMeterValues = performance.timerify(this.sendMeterValues);
489 this._performanceObserver.observe({
490 entryTypes: ['function'],
491 });
492 await sendMeterValues(connectorId, interval, this);
493 } else {
494 await this.sendMeterValues(connectorId, interval, this);
495 }
496 }, interval);
497 } else {
498 logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
499 }
500 }
501
502 _openWSConnection(): void {
503 this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16);
504 logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl);
505 }
506
507 start(): void {
508 this._openWSConnection();
509 // Monitor authorization file
510 this._startAuthorizationFileMonitoring();
511 // Monitor station template file
512 this._startStationTemplateFileMonitoring();
513 // Handle Socket incoming messages
514 this._wsConnection.on('message', this.onMessage.bind(this));
515 // Handle Socket error
516 this._wsConnection.on('error', this.onError.bind(this));
517 // Handle Socket close
518 this._wsConnection.on('close', this.onClose.bind(this));
519 // Handle Socket opening connection
520 this._wsConnection.on('open', this.onOpen.bind(this));
521 // Handle Socket ping
522 this._wsConnection.on('ping', this.onPing.bind(this));
523 // Handle Socket pong
524 this._wsConnection.on('pong', this.onPong.bind(this));
525 }
526
527 async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
528 // Stop message sequence
529 await this._stopMessageSequence(reason);
530 // eslint-disable-next-line guard-for-in
531 for (const connector in this._connectors) {
532 await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
533 }
534 if (this._wsConnection?.readyState === WebSocket.OPEN) {
535 this._wsConnection.close();
536 }
537 this._hasStopped = true;
538 }
539
540 _reconnect(error): void {
541 logger.error(this._logPrefix() + ' Socket: abnormally closed: %j', error);
542 // Stop heartbeat
543 this._stopHeartbeat();
544 // Stop the ATG if needed
545 if (this._stationInfo.AutomaticTransactionGenerator.enable &&
546 this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
547 this._automaticTransactionGeneration &&
548 !this._automaticTransactionGeneration.timeToStop) {
549 this._automaticTransactionGeneration.stop().catch(() => { });
550 }
551 if (this._autoReconnectTimeout !== 0 &&
552 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
553 logger.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
554 this._autoReconnectRetryCount++;
555 setTimeout(() => {
556 logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount.toString());
557 this._openWSConnection();
558 }, this._autoReconnectTimeout);
559 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
560 logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
561 }
562 }
563
564 async onOpen(): Promise<void> {
565 logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
566 if (!this._hasSocketRestarted || this._hasStopped) {
567 // Send BootNotification
568 await this.sendBootNotification();
569 }
570 await this._startMessageSequence();
571 if (this._hasSocketRestarted) {
572 if (!Utils.isEmptyArray(this._messageQueue)) {
573 this._messageQueue.forEach((message, index) => {
574 if (this._wsConnection?.readyState === WebSocket.OPEN) {
575 this._messageQueue.splice(index, 1);
576 this._wsConnection.send(message);
577 }
578 });
579 }
580 }
581 this._hasSocketRestarted = false;
582 this._autoReconnectRetryCount = 0;
583 }
584
585 onError(errorEvent): void {
586 switch (errorEvent.code) {
587 case 'ECONNREFUSED':
588 this._hasSocketRestarted = true;
589 this._reconnect(errorEvent);
590 break;
591 default:
592 logger.error(this._logPrefix() + ' Socket error: %j', errorEvent);
593 break;
594 }
595 }
596
597 onClose(closeEvent): void {
598 switch (closeEvent) {
599 case 1000: // Normal close
600 case 1005:
601 logger.info(this._logPrefix() + ' Socket normally closed: %j', closeEvent);
602 this._autoReconnectRetryCount = 0;
603 break;
604 default: // Abnormal close
605 this._hasSocketRestarted = true;
606 this._reconnect(closeEvent);
607 break;
608 }
609 }
610
611 onPing(): void {
612 logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
613 }
614
615 onPong(): void {
616 logger.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
617 }
618
619 async onMessage(messageEvent: MessageEvent): Promise<void> {
620 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
621 try {
622 // Parse the message
623 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString());
624
625 // Check the Type of message
626 switch (messageType) {
627 // Incoming Message
628 case Constants.OCPP_JSON_CALL_MESSAGE:
629 if (this.getEnableStatistics()) {
630 this._statistics.addMessage(commandName, messageType);
631 }
632 // Process the call
633 await this.handleRequest(messageId, commandName, commandPayload);
634 break;
635 // Outcome Message
636 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
637 // Respond
638 // eslint-disable-next-line no-case-declarations
639 let responseCallback; let requestPayload;
640 if (Utils.isIterable(this._requests[messageId])) {
641 [responseCallback, , requestPayload] = this._requests[messageId];
642 } else {
643 throw new Error(`Response request for message id ${messageId} is not iterable`);
644 }
645 if (!responseCallback) {
646 // Error
647 throw new Error(`Response request for unknown message id ${messageId}`);
648 }
649 delete this._requests[messageId];
650 responseCallback(commandName, requestPayload);
651 break;
652 // Error Message
653 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
654 if (!this._requests[messageId]) {
655 // Error
656 throw new Error(`Error request for unknown message id ${messageId}`);
657 }
658 // eslint-disable-next-line no-case-declarations
659 let rejectCallback;
660 if (Utils.isIterable(this._requests[messageId])) {
661 [, rejectCallback] = this._requests[messageId];
662 } else {
663 throw new Error(`Error request for message id ${messageId} is not iterable`);
664 }
665 delete this._requests[messageId];
666 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
667 break;
668 // Error
669 default:
670 // eslint-disable-next-line no-case-declarations
671 const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
672 logger.error(errMsg);
673 throw new Error(errMsg);
674 }
675 } catch (error) {
676 // Log
677 logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent, error, this._requests[messageId]);
678 // Send error
679 messageType !== Constants.OCPP_JSON_CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName);
680 }
681 }
682
683 async sendHeartbeat(): Promise<void> {
684 try {
685 const payload = {
686 currentTime: new Date().toISOString(),
687 };
688 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
689 } catch (error) {
690 logger.error(this._logPrefix() + ' Send Heartbeat error: %j', error);
691 throw error;
692 }
693 }
694
695 async sendBootNotification(): Promise<void> {
696 try {
697 await this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
698 } catch (error) {
699 logger.error(this._logPrefix() + ' Send BootNotification error: %j', error);
700 throw error;
701 }
702 }
703
704 async sendStatusNotification(connectorId: number, status: ChargePointStatus, errorCode: ChargePointErrorCode = ChargePointErrorCode.NO_ERROR): Promise<void> {
705 this.getConnector(connectorId).status = status;
706 try {
707 const payload = {
708 connectorId,
709 errorCode,
710 status,
711 };
712 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
713 } catch (error) {
714 logger.error(this._logPrefix() + ' Send StatusNotification error: %j', error);
715 throw error;
716 }
717 }
718
719 async sendStartTransaction(connectorId: number, idTag?: string): Promise<StartTransactionResponse> {
720 try {
721 const payload = {
722 connectorId,
723 ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.TRANSACTION_DEFAULT_IDTAG },
724 meterStart: 0,
725 timestamp: new Date().toISOString(),
726 };
727 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction') as StartTransactionResponse;
728 } catch (error) {
729 logger.error(this._logPrefix() + ' Send StartTransaction error: %j', error);
730 throw error;
731 }
732 }
733
734 async sendStopTransaction(transactionId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
735 const idTag = this._getTransactionidTag(transactionId);
736 try {
737 const payload = {
738 transactionId,
739 ...!Utils.isUndefined(idTag) && { idTag: idTag },
740 meterStop: 0,
741 timestamp: new Date().toISOString(),
742 ...reason && { reason },
743 };
744 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction') as StartTransactionResponse;
745 } catch (error) {
746 logger.error(this._logPrefix() + ' Send StopTransaction error: %j', error);
747 throw error;
748 }
749 }
750
751 // eslint-disable-next-line consistent-this
752 async sendMeterValues(connectorId: number, interval: number, self: ChargingStation, debug = false): Promise<void> {
753 try {
754 const sampledValues: {
755 timestamp: string;
756 sampledValue: MeterValue[];
757 } = {
758 timestamp: new Date().toISOString(),
759 sampledValue: [],
760 };
761 const meterValuesTemplate = self.getConnector(connectorId).MeterValues;
762 for (let index = 0; index < meterValuesTemplate.length; index++) {
763 const connector = self.getConnector(connectorId);
764 // SoC measurand
765 if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.STATE_OF_CHARGE && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.STATE_OF_CHARGE)) {
766 sampledValues.sampledValue.push({
767 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.PERCENT },
768 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
769 measurand: meterValuesTemplate[index].measurand,
770 ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: MeterValueLocation.EV },
771 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100).toString() },
772 });
773 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
774 if (Utils.convertToInt(sampledValues.sampledValue[sampledValuesIndex].value) > 100 || debug) {
775 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/100`);
776 }
777 // Voltage measurand
778 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.VOLTAGE && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.VOLTAGE)) {
779 const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
780 sampledValues.sampledValue.push({
781 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT },
782 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
783 measurand: meterValuesTemplate[index].measurand,
784 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
785 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() },
786 });
787 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
788 const voltageValue = Utils.convertToFloat(sampledValues.sampledValue[sampledValues.sampledValue.length - 1].value);
789 let phaseValue: string;
790 if (voltageValue >= 0 && voltageValue <= 250) {
791 phaseValue = `L${phase}-N`;
792 } else if (voltageValue > 250) {
793 phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
794 }
795 sampledValues.sampledValue.push({
796 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT },
797 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
798 measurand: meterValuesTemplate[index].measurand,
799 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
800 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() },
801 phase: phaseValue as MeterValuePhase,
802 });
803 }
804 // Power.Active.Import measurand
805 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.POWER_ACTIVE_IMPORT && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.POWER_ACTIVE_IMPORT)) {
806 // FIXME: factor out powerDivider checks
807 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
808 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
809 logger.error(errMsg);
810 throw Error(errMsg);
811 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
812 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
813 logger.error(errMsg);
814 throw Error(errMsg);
815 }
816 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
817 const powerMeasurandValues = {} as MeasurandValues;
818 const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider);
819 const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases());
820 switch (self._getPowerOutType()) {
821 case PowerOutType.AC:
822 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
823 powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase);
824 powerMeasurandValues.L2 = 0;
825 powerMeasurandValues.L3 = 0;
826 if (self._getNumberOfPhases() === 3) {
827 powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase);
828 powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase);
829 }
830 powerMeasurandValues.allPhases = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2);
831 }
832 break;
833 case PowerOutType.DC:
834 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
835 powerMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxPower);
836 }
837 break;
838 default:
839 logger.error(errMsg);
840 throw Error(errMsg);
841 }
842 sampledValues.sampledValue.push({
843 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT },
844 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
845 measurand: meterValuesTemplate[index].measurand,
846 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
847 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.allPhases.toString() },
848 });
849 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
850 if (Utils.convertToFloat(sampledValues.sampledValue[sampledValuesIndex].value) > maxPower || debug) {
851 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxPower}`);
852 }
853 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
854 const phaseValue = `L${phase}-N`;
855 sampledValues.sampledValue.push({
856 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT },
857 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
858 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
859 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
860 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] as string },
861 phase: phaseValue as MeterValuePhase,
862 });
863 }
864 // Current.Import measurand
865 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.CURRENT_IMPORT && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.CURRENT_IMPORT)) {
866 // FIXME: factor out powerDivider checks
867 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
868 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
869 logger.error(errMsg);
870 throw Error(errMsg);
871 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
872 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
873 logger.error(errMsg);
874 throw Error(errMsg);
875 }
876 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
877 const currentMeasurandValues: MeasurandValues = {} as MeasurandValues;
878 let maxAmperage: number;
879 switch (self._getPowerOutType()) {
880 case PowerOutType.AC:
881 maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
882 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
883 currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage);
884 currentMeasurandValues.L2 = 0;
885 currentMeasurandValues.L3 = 0;
886 if (self._getNumberOfPhases() === 3) {
887 currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage);
888 currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage);
889 }
890 currentMeasurandValues.allPhases = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2);
891 }
892 break;
893 case PowerOutType.DC:
894 maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
895 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
896 currentMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxAmperage);
897 }
898 break;
899 default:
900 logger.error(errMsg);
901 throw Error(errMsg);
902 }
903 sampledValues.sampledValue.push({
904 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP },
905 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
906 measurand: meterValuesTemplate[index].measurand,
907 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
908 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.allPhases.toString() },
909 });
910 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
911 if (Utils.convertToFloat(sampledValues.sampledValue[sampledValuesIndex].value) > maxAmperage || debug) {
912 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxAmperage}`);
913 }
914 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
915 const phaseValue = `L${phase}`;
916 sampledValues.sampledValue.push({
917 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP },
918 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
919 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
920 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
921 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] as string },
922 phase: phaseValue as MeterValuePhase,
923 });
924 }
925 // Energy.Active.Import.Register measurand (default)
926 } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
927 // FIXME: factor out powerDivider checks
928 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
929 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
930 logger.error(errMsg);
931 throw Error(errMsg);
932 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
933 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
934 logger.error(errMsg);
935 throw Error(errMsg);
936 }
937 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
938 const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval);
939 // Persist previous value in connector
940 if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) {
941 connector.lastEnergyActiveImportRegisterValue += measurandValue;
942 } else {
943 connector.lastEnergyActiveImportRegisterValue = 0;
944 }
945 }
946 sampledValues.sampledValue.push({
947 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT_HOUR },
948 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
949 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
950 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
951 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } :
952 { value: connector.lastEnergyActiveImportRegisterValue.toString() },
953 });
954 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
955 const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval));
956 if (Utils.convertToFloat(sampledValues.sampledValue[sampledValuesIndex].value) > maxConsumption || debug) {
957 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxConsumption}`);
958 }
959 // Unsupported measurand
960 } else {
961 logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
962 }
963 }
964
965 const payload = {
966 connectorId,
967 transactionId: self.getConnector(connectorId).transactionId,
968 meterValue: sampledValues,
969 };
970 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
971 } catch (error) {
972 logger.error(self._logPrefix() + ' Send MeterValues error: %j', error);
973 throw error;
974 }
975 }
976
977 async sendError(messageId: string, err: Error | OCPPError, commandName: string): Promise<unknown> {
978 // Check exception type: only OCPP error are accepted
979 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack);
980 // Send error
981 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName);
982 }
983
984 async sendMessage(messageId: string, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string): Promise<any> {
985 // eslint-disable-next-line @typescript-eslint/no-this-alias
986 const self = this;
987 // Send a message through wsConnection
988 return new Promise((resolve, reject) => {
989 let messageToSend;
990 // Type of message
991 switch (messageType) {
992 // Request
993 case Constants.OCPP_JSON_CALL_MESSAGE:
994 // Build request
995 this._requests[messageId] = [responseCallback, rejectCallback, commandParams];
996 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
997 break;
998 // Response
999 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
1000 // Build response
1001 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
1002 break;
1003 // Error Message
1004 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
1005 // Build Error Message
1006 messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
1007 break;
1008 }
1009 // Check if wsConnection is ready
1010 if (this._wsConnection?.readyState === WebSocket.OPEN) {
1011 if (this.getEnableStatistics()) {
1012 this._statistics.addMessage(commandName, messageType);
1013 }
1014 // Yes: Send Message
1015 this._wsConnection.send(messageToSend);
1016 } else {
1017 let dups = false;
1018 // Handle dups in buffer
1019 for (const message of this._messageQueue) {
1020 // Same message
1021 if (JSON.stringify(messageToSend) === JSON.stringify(message)) {
1022 dups = true;
1023 break;
1024 }
1025 }
1026 if (!dups) {
1027 // Buffer message
1028 this._messageQueue.push(messageToSend);
1029 }
1030 // Reject it
1031 return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
1032 }
1033 // Response?
1034 if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) {
1035 // Yes: send Ok
1036 resolve();
1037 } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) {
1038 // Send timeout
1039 setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_SOCKET_TIMEOUT);
1040 }
1041
1042 // Function that will receive the request's response
1043 function responseCallback(payload, requestPayload): void {
1044 if (self.getEnableStatistics()) {
1045 self._statistics.addMessage(commandName, messageType);
1046 }
1047 // Send the response
1048 self.handleResponse(commandName, payload, requestPayload);
1049 resolve(payload);
1050 }
1051
1052 // Function that will receive the request's rejection
1053 function rejectCallback(error: OCPPError): void {
1054 if (self.getEnableStatistics()) {
1055 self._statistics.addMessage(commandName, messageType);
1056 }
1057 logger.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error, commandName, commandParams);
1058 // Build Exception
1059 // eslint-disable-next-line no-empty-function
1060 self._requests[messageId] = [() => { }, () => { }, {}]; // Properly format the request
1061 // Send error
1062 reject(error);
1063 }
1064 });
1065 }
1066
1067 handleResponse(commandName: string, payload, requestPayload): void {
1068 const responseCallbackFn = 'handleResponse' + commandName;
1069 if (typeof this[responseCallbackFn] === 'function') {
1070 this[responseCallbackFn](payload, requestPayload);
1071 } else {
1072 logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
1073 }
1074 }
1075
1076 handleResponseBootNotification(payload, requestPayload): void {
1077 if (payload.status === 'Accepted') {
1078 this._heartbeatInterval = Utils.convertToInt(payload.interval) * 1000;
1079 this._heartbeatSetInterval ? this._restartHeartbeat() : this._startHeartbeat();
1080 this._addConfigurationKey('HeartBeatInterval', payload.interval);
1081 this._addConfigurationKey('HeartbeatInterval', payload.interval, false, false);
1082 this._hasStopped && (this._hasStopped = false);
1083 } else if (payload.status === 'Pending') {
1084 logger.info(this._logPrefix() + ' Charging station in pending state on the central server');
1085 } else {
1086 logger.info(this._logPrefix() + ' Charging station rejected by the central server');
1087 }
1088 }
1089
1090 _initTransactionOnConnector(connectorId: number): void {
1091 this.getConnector(connectorId).transactionStarted = false;
1092 this.getConnector(connectorId).transactionId = null;
1093 this.getConnector(connectorId).idTag = null;
1094 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
1095 }
1096
1097 _resetTransactionOnConnector(connectorId: number): void {
1098 this._initTransactionOnConnector(connectorId);
1099 if (this.getConnector(connectorId).transactionSetInterval) {
1100 clearInterval(this.getConnector(connectorId).transactionSetInterval);
1101 }
1102 }
1103
1104 handleResponseStartTransaction(payload: StartTransactionResponse, requestPayload): void {
1105 const connectorId = Utils.convertToInt(requestPayload.connectorId);
1106 if (this.getConnector(connectorId).transactionStarted) {
1107 logger.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId.toString() + ': %j', this.getConnector(connectorId));
1108 return;
1109 }
1110
1111 let transactionConnectorId: number;
1112 for (const connector in this._connectors) {
1113 if (Utils.convertToInt(connector) === connectorId) {
1114 transactionConnectorId = Utils.convertToInt(connector);
1115 break;
1116 }
1117 }
1118 if (!transactionConnectorId) {
1119 logger.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId.toString());
1120 return;
1121 }
1122 if (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
1123 this.getConnector(connectorId).transactionStarted = true;
1124 this.getConnector(connectorId).transactionId = payload.transactionId;
1125 this.getConnector(connectorId).idTag = requestPayload.idTag;
1126 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = 0;
1127 this.sendStatusNotification(connectorId, ChargePointStatus.CHARGING).catch(() => { });
1128 logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId.toString() + ' STARTED on ' + this._stationInfo.name + '#' + connectorId.toString() + ' for idTag ' + requestPayload.idTag);
1129 if (this._stationInfo.powerSharedByConnectors) {
1130 this._stationInfo.powerDivider++;
1131 }
1132 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
1133 this._startMeterValues(connectorId,
1134 configuredMeterValueSampleInterval ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000 : 60000);
1135 } else {
1136 logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId.toString() + ' REJECTED with status ' + payload.idTagInfo?.status + ', idTag ' + requestPayload.idTag);
1137 this._resetTransactionOnConnector(connectorId);
1138 this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE).catch(() => { });
1139 }
1140 }
1141
1142 handleResponseStopTransaction(payload: StopTransactionResponse, requestPayload): void {
1143 let transactionConnectorId: number;
1144 for (const connector in this._connectors) {
1145 if (this.getConnector(Utils.convertToInt(connector)).transactionId === Utils.convertToInt(requestPayload.transactionId)) {
1146 transactionConnectorId = Utils.convertToInt(connector);
1147 break;
1148 }
1149 }
1150 if (!transactionConnectorId) {
1151 logger.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload.transactionId);
1152 return;
1153 }
1154 if (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
1155 this.sendStatusNotification(transactionConnectorId, ChargePointStatus.AVAILABLE).catch(() => { });
1156 if (this._stationInfo.powerSharedByConnectors) {
1157 this._stationInfo.powerDivider--;
1158 }
1159 logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId.toString());
1160 this._resetTransactionOnConnector(transactionConnectorId);
1161 } else {
1162 logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo?.status);
1163 }
1164 }
1165
1166 handleResponseStatusNotification(payload, requestPayload): void {
1167 logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload);
1168 }
1169
1170 handleResponseMeterValues(payload, requestPayload): void {
1171 logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
1172 }
1173
1174 handleResponseHeartbeat(payload, requestPayload): void {
1175 logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
1176 }
1177
1178 async handleRequest(messageId: string, commandName: string, commandPayload): Promise<void> {
1179 let response;
1180 // Call
1181 if (typeof this['handleRequest' + commandName] === 'function') {
1182 try {
1183 // Call the method to build the response
1184 response = await this['handleRequest' + commandName](commandPayload);
1185 } catch (error) {
1186 // Log
1187 logger.error(this._logPrefix() + ' Handle request error: %j', error);
1188 // Send back response to inform backend
1189 await this.sendError(messageId, error, commandName);
1190 throw error;
1191 }
1192 } else {
1193 // Throw exception
1194 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName);
1195 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1196 }
1197 // Send response
1198 await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName);
1199 }
1200
1201 // Simulate charging station restart
1202 handleRequestReset(commandPayload): DefaultRequestResponse {
1203 setImmediate(async () => {
1204 await this.stop(commandPayload.type + 'Reset' as StopTransactionReason);
1205 await Utils.sleep(this._stationInfo.resetTime);
1206 await this.start();
1207 });
1208 logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`);
1209 return Constants.OCPP_RESPONSE_ACCEPTED;
1210 }
1211
1212 async handleRequestUnlockConnector(commandPayload): Promise<UnlockResponse> {
1213 const connectorId = Utils.convertToInt(commandPayload.connectorId);
1214 if (connectorId === 0) {
1215 logger.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId.toString());
1216 return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
1217 }
1218 if (this.getConnector(connectorId).transactionStarted) {
1219 const stopResponse = await this.sendStopTransaction(this.getConnector(connectorId).transactionId, StopTransactionReason.UNLOCK_COMMAND);
1220 if (stopResponse.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
1221 return Constants.OCPP_RESPONSE_UNLOCKED;
1222 }
1223 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
1224 }
1225 await this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
1226 return Constants.OCPP_RESPONSE_UNLOCKED;
1227 }
1228
1229 _getConfigurationKey(key: string): ConfigurationKey {
1230 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
1231 }
1232
1233 _addConfigurationKey(key: string, value: string, readonly = false, visible = true, reboot = false): void {
1234 const keyFound = this._getConfigurationKey(key);
1235 if (!keyFound) {
1236 this._configuration.configurationKey.push({
1237 key,
1238 readonly,
1239 value,
1240 visible,
1241 reboot,
1242 });
1243 }
1244 }
1245
1246 _setConfigurationKeyValue(key: string, value: string): void {
1247 const keyFound = this._getConfigurationKey(key);
1248 if (keyFound) {
1249 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
1250 this._configuration.configurationKey[keyIndex].value = value;
1251 }
1252 }
1253
1254 handleRequestGetConfiguration(commandPayload): { configurationKey: ConfigurationKey[]; unknownKey: string[] } {
1255 const configurationKey: ConfigurationKey[] = [];
1256 const unknownKey: string[] = [];
1257 if (Utils.isEmptyArray(commandPayload.key)) {
1258 for (const configuration of this._configuration.configurationKey) {
1259 if (Utils.isUndefined(configuration.visible)) {
1260 configuration.visible = true;
1261 }
1262 if (!configuration.visible) {
1263 continue;
1264 }
1265 configurationKey.push({
1266 key: configuration.key,
1267 readonly: configuration.readonly,
1268 value: configuration.value,
1269 });
1270 }
1271 } else {
1272 for (const key of commandPayload.key as string[]) {
1273 const keyFound = this._getConfigurationKey(key);
1274 if (keyFound) {
1275 if (Utils.isUndefined(keyFound.visible)) {
1276 keyFound.visible = true;
1277 }
1278 if (!keyFound.visible) {
1279 continue;
1280 }
1281 configurationKey.push({
1282 key: keyFound.key,
1283 readonly: keyFound.readonly,
1284 value: keyFound.value,
1285 });
1286 } else {
1287 unknownKey.push(key);
1288 }
1289 }
1290 }
1291 return {
1292 configurationKey,
1293 unknownKey,
1294 };
1295 }
1296
1297 handleRequestChangeConfiguration(commandPayload): ConfigurationResponse {
1298 const keyToChange = this._getConfigurationKey(commandPayload.key);
1299 if (!keyToChange) {
1300 return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
1301 } else if (keyToChange && keyToChange.readonly) {
1302 return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
1303 } else if (keyToChange && !keyToChange.readonly) {
1304 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
1305 let valueChanged = false;
1306 if (this._configuration.configurationKey[keyIndex].value !== commandPayload.value) {
1307 this._configuration.configurationKey[keyIndex].value = commandPayload.value as string;
1308 valueChanged = true;
1309 }
1310 let triggerHeartbeatRestart = false;
1311 if (keyToChange.key === 'HeartBeatInterval' && valueChanged) {
1312 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
1313 triggerHeartbeatRestart = true;
1314 }
1315 if (keyToChange.key === 'HeartbeatInterval' && valueChanged) {
1316 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
1317 triggerHeartbeatRestart = true;
1318 }
1319 if (triggerHeartbeatRestart) {
1320 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
1321 this._restartHeartbeat();
1322 }
1323 if (keyToChange.key === 'WebSocketPingInterval' && valueChanged) {
1324 this._restartWebSocketPing();
1325 }
1326 if (keyToChange.reboot) {
1327 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
1328 }
1329 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
1330 }
1331 }
1332
1333 async handleRequestRemoteStartTransaction(commandPayload): Promise<DefaultRequestResponse> {
1334 const transactionConnectorID: number = commandPayload.connectorId ? Utils.convertToInt(commandPayload.connectorId) : 1;
1335 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1336 // Check if authorized
1337 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
1338 // Authorization successful start transaction
1339 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
1340 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag);
1341 return Constants.OCPP_RESPONSE_ACCEPTED;
1342 }
1343 logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo?.status + ', idTag ' + commandPayload.idTag);
1344 return Constants.OCPP_RESPONSE_REJECTED;
1345 }
1346 // No local authorization check required => start transaction
1347 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
1348 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag);
1349 return Constants.OCPP_RESPONSE_ACCEPTED;
1350 }
1351
1352 async handleRequestRemoteStopTransaction(commandPayload): Promise<DefaultRequestResponse> {
1353 const transactionId = Utils.convertToInt(commandPayload.transactionId);
1354 for (const connector in this._connectors) {
1355 if (this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
1356 await this.sendStopTransaction(transactionId);
1357 return Constants.OCPP_RESPONSE_ACCEPTED;
1358 }
1359 }
1360 logger.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
1361 return Constants.OCPP_RESPONSE_REJECTED;
1362 }
1363 }
1364