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