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