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