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