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