CF: include TS sources.
[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 17 private _index: number;
a4a21709 18 private _stationTemplateFile: string;
6af9012e
JB
19 private _stationInfo;
20 private _bootNotificationMessage;
21 private _connectors;
22 private _configuration;
a4a21709 23 private _connectorsConfigurationHash: string;
6af9012e
JB
24 private _supervisionUrl;
25 private _wsConnectionUrl;
a4a21709 26 private _wsConnection: WebSocket;
6af9012e 27 private _isSocketRestart;
a4a21709
JB
28 private _autoReconnectRetryCount: number;
29 private _autoReconnectMaxRetries: number;
30 private _autoReconnectTimeout: number;
6af9012e 31 private _requests;
7f134aca 32 private _messageQueue: any[];
6af9012e
JB
33 private _automaticTransactionGeneration: AutomaticTransactionGenerator;
34 private _authorizedTags: string[];
a4a21709 35 private _heartbeatInterval: number;
6af9012e
JB
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
65c5527e 172 _getAuthorizationFile() : string {
6af9012e 173 return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile;
7dde0b73
JB
174 }
175
6af9012e 176 _loadAndGetAuthorizedTags(): string[] {
65c5527e 177 let authorizedTags: string[] = [];
2e6f5966
JB
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
65c5527e 195 getRandomTagId(): string {
5ad8570f
JB
196 const index = Math.floor(Math.random() * this._authorizedTags.length);
197 return this._authorizedTags[index];
2e6f5966
JB
198 }
199
65c5527e 200 hasAuthorizedTags(): boolean {
5ad8570f
JB
201 return !Utils.isEmptyArray(this._authorizedTags);
202 }
203
65c5527e 204 getEnableStatistics(): boolean {
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
65c5527e 217 _getNumberOfRunningTransactions(): number {
6ecb15e4
JB
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
65c5527e 227 _getPowerDivider(): number {
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
65c5527e 239 _getTemplateMaxNumberOfConnectors(): number {
7abfea5f
JB
240 return Object.keys(this._stationInfo.Connectors).length;
241 }
242
65c5527e 243 _getMaxNumberOfConnectors(): number {
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
65c5527e 260 _getVoltageOut(): number {
b2acff85
JB
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
65c5527e 277 _getPowerOutType(): string {
b2acff85 278 return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : 'AC';
3f40bc9c
JB
279 }
280
65c5527e 281 _getSupervisionURL(): string {
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
65c5527e 296 _getAuthorizeRemoteTxRequests(): boolean {
61c2e33d 297 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
a6e68f34 298 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
7dde0b73
JB
299 }
300
65c5527e 301 _getLocalAuthListEnabled(): boolean {
61c2e33d 302 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
def3d48e
JB
303 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
304 }
305
79411696 306 _startMessageSequence(): 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) {
79411696 313 this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
5ad8570f 314 } else {
79411696 315 this.sendStatusNotification(Utils.convertToInt(connector), 'Available');
5ad8570f
JB
316 }
317 } else {
79411696 318 this.sendStatusNotification(Utils.convertToInt(connector), 'Charging');
5ad8570f
JB
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
a4a21709 335 async _stopMessageSequence(reason = ''): Promise<void> {
79411696
JB
336 // Stop heartbeat
337 this._stopHeartbeat();
338 // Stop the ATG
339 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
340 this._automaticTransactionGeneration &&
341 !this._automaticTransactionGeneration.timeToStop) {
342 await this._automaticTransactionGeneration.stop(reason);
343 } else {
344 for (const connector in this._connectors) {
345 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
346 await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason);
347 }
348 }
349 }
350 }
351
6af9012e
JB
352 _startHeartbeat(): void {
353 if (this._heartbeatInterval && this._heartbeatInterval > 0 && !this._heartbeatSetInterval) {
354 this._heartbeatSetInterval = setInterval(() => {
0a60c33c 355 this.sendHeartbeat();
6af9012e
JB
356 }, this._heartbeatInterval);
357 logger.info(this._logPrefix() + ' Heartbeat started every ' + this._heartbeatInterval.toString() + 'ms');
7dde0b73 358 } else {
6af9012e 359 logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval}ms, not starting the heartbeat`);
0a60c33c
JB
360 }
361 }
362
65c5527e 363 _stopHeartbeat(): void {
0a60c33c
JB
364 if (this._heartbeatSetInterval) {
365 clearInterval(this._heartbeatSetInterval);
366 this._heartbeatSetInterval = null;
7dde0b73 367 }
5ad8570f
JB
368 }
369
65c5527e
JB
370 _startAuthorizationFileMonitoring(): void {
371 // eslint-disable-next-line @typescript-eslint/no-unused-vars
5ad8570f
JB
372 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
373 try {
ead548f2 374 logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
5ad8570f
JB
375 // Initialize _authorizedTags
376 this._authorizedTags = this._loadAndGetAuthorizedTags();
377 } catch (error) {
ead548f2 378 logger.error(this._logPrefix() + ' Authorization file monitoring error: ' + error);
5ad8570f
JB
379 }
380 });
381 }
382
65c5527e
JB
383 _startStationTemplateFileMonitoring(): void {
384 // eslint-disable-next-line @typescript-eslint/no-unused-vars
5ad8570f
JB
385 fs.watchFile(this._stationTemplateFile, (current, previous) => {
386 try {
ead548f2 387 logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
5ad8570f
JB
388 // Initialize
389 this._initialize();
79411696
JB
390 if (!Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
391 this._automaticTransactionGeneration) {
392 this._automaticTransactionGeneration.stop().catch(() => {});
393 }
5ad8570f 394 } catch (error) {
ead548f2 395 logger.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error);
5ad8570f
JB
396 }
397 });
398 }
399
6af9012e 400 _startMeterValues(connectorId: number, interval: number): void {
8bce55bf 401 if (!this.getConnector(connectorId).transactionStarted) {
6ecb15e4 402 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
5ad8570f 403 return;
8bce55bf 404 } else if (this.getConnector(connectorId).transactionStarted && !this.getConnector(connectorId).transactionId) {
6ecb15e4 405 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
5ad8570f
JB
406 return;
407 }
0a60c33c 408 if (interval > 0) {
65c5527e 409 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
8bce55bf
JB
410 if (this.getEnableStatistics()) {
411 const sendMeterValues = performance.timerify(this.sendMeterValues);
412 this._performanceObserver.observe({
413 entryTypes: ['function'],
414 });
65c5527e 415 await sendMeterValues(connectorId, interval, this);
8bce55bf 416 } else {
65c5527e 417 await this.sendMeterValues(connectorId, interval, this);
8bce55bf 418 }
0a60c33c
JB
419 }, interval);
420 } else {
ead548f2 421 logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
0a60c33c 422 }
7dde0b73
JB
423 }
424
65c5527e 425 start(): void {
0a60c33c
JB
426 if (!this._wsConnectionUrl) {
427 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
5ad8570f 428 }
0a60c33c 429 this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16);
ead548f2 430 logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl);
2e6f5966
JB
431 // Monitor authorization file
432 this._startAuthorizationFileMonitoring();
433 // Monitor station template file
434 this._startStationTemplateFileMonitoring();
7dde0b73
JB
435 // Handle Socket incoming messages
436 this._wsConnection.on('message', this.onMessage.bind(this));
437 // Handle Socket error
438 this._wsConnection.on('error', this.onError.bind(this));
439 // Handle Socket close
440 this._wsConnection.on('close', this.onClose.bind(this));
441 // Handle Socket opening connection
442 this._wsConnection.on('open', this.onOpen.bind(this));
443 // Handle Socket ping
444 this._wsConnection.on('ping', this.onPing.bind(this));
445 }
446
65c5527e 447 async stop(reason = ''): Promise<void> {
79411696
JB
448 // Stop
449 await this._stopMessageSequence();
5ad8570f
JB
450 // eslint-disable-next-line guard-for-in
451 for (const connector in this._connectors) {
6af9012e 452 await this.sendStatusNotification(Utils.convertToInt(connector), 'Unavailable');
5ad8570f 453 }
0a60c33c 454 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
65c5527e 455 this._wsConnection.close();
5ad8570f
JB
456 }
457 }
458
65c5527e 459 _reconnect(error): void {
ead548f2 460 logger.error(this._logPrefix() + ' Socket: abnormally closed', error);
5ad8570f
JB
461 // Stop the ATG if needed
462 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
463 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
464 this._automaticTransactionGeneration &&
465 !this._automaticTransactionGeneration.timeToStop) {
466 this._automaticTransactionGeneration.stop();
467 }
468 // Stop heartbeat
0a60c33c 469 this._stopHeartbeat();
5ad8570f
JB
470 if (this._autoReconnectTimeout !== 0 &&
471 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
ead548f2 472 logger.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
5ad8570f
JB
473 this._autoReconnectRetryCount++;
474 setTimeout(() => {
ead548f2 475 logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
5ad8570f
JB
476 this.start();
477 }, this._autoReconnectTimeout);
478 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
ead548f2 479 logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
5ad8570f
JB
480 }
481 }
482
7dde0b73 483 onOpen() {
ead548f2 484 logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
5ad8570f 485 if (!this._isSocketRestart) {
0bbcb3dc 486 // Send BootNotification
0a60c33c 487 this.sendBootNotification();
0bbcb3dc 488 }
7dde0b73 489 if (this._isSocketRestart) {
79411696 490 this._startMessageSequence();
546dec0f 491 if (!Utils.isEmptyArray(this._messageQueue)) {
7dde0b73 492 this._messageQueue.forEach((message) => {
0a60c33c 493 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
7dde0b73
JB
494 this._wsConnection.send(message);
495 }
496 });
497 }
7dde0b73
JB
498 }
499 this._autoReconnectRetryCount = 0;
500 this._isSocketRestart = false;
501 }
502
503 onError(error) {
504 switch (error) {
505 case 'ECONNREFUSED':
506 this._isSocketRestart = true;
507 this._reconnect(error);
508 break;
509 default:
ead548f2 510 logger.error(this._logPrefix() + ' Socket error: ' + error);
7dde0b73
JB
511 break;
512 }
513 }
514
515 onClose(error) {
516 switch (error) {
517 case 1000: // Normal close
518 case 1005:
ead548f2 519 logger.info(this._logPrefix() + ' Socket normally closed ' + error);
7dde0b73
JB
520 this._autoReconnectRetryCount = 0;
521 break;
522 default: // Abnormal close
523 this._isSocketRestart = true;
524 this._reconnect(error);
525 break;
526 }
527 }
528
529 onPing() {
ead548f2 530 logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
7dde0b73
JB
531 }
532
533 async onMessage(message) {
2d8cee5a 534 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
7dde0b73 535 try {
2d8cee5a
JB
536 // Parse the message
537 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
538
7dde0b73
JB
539 // Check the Type of message
540 switch (messageType) {
541 // Incoming Message
f7869514 542 case Constants.OCPP_JSON_CALL_MESSAGE:
7f134aca
JB
543 if (this.getEnableStatistics()) {
544 this._statistics.addMessage(commandName, messageType);
545 }
7dde0b73 546 // Process the call
7dde0b73
JB
547 await this.handleRequest(messageId, commandName, commandPayload);
548 break;
549 // Outcome Message
f7869514 550 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73
JB
551 // Respond
552 // eslint-disable-next-line no-case-declarations
553 let responseCallback; let requestPayload;
554 if (Utils.isIterable(this._requests[messageId])) {
555 [responseCallback, , requestPayload] = this._requests[messageId];
556 } else {
5933cbc8 557 throw new Error(`Response request for message id ${messageId} is not iterable`);
7dde0b73
JB
558 }
559 if (!responseCallback) {
560 // Error
a979cc12 561 throw new Error(`Response request for unknown message id ${messageId}`);
7dde0b73
JB
562 }
563 delete this._requests[messageId];
7dde0b73
JB
564 responseCallback(commandName, requestPayload);
565 break;
566 // Error Message
f7869514 567 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73
JB
568 if (!this._requests[messageId]) {
569 // Error
a979cc12 570 throw new Error(`Error request for unknown message id ${messageId}`);
7dde0b73
JB
571 }
572 // eslint-disable-next-line no-case-declarations
573 let rejectCallback;
574 if (Utils.isIterable(this._requests[messageId])) {
575 [, rejectCallback] = this._requests[messageId];
576 } else {
5933cbc8 577 throw new Error(`Error request for message id ${messageId} is not iterable`);
7dde0b73
JB
578 }
579 delete this._requests[messageId];
580 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
581 break;
582 // Error
583 default:
7f134aca
JB
584 // eslint-disable-next-line no-case-declarations
585 const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
586 logger.error(errMsg);
587 throw new Error(errMsg);
7dde0b73
JB
588 }
589 } catch (error) {
590 // Log
7f134aca 591 logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), message, error, this._requests[messageId]);
7dde0b73 592 // Send error
7f134aca 593 await this.sendError(messageId, error, commandName);
7dde0b73
JB
594 }
595 }
596
65c5527e 597 async sendHeartbeat() {
0a60c33c
JB
598 try {
599 const payload = {
600 currentTime: new Date().toISOString(),
601 };
65c5527e 602 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
0a60c33c 603 } catch (error) {
ead548f2 604 logger.error(this._logPrefix() + ' Send Heartbeat error: ' + error);
0a60c33c
JB
605 throw error;
606 }
607 }
608
65c5527e 609 async sendBootNotification() {
0a60c33c 610 try {
65c5527e 611 await this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
0a60c33c 612 } catch (error) {
ead548f2 613 logger.error(this._logPrefix() + ' Send BootNotification error: ' + error);
0a60c33c
JB
614 throw error;
615 }
616 }
617
65c5527e 618 async sendStatusNotification(connectorId: number, status: string, errorCode = 'NoError') {
5ad8570f
JB
619 try {
620 const payload = {
621 connectorId,
622 errorCode,
623 status,
624 };
625 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
626 } catch (error) {
ead548f2 627 logger.error(this._logPrefix() + ' Send StatusNotification error: ' + error);
5ad8570f 628 throw error;
027b409a
JB
629 }
630 }
631
65c5527e 632 async sendStartTransaction(connectorId: number, idTag?: string): Promise<unknown> {
5ad8570f
JB
633 try {
634 const payload = {
bec64e8b 635 connectorId,
79411696 636 ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: '' },
5ad8570f
JB
637 meterStart: 0,
638 timestamp: new Date().toISOString(),
639 };
640 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
641 } catch (error) {
ead548f2 642 logger.error(this._logPrefix() + ' Send StartTransaction error: ' + error);
5ad8570f 643 throw error;
7dde0b73
JB
644 }
645 }
646
7dc7fd62 647 async sendStopTransaction(transactionId: number, reason = ''): Promise<void> {
027b409a 648 try {
38c8fd6c
JB
649 const payload = {
650 transactionId,
651 meterStop: 0,
652 timestamp: new Date().toISOString(),
6af9012e 653 ...reason && { reason },
38c8fd6c 654 };
5ad8570f 655 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
027b409a 656 } catch (error) {
ead548f2 657 logger.error(this._logPrefix() + ' Send StopTransaction error: ' + error);
5ad8570f 658 throw error;
027b409a
JB
659 }
660 }
661
79411696 662 // eslint-disable-next-line consistent-this
65c5527e 663 async sendMeterValues(connectorId: number, interval: number, self: ChargingStation, debug = false): Promise<void> {
5ad8570f 664 try {
7abfea5f 665 const sampledValues = {
5ad8570f 666 timestamp: new Date().toISOString(),
7abfea5f 667 sampledValue: [],
5ad8570f 668 };
79411696 669 const meterValuesTemplate = self.getConnector(connectorId).MeterValues;
7abfea5f 670 for (let index = 0; index < meterValuesTemplate.length; index++) {
79411696 671 const connector = self.getConnector(connectorId);
0a60c33c 672 // SoC measurand
79411696 673 if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value.includes('SoC')) {
7abfea5f 674 sampledValues.sampledValue.push({
6af9012e
JB
675 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Percent' },
676 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
7abfea5f 677 measurand: meterValuesTemplate[index].measurand,
6af9012e
JB
678 ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: 'EV' },
679 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100) },
7abfea5f
JB
680 });
681 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
682 if (sampledValues.sampledValue[sampledValuesIndex].value > 100 || debug) {
79411696 683 logger.error(`${self._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 684 }
0a60c33c 685 // Voltage measurand
79411696 686 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Voltage')) {
7f134aca 687 const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
7abfea5f 688 sampledValues.sampledValue.push({
6af9012e
JB
689 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' },
690 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
7abfea5f 691 measurand: meterValuesTemplate[index].measurand,
6af9012e 692 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
7f134aca 693 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue },
7abfea5f 694 });
79411696 695 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
7abfea5f
JB
696 const voltageValue = sampledValues.sampledValue[sampledValues.sampledValue.length - 1].value;
697 let phaseValue;
b2acff85 698 if (voltageValue >= 0 && voltageValue <= 250) {
7abfea5f 699 phaseValue = `L${phase}-N`;
b2acff85 700 } else if (voltageValue > 250) {
79411696 701 phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
7abfea5f
JB
702 }
703 sampledValues.sampledValue.push({
6af9012e
JB
704 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' },
705 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
7abfea5f 706 measurand: meterValuesTemplate[index].measurand,
6af9012e 707 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
7f134aca 708 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue },
3f40bc9c
JB
709 phase: phaseValue,
710 });
711 }
fee83021 712 // Power.Active.Import measurand
79411696 713 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Power.Active.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Power.Active.Import')) {
fee83021 714 // FIXME: factor out powerDivider checks
79411696
JB
715 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
716 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
fee83021
JB
717 logger.error(errMsg);
718 throw Error(errMsg);
79411696
JB
719 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
720 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
fee83021
JB
721 logger.error(errMsg);
722 throw Error(errMsg);
723 }
79411696 724 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
6af9012e 725 const powerMeasurandValues = {} as MeasurandValues ;
79411696
JB
726 const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider);
727 const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases());
728 switch (self._getPowerOutType()) {
fee83021
JB
729 case 'AC':
730 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
731 powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase);
732 powerMeasurandValues.L2 = 0;
733 powerMeasurandValues.L3 = 0;
79411696 734 if (self._getNumberOfPhases() === 3) {
fee83021
JB
735 powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase);
736 powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase);
737 }
738 powerMeasurandValues.all = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2);
739 }
740 break;
741 case 'DC':
742 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
743 powerMeasurandValues.all = Utils.getRandomFloatRounded(maxPower);
744 }
745 break;
746 default:
747 logger.error(errMsg);
748 throw Error(errMsg);
749 }
750 sampledValues.sampledValue.push({
6af9012e
JB
751 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' },
752 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
fee83021 753 measurand: meterValuesTemplate[index].measurand,
6af9012e
JB
754 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
755 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.all },
fee83021
JB
756 });
757 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
758 if (sampledValues.sampledValue[sampledValuesIndex].value > maxPower || debug) {
79411696 759 logger.error(`${self._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 760 }
79411696 761 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
fee83021
JB
762 const phaseValue = `L${phase}-N`;
763 sampledValues.sampledValue.push({
6af9012e
JB
764 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' },
765 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
766 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
767 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
768 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] },
fee83021
JB
769 phase: phaseValue,
770 });
771 }
3f40bc9c 772 // Current.Import measurand
79411696 773 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Current.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Current.Import')) {
3f40bc9c 774 // FIXME: factor out powerDivider checks
79411696
JB
775 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
776 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
3f40bc9c
JB
777 logger.error(errMsg);
778 throw Error(errMsg);
79411696
JB
779 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
780 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
3f40bc9c
JB
781 logger.error(errMsg);
782 throw Error(errMsg);
783 }
79411696 784 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
6af9012e 785 const currentMeasurandValues = {} as MeasurandValues;
b2acff85 786 let maxAmperage;
79411696 787 switch (self._getPowerOutType()) {
b2acff85 788 case 'AC':
79411696 789 maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
b2acff85
JB
790 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
791 currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage);
792 currentMeasurandValues.L2 = 0;
793 currentMeasurandValues.L3 = 0;
79411696 794 if (self._getNumberOfPhases() === 3) {
b2acff85
JB
795 currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage);
796 currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage);
797 }
79411696 798 currentMeasurandValues.all = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2);
b2acff85
JB
799 }
800 break;
801 case 'DC':
79411696 802 maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
fee83021
JB
803 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
804 currentMeasurandValues.all = Utils.getRandomFloatRounded(maxAmperage);
805 }
b2acff85
JB
806 break;
807 default:
808 logger.error(errMsg);
809 throw Error(errMsg);
3f40bc9c
JB
810 }
811 sampledValues.sampledValue.push({
6af9012e
JB
812 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' },
813 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
3f40bc9c 814 measurand: meterValuesTemplate[index].measurand,
6af9012e
JB
815 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
816 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.all },
3f40bc9c
JB
817 });
818 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
b2acff85 819 if (sampledValues.sampledValue[sampledValuesIndex].value > maxAmperage || debug) {
79411696 820 logger.error(`${self._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 821 }
79411696 822 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
3f40bc9c
JB
823 const phaseValue = `L${phase}`;
824 sampledValues.sampledValue.push({
6af9012e
JB
825 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' },
826 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
827 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
828 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
829 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] },
7abfea5f
JB
830 phase: phaseValue,
831 });
832 }
0a60c33c 833 // Energy.Active.Import.Register measurand (default)
7abfea5f 834 } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === 'Energy.Active.Import.Register') {
38c8fd6c 835 // FIXME: factor out powerDivider checks
79411696
JB
836 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
837 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
6ecb15e4
JB
838 logger.error(errMsg);
839 throw Error(errMsg);
79411696
JB
840 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
841 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
6ecb15e4
JB
842 logger.error(errMsg);
843 throw Error(errMsg);
844 }
7abfea5f 845 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
79411696 846 const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval);
9b25a525 847 // Persist previous value in connector
3f40bc9c 848 if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) {
9b25a525
JB
849 connector.lastEnergyActiveImportRegisterValue += measurandValue;
850 } else {
851 connector.lastEnergyActiveImportRegisterValue = 0;
852 }
5ad8570f 853 }
7abfea5f 854 sampledValues.sampledValue.push({
6af9012e
JB
855 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Wh' },
856 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
857 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
858 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
859 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: connector.lastEnergyActiveImportRegisterValue },
7abfea5f
JB
860 });
861 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
79411696 862 const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval));
7abfea5f 863 if (sampledValues.sampledValue[sampledValuesIndex].value > maxConsumption || debug) {
79411696 864 logger.error(`${self._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 865 }
0a60c33c
JB
866 // Unsupported measurand
867 } else {
79411696 868 logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
5ad8570f
JB
869 }
870 }
871
872 const payload = {
bec64e8b 873 connectorId,
79411696 874 transactionId: self.getConnector(connectorId).transactionId,
7abfea5f 875 meterValue: sampledValues,
5ad8570f 876 };
79411696 877 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
5ad8570f 878 } catch (error) {
79411696 879 logger.error(self._logPrefix() + ' Send MeterValues error: ' + error);
0a60c33c 880 throw error;
5ad8570f
JB
881 }
882 }
883
65c5527e 884 async sendError(messageId, err: Error|OCPPError, commandName) {
7f134aca
JB
885 // Check exception type: only OCPP error are accepted
886 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack);
5ad8570f 887 // Send error
7f134aca 888 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName);
027b409a
JB
889 }
890
65c5527e
JB
891 async sendMessage(messageId, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string) {
892 // eslint-disable-next-line @typescript-eslint/no-this-alias
7dde0b73 893 const self = this;
6af9012e 894 // Send a message through wsConnection
7dde0b73
JB
895 return new Promise((resolve, reject) => {
896 let messageToSend;
897 // Type of message
898 switch (messageType) {
899 // Request
f7869514 900 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73 901 // Build request
7f134aca
JB
902 this._requests[messageId] = [responseCallback, rejectCallback, commandParams];
903 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
7dde0b73
JB
904 break;
905 // Response
f7869514 906 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73 907 // Build response
7f134aca 908 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
7dde0b73
JB
909 break;
910 // Error Message
f7869514 911 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
a979cc12 912 // Build Error Message
7f134aca 913 messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
7dde0b73
JB
914 break;
915 }
2e6f5966 916 // Check if wsConnection is ready
0a60c33c 917 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
7f134aca
JB
918 if (this.getEnableStatistics()) {
919 this._statistics.addMessage(commandName, messageType);
920 }
7dde0b73
JB
921 // Yes: Send Message
922 this._wsConnection.send(messageToSend);
923 } else {
7f134aca
JB
924 let dups = false;
925 // Handle dups in buffer
926 for (const message of this._messageQueue) {
927 // Same message
928 if (JSON.stringify(messageToSend) === JSON.stringify(message)) {
929 dups = true;
930 break;
931 }
932 }
933 if (!dups) {
934 // Buffer message
935 this._messageQueue.push(messageToSend);
936 }
a979cc12 937 // Reject it
7f134aca 938 return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Web socket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
7dde0b73 939 }
a979cc12
JB
940 // Response?
941 if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) {
7dde0b73
JB
942 // Yes: send Ok
943 resolve();
a979cc12
JB
944 } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) {
945 // Send timeout
7f134aca 946 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);
7dde0b73
JB
947 }
948
949 // Function that will receive the request's response
7f134aca
JB
950 function responseCallback(payload, requestPayload): void {
951 if (self.getEnableStatistics()) {
952 self._statistics.addMessage(commandName, messageType);
953 }
7dde0b73 954 // Send the response
a979cc12 955 self.handleResponse(commandName, payload, requestPayload);
7dde0b73
JB
956 resolve(payload);
957 }
958
959 // Function that will receive the request's rejection
7f134aca 960 function rejectCallback(error: OCPPError): void {
8bce55bf 961 if (self.getEnableStatistics()) {
7f134aca 962 self._statistics.addMessage(commandName, messageType);
8bce55bf 963 }
7f134aca 964 logger.debug(`${self._logPrefix()} Error %j occurred when calling command %s with parameters %j`, error, commandName, commandParams);
7dde0b73
JB
965 // Build Exception
966 // eslint-disable-next-line no-empty-function
967 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
7dde0b73
JB
968 // Send error
969 reject(error);
970 }
971 });
972 }
973
7f134aca 974 handleResponse(commandName: string, payload, requestPayload) {
3f40bc9c 975 const responseCallbackFn = 'handleResponse' + commandName;
6af9012e
JB
976 if (typeof this[responseCallbackFn] === 'function') {
977 this[responseCallbackFn](payload, requestPayload);
3f40bc9c 978 } else {
6af9012e 979 logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
3f40bc9c
JB
980 }
981 }
982
6af9012e 983 handleResponseBootNotification(payload, requestPayload) {
5ad8570f
JB
984 if (payload.status === 'Accepted') {
985 this._heartbeatInterval = payload.interval * 1000;
986 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
987 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
79411696 988 this._startMessageSequence();
0a60c33c 989 } else if (payload.status === 'Pending') {
fda4af57 990 logger.info(this._logPrefix() + ' Charging station in pending state on the central server');
5ad8570f 991 } else {
ead548f2 992 logger.info(this._logPrefix() + ' Charging station rejected by the central server');
7dde0b73 993 }
7dde0b73
JB
994 }
995
bec64e8b 996 _initTransactionOnConnector(connectorId) {
8bce55bf
JB
997 this.getConnector(connectorId).transactionStarted = false;
998 this.getConnector(connectorId).transactionId = null;
999 this.getConnector(connectorId).idTag = null;
1000 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
0a60c33c
JB
1001 }
1002
bec64e8b
JB
1003 _resetTransactionOnConnector(connectorId) {
1004 this._initTransactionOnConnector(connectorId);
8bce55bf
JB
1005 if (this.getConnector(connectorId).transactionSetInterval) {
1006 clearInterval(this.getConnector(connectorId).transactionSetInterval);
027b409a
JB
1007 }
1008 }
1009
7dde0b73 1010 handleResponseStartTransaction(payload, requestPayload) {
8bce55bf
JB
1011 if (this.getConnector(requestPayload.connectorId).transactionStarted) {
1012 logger.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ': %s', this.getConnector(requestPayload.connectorId));
2d0e26f5 1013 return;
d3a7883e 1014 }
84393381 1015
7de604f9
JB
1016 let transactionConnectorId;
1017 for (const connector in this._connectors) {
1018 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
1019 transactionConnectorId = connector;
1020 break;
7dde0b73 1021 }
7de604f9
JB
1022 }
1023 if (!transactionConnectorId) {
ead548f2 1024 logger.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId);
7de604f9
JB
1025 return;
1026 }
1027 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
8bce55bf
JB
1028 this.getConnector(requestPayload.connectorId).transactionStarted = true;
1029 this.getConnector(requestPayload.connectorId).transactionId = payload.transactionId;
1030 this.getConnector(requestPayload.connectorId).idTag = requestPayload.idTag;
1031 this.getConnector(requestPayload.connectorId).lastEnergyActiveImportRegisterValue = 0;
7de604f9 1032 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
ead548f2 1033 logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
6ecb15e4
JB
1034 if (this._stationInfo.powerSharedByConnectors) {
1035 this._stationInfo.powerDivider++;
1036 }
7de604f9 1037 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
5ad8570f 1038 this._startMeterValues(requestPayload.connectorId,
7de604f9 1039 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000);
7dde0b73 1040 } else {
ead548f2 1041 logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
8bce55bf 1042 this._resetTransactionOnConnector(requestPayload.connectorId);
7dde0b73
JB
1043 this.sendStatusNotification(requestPayload.connectorId, 'Available');
1044 }
1045 }
1046
34dcb3b5 1047 handleResponseStopTransaction(payload, requestPayload) {
d3a7883e
JB
1048 let transactionConnectorId;
1049 for (const connector in this._connectors) {
6af9012e 1050 if (this.getConnector(Utils.convertToInt(connector)).transactionId === requestPayload.transactionId) {
d3a7883e
JB
1051 transactionConnectorId = connector;
1052 break;
1053 }
1054 }
1055 if (!transactionConnectorId) {
ead548f2 1056 logger.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
7de604f9 1057 return;
d3a7883e
JB
1058 }
1059 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
1060 this.sendStatusNotification(transactionConnectorId, 'Available');
6ecb15e4
JB
1061 if (this._stationInfo.powerSharedByConnectors) {
1062 this._stationInfo.powerDivider--;
1063 }
ead548f2 1064 logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId);
d3a7883e 1065 this._resetTransactionOnConnector(transactionConnectorId);
34dcb3b5 1066 } else {
ead548f2 1067 logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
34dcb3b5
JB
1068 }
1069 }
1070
facd8ebd 1071 handleResponseStatusNotification(payload, requestPayload) {
ead548f2 1072 logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload);
7dde0b73
JB
1073 }
1074
facd8ebd 1075 handleResponseMeterValues(payload, requestPayload) {
ead548f2 1076 logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
027b409a
JB
1077 }
1078
facd8ebd 1079 handleResponseHeartbeat(payload, requestPayload) {
ead548f2 1080 logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
7dde0b73
JB
1081 }
1082
1083 async handleRequest(messageId, commandName, commandPayload) {
3f40bc9c 1084 let response;
7dde0b73 1085 // Call
fda4af57 1086 if (typeof this['handleRequest' + commandName] === 'function') {
7dde0b73 1087 try {
3f40bc9c 1088 // Call the method to build the response
fda4af57 1089 response = await this['handleRequest' + commandName](commandPayload);
7dde0b73
JB
1090 } catch (error) {
1091 // Log
ead548f2 1092 logger.error(this._logPrefix() + ' Handle request error: ' + error);
facd8ebd 1093 // Send back response to inform backend
7f134aca
JB
1094 await this.sendError(messageId, error, commandName);
1095 throw error;
7dde0b73
JB
1096 }
1097 } else {
84393381 1098 // Throw exception
64dc325e 1099 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName);
7dde0b73
JB
1100 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1101 }
84393381 1102 // Send response
7f134aca 1103 await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName);
7dde0b73
JB
1104 }
1105
fda4af57
JB
1106 // Simulate charging station restart
1107 async handleRequestReset(commandPayload) {
5ad8570f 1108 setImmediate(async () => {
2d0e26f5 1109 await this.stop(commandPayload.type + 'Reset');
0a60c33c 1110 await Utils.sleep(this._stationInfo.resetTime);
5ad8570f
JB
1111 await this.start();
1112 });
ead548f2 1113 logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
5ad8570f
JB
1114 return Constants.OCPP_RESPONSE_ACCEPTED;
1115 }
1116
61c2e33d
JB
1117 _getConfigurationKey(key) {
1118 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
1119 }
1120
3497da01 1121 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
61c2e33d
JB
1122 const keyFound = this._getConfigurationKey(key);
1123 if (!keyFound) {
1124 this._configuration.configurationKey.push({
1125 key,
1126 readonly,
1127 value,
1128 visible,
3497da01 1129 reboot,
61c2e33d
JB
1130 });
1131 }
1132 }
1133
1134 _setConfigurationKeyValue(key, value) {
1135 const keyFound = this._getConfigurationKey(key);
1136 if (keyFound) {
d3a7883e
JB
1137 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
1138 this._configuration.configurationKey[keyIndex].value = value;
61c2e33d
JB
1139 }
1140 }
1141
fda4af57 1142 async handleRequestGetConfiguration(commandPayload) {
facd8ebd
JB
1143 const configurationKey = [];
1144 const unknownKey = [];
61c2e33d
JB
1145 if (Utils.isEmptyArray(commandPayload.key)) {
1146 for (const configuration of this._configuration.configurationKey) {
1147 if (Utils.isUndefined(configuration.visible)) {
1148 configuration.visible = true;
1149 } else {
1150 configuration.visible = Utils.convertToBoolean(configuration.visible);
1151 }
1152 if (!configuration.visible) {
1153 continue;
1154 }
1155 configurationKey.push({
1156 key: configuration.key,
1157 readonly: configuration.readonly,
1158 value: configuration.value,
1159 });
facd8ebd 1160 }
61c2e33d 1161 } else {
d20c21a0
JB
1162 for (const configurationKey of commandPayload.key) {
1163 const keyFound = this._getConfigurationKey(configurationKey);
61c2e33d
JB
1164 if (keyFound) {
1165 if (Utils.isUndefined(keyFound.visible)) {
1166 keyFound.visible = true;
1167 } else {
d20c21a0 1168 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
61c2e33d
JB
1169 }
1170 if (!keyFound.visible) {
1171 continue;
1172 }
1173 configurationKey.push({
1174 key: keyFound.key,
1175 readonly: keyFound.readonly,
1176 value: keyFound.value,
1177 });
1178 } else {
d20c21a0 1179 unknownKey.push(configurationKey);
61c2e33d 1180 }
facd8ebd 1181 }
facd8ebd
JB
1182 }
1183 return {
1184 configurationKey,
1185 unknownKey,
1186 };
7dde0b73
JB
1187 }
1188
fda4af57 1189 async handleRequestChangeConfiguration(commandPayload) {
61c2e33d 1190 const keyToChange = this._getConfigurationKey(commandPayload.key);
7d887a1b 1191 if (!keyToChange) {
6af9012e 1192 return { status: Constants.OCPP_ERROR_NOT_SUPPORTED };
7d887a1b
JB
1193 } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) {
1194 return Constants.OCPP_RESPONSE_REJECTED;
1195 } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
a6e68f34
JB
1196 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
1197 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
d3a7883e
JB
1198 let triggerHeartbeatRestart = false;
1199 if (keyToChange.key === 'HeartBeatInterval') {
1200 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
1201 triggerHeartbeatRestart = true;
1202 }
1203 if (keyToChange.key === 'HeartbeatInterval') {
1204 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
1205 triggerHeartbeatRestart = true;
1206 }
1207 if (triggerHeartbeatRestart) {
5c68da4d
JB
1208 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
1209 // Stop heartbeat
0a60c33c 1210 this._stopHeartbeat();
5c68da4d 1211 // Start heartbeat
6af9012e 1212 this._startHeartbeat();
5c68da4d 1213 }
7d887a1b
JB
1214 if (Utils.convertToBoolean(keyToChange.reboot)) {
1215 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
1216 }
dcab13bd 1217 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 1218 }
7dde0b73
JB
1219 }
1220
fda4af57 1221 async handleRequestRemoteStartTransaction(commandPayload) {
72766a82 1222 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
fda4af57 1223 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
dcab13bd 1224 // Check if authorized
2e6f5966 1225 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
7dde0b73 1226 // Authorization successful start transaction
65c5527e 1227 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
ead548f2 1228 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
dcab13bd 1229 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 1230 }
ead548f2 1231 logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
dcab13bd 1232 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 1233 }
dcab13bd 1234 // No local authorization check required => start transaction
65c5527e 1235 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
ead548f2 1236 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
027b409a
JB
1237 return Constants.OCPP_RESPONSE_ACCEPTED;
1238 }
1239
fda4af57 1240 async handleRequestRemoteStopTransaction(commandPayload) {
027b409a 1241 for (const connector in this._connectors) {
6af9012e 1242 if (this.getConnector(Utils.convertToInt(connector)).transactionId === commandPayload.transactionId) {
65c5527e 1243 await this.sendStopTransaction(commandPayload.transactionId);
d3a7883e 1244 return Constants.OCPP_RESPONSE_ACCEPTED;
027b409a
JB
1245 }
1246 }
ead548f2 1247 logger.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
d3a7883e 1248 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 1249 }
7dde0b73
JB
1250}
1251