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