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