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