1 import { AuthorizationStatus
, AuthorizeRequest
, AuthorizeResponse
, 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
, VoltageOut
} 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';
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';
31 import logger from
'../utils/Logger';
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
;
57 constructor(index
: number, stationTemplateFile
: string) {
59 this._stationTemplateFile
= stationTemplateFile
;
60 this._connectors
= {} as Connectors
;
63 this._hasStopped
= false;
64 this._hasSocketRestarted
= false;
65 this._autoReconnectRetryCount
= 0;
67 this._requests
= {} as Requests
;
68 this._messageQueue
= [] as string[];
70 this._authorizedTags
= this._loadAndGetAuthorizedTags();
73 _getStationName(stationTemplate
: ChargingStationTemplate
): string {
74 // In case of multiple instances: add instance index to charging station id
75 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
? process
.env
.CF_INSTANCE_INDEX
: 0;
76 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
78 const idSuffix
= stationTemplate
.nameSuffix
? stationTemplate
.nameSuffix
: '';
80 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this._index
.toString()).substr(('000000000' + this._index
.toString()).length
- 4) + idSuffix
;
83 _buildStationInfo(): ChargingStationInfo
{
84 let stationTemplateFromFile
: ChargingStationTemplate
;
87 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
88 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
89 fs
.closeSync(fileDescriptor
);
91 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: %j', error
);
94 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
95 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
96 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
97 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
99 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
101 stationInfo
.name
= this._getStationName(stationTemplateFromFile
);
102 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
106 get
stationInfo(): ChargingStationInfo
{
107 return this._stationInfo
;
110 _initialize(): void {
111 this._stationInfo
= this._buildStationInfo();
112 this._bootNotificationRequest
= {
113 chargePointModel
: this._stationInfo
.chargePointModel
,
114 chargePointVendor
: this._stationInfo
.chargePointVendor
,
115 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
116 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && { firmwareVersion
: this._stationInfo
.firmwareVersion
},
118 this._configuration
= this._getTemplateChargingStationConfiguration();
119 this._supervisionUrl
= this._getSupervisionURL();
120 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
121 // Build connectors if needed
122 const maxConnectors
= this._getMaxNumberOfConnectors();
123 if (maxConnectors
<= 0) {
124 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
126 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
127 if (templateMaxConnectors
<= 0) {
128 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configuration`);
130 if (!this._stationInfo
.Connectors
[0]) {
131 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector Id 0 configuration`);
134 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this._stationInfo
.randomConnectors
) {
135 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
136 this._stationInfo
.randomConnectors
= true;
138 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
139 // FIXME: Handle shrinking the number of connectors
140 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
141 this._connectorsConfigurationHash
= connectorsConfigHash
;
142 // Add connector Id 0
143 let lastConnector
= '0';
144 for (lastConnector
in this._stationInfo
.Connectors
) {
145 if (Utils
.convertToInt(lastConnector
) === 0 && this._getUseConnectorId0() && this._stationInfo
.Connectors
[lastConnector
]) {
146 this._connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this._stationInfo
.Connectors
[lastConnector
]);
147 this._connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
150 // Generate all connectors
151 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
152 for (let index
= 1; index
<= maxConnectors
; index
++) {
153 const randConnectorID
= this._stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
154 this._connectors
[index
] = Utils
.cloneObject
<Connector
>(this._stationInfo
.Connectors
[randConnectorID
]);
155 this._connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
159 // Avoid duplication of connectors related information
160 delete this._stationInfo
.Connectors
;
161 // Initialize transaction attributes on connectors
162 for (const connector
in this._connectors
) {
163 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
164 this._initTransactionOnConnector(Utils
.convertToInt(connector
));
168 this._addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this._getNumberOfConnectors().toString(), true);
169 if (!this._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
170 this._addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
172 this._stationInfo
.powerDivider
= this._getPowerDivider();
173 if (this.getEnableStatistics()) {
174 this._statistics
= Statistics
.getInstance();
175 this._statistics
.objName
= this._stationInfo
.name
;
176 this._performanceObserver
= new PerformanceObserver((list
) => {
177 const entry
= list
.getEntries()[0];
178 this._statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
179 this._performanceObserver
.disconnect();
184 get
connectors(): Connectors
{
185 return this._connectors
;
188 get
statistics(): Statistics
{
189 return this._statistics
;
192 _logPrefix(): string {
193 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
196 _isWebSocketOpen(): boolean {
197 return this._wsConnection
?.readyState
=== WebSocket
.OPEN
;
200 _isRegistered(): boolean {
201 return this._bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
204 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
205 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
208 _getAuthorizationFile(): string {
209 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
212 _getUseConnectorId0(): boolean {
213 return !Utils
.isUndefined(this._stationInfo
.useConnectorId0
) ? this._stationInfo
.useConnectorId0
: true;
216 _loadAndGetAuthorizedTags(): string[] {
217 let authorizedTags
: string[] = [];
218 const authorizationFile
= this._getAuthorizationFile();
219 if (authorizationFile
) {
221 // Load authorization file
222 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
223 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
224 fs
.closeSync(fileDescriptor
);
226 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
230 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
232 return authorizedTags
;
235 getRandomTagId(): string {
236 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
237 return this._authorizedTags
[index
];
240 hasAuthorizedTags(): boolean {
241 return !Utils
.isEmptyArray(this._authorizedTags
);
244 getEnableStatistics(): boolean {
245 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? this._stationInfo
.enableStatistics
: true;
248 _getNumberOfPhases(): number {
249 switch (this._getPowerOutType()) {
250 case PowerOutType
.AC
:
251 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? this._stationInfo
.numberOfPhases
: 3;
252 case PowerOutType
.DC
:
257 _getNumberOfRunningTransactions(): number {
259 for (const connector
in this._connectors
) {
260 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
268 _getConnectionTimeout(): number {
269 if (!Utils
.isUndefined(this._stationInfo
.connectionTimeout
)) {
270 return this._stationInfo
.connectionTimeout
;
272 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
273 return Configuration
.getConnectionTimeout();
278 // -1 for unlimited, 0 for disabling
279 _getAutoReconnectMaxRetries(): number {
280 if (!Utils
.isUndefined(this._stationInfo
.autoReconnectMaxRetries
)) {
281 return this._stationInfo
.autoReconnectMaxRetries
;
283 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
284 return Configuration
.getAutoReconnectMaxRetries();
290 _getRegistrationMaxRetries(): number {
291 if (!Utils
.isUndefined(this._stationInfo
.registrationMaxRetries
)) {
292 return this._stationInfo
.registrationMaxRetries
;
297 _getPowerDivider(): number {
298 let powerDivider
= this._getNumberOfConnectors();
299 if (this._stationInfo
.powerSharedByConnectors
) {
300 powerDivider
= this._getNumberOfRunningTransactions();
305 getConnector(id
: number): Connector
{
306 return this._connectors
[id
];
309 _isConnectorAvailable(id
: number): boolean {
310 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
313 _isChargingStationAvailable(): boolean {
314 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
317 _getTemplateMaxNumberOfConnectors(): number {
318 return Object.keys(this._stationInfo
.Connectors
).length
;
321 _getMaxNumberOfConnectors(): number {
322 let maxConnectors
= 0;
323 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
324 const numberOfConnectors
= this._stationInfo
.numberOfConnectors
as number[];
325 // Distribute evenly the number of connectors
326 maxConnectors
= numberOfConnectors
[(this._index
- 1) % numberOfConnectors
.length
];
327 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
328 maxConnectors
= this._stationInfo
.numberOfConnectors
as number;
330 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
332 return maxConnectors
;
335 _getNumberOfConnectors(): number {
336 return this._connectors
[0] ? Object.keys(this._connectors
).length
- 1 : Object.keys(this._connectors
).length
;
339 _getVoltageOut(): number {
340 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
341 let defaultVoltageOut
: number;
342 switch (this._getPowerOutType()) {
343 case PowerOutType
.AC
:
344 defaultVoltageOut
= VoltageOut
.VOLTAGE_230
;
346 case PowerOutType
.DC
:
347 defaultVoltageOut
= VoltageOut
.VOLTAGE_400
;
350 logger
.error(errMsg
);
353 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? this._stationInfo
.voltageOut
: defaultVoltageOut
;
356 _getTransactionIdTag(transactionId
: number): string {
357 for (const connector
in this._connectors
) {
358 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
359 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
364 _getTransactionMeterStop(transactionId
: number): number {
365 for (const connector
in this._connectors
) {
366 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
367 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
372 _getPowerOutType(): PowerOutType
{
373 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: PowerOutType
.AC
;
376 _getSupervisionURL(): string {
377 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
379 if (!Utils
.isEmptyArray(supervisionUrls
)) {
380 if (Configuration
.getDistributeStationsToTenantsEqually()) {
381 indexUrl
= this._index
% supervisionUrls
.length
;
384 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
386 return supervisionUrls
[indexUrl
];
388 return supervisionUrls
as string;
391 _getReconnectExponentialDelay(): boolean {
392 return !Utils
.isUndefined(this._stationInfo
.reconnectExponentialDelay
) ? this._stationInfo
.reconnectExponentialDelay
: false;
395 _getHeartbeatInterval(): number {
396 const HeartbeatInterval
= this._getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
397 if (HeartbeatInterval
) {
398 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
400 const HeartBeatInterval
= this._getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
401 if (HeartBeatInterval
) {
402 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
406 _getAuthorizeRemoteTxRequests(): boolean {
407 const authorizeRemoteTxRequests
= this._getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
408 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
411 _getLocalAuthListEnabled(): boolean {
412 const localAuthListEnabled
= this._getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
413 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
416 async _startMessageSequence(): Promise
<void> {
417 // Start WebSocket ping
418 this._startWebSocketPing();
420 this._startHeartbeat();
421 // Initialize connectors status
422 for (const connector
in this._connectors
) {
423 if (Utils
.convertToInt(connector
) === 0) {
425 } else if (!this._hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
426 // Send status in template at startup
427 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
428 } else if (this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
429 // Send status in template after reset
430 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
431 } else if (!this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
432 // Send previous status at template reload
433 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
435 // Send default status
436 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
440 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
) {
441 if (!this._automaticTransactionGeneration
) {
442 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
444 if (this._automaticTransactionGeneration
.timeToStop
) {
445 this._automaticTransactionGeneration
.start();
448 if (this.getEnableStatistics()) {
449 this._statistics
.start();
453 async _stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
454 // Stop WebSocket ping
455 this._stopWebSocketPing();
457 this._stopHeartbeat();
459 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
460 this._automaticTransactionGeneration
&&
461 !this._automaticTransactionGeneration
.timeToStop
) {
462 await this._automaticTransactionGeneration
.stop(reason
);
464 for (const connector
in this._connectors
) {
465 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
466 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
472 _startWebSocketPing(): void {
473 const webSocketPingInterval
: number = this._getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
) ? Utils
.convertToInt(this._getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
) : 0;
474 if (webSocketPingInterval
> 0 && !this._webSocketPingSetInterval
) {
475 this._webSocketPingSetInterval
= setInterval(() => {
476 if (this._isWebSocketOpen()) {
477 this._wsConnection
.ping((): void => { });
479 }, webSocketPingInterval
* 1000);
480 logger
.info(this._logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
481 } else if (this._webSocketPingSetInterval
) {
482 logger
.info(this._logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
484 logger
.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
488 _stopWebSocketPing(): void {
489 if (this._webSocketPingSetInterval
) {
490 clearInterval(this._webSocketPingSetInterval
);
491 this._webSocketPingSetInterval
= null;
495 _restartWebSocketPing(): void {
496 // Stop WebSocket ping
497 this._stopWebSocketPing();
498 // Start WebSocket ping
499 this._startWebSocketPing();
502 _startHeartbeat(): void {
503 if (this._getHeartbeatInterval() && this._getHeartbeatInterval() > 0 && !this._heartbeatSetInterval
) {
504 this._heartbeatSetInterval
= setInterval(async () => {
505 await this.sendHeartbeat();
506 }, this._getHeartbeatInterval());
507 logger
.info(this._logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this._getHeartbeatInterval()));
508 } else if (this._heartbeatSetInterval
) {
509 logger
.info(this._logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this._getHeartbeatInterval()) + ' already started');
511 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this._getHeartbeatInterval()) : this._getHeartbeatInterval()}, not starting the heartbeat`);
515 _stopHeartbeat(): void {
516 if (this._heartbeatSetInterval
) {
517 clearInterval(this._heartbeatSetInterval
);
518 this._heartbeatSetInterval
= null;
522 _restartHeartbeat(): void {
524 this._stopHeartbeat();
526 this._startHeartbeat();
529 _startAuthorizationFileMonitoring(): void {
530 fs
.watch(this._getAuthorizationFile()).on('change', (e
) => {
532 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
533 // Initialize _authorizedTags
534 this._authorizedTags
= this._loadAndGetAuthorizedTags();
536 logger
.error(this._logPrefix() + ' Authorization file monitoring error: %j', error
);
541 _startStationTemplateFileMonitoring(): void {
542 fs
.watch(this._stationTemplateFile
).on('change', (e
) => {
544 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
548 if (!this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
549 this._automaticTransactionGeneration
) {
550 this._automaticTransactionGeneration
.stop().catch(() => { });
553 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
) {
554 if (!this._automaticTransactionGeneration
) {
555 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
557 if (this._automaticTransactionGeneration
.timeToStop
) {
558 this._automaticTransactionGeneration
.start();
561 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
563 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error
);
568 _startMeterValues(connectorId
: number, interval
: number): void {
569 if (connectorId
=== 0) {
570 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
573 if (!this.getConnector(connectorId
)) {
574 logger
.error(`${this._logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
577 if (!this.getConnector(connectorId
)?.transactionStarted
) {
578 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
580 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
581 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
585 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
586 if (this.getEnableStatistics()) {
587 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
588 this._performanceObserver
.observe({
589 entryTypes
: ['function'],
591 await sendMeterValues(connectorId
, interval
, this);
593 await this.sendMeterValues(connectorId
, interval
, this);
597 logger
.error(`${this._logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
601 _openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
602 if (Utils
.isUndefined(options
)) {
603 options
= {} as WebSocket
.ClientOptions
;
605 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
606 options
.handshakeTimeout
= this._getConnectionTimeout() * 1000;
608 if (this._isWebSocketOpen() && forceCloseOpened
) {
609 this._wsConnection
.close();
611 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
, options
);
612 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
616 this._openWSConnection();
617 // Monitor authorization file
618 this._startAuthorizationFileMonitoring();
619 // Monitor station template file
620 this._startStationTemplateFileMonitoring();
621 // Handle Socket incoming messages
622 this._wsConnection
.on('message', this.onMessage
.bind(this));
623 // Handle Socket error
624 this._wsConnection
.on('error', this.onError
.bind(this));
625 // Handle Socket close
626 this._wsConnection
.on('close', this.onClose
.bind(this));
627 // Handle Socket opening connection
628 this._wsConnection
.on('open', this.onOpen
.bind(this));
629 // Handle Socket ping
630 this._wsConnection
.on('ping', this.onPing
.bind(this));
631 // Handle Socket pong
632 this._wsConnection
.on('pong', this.onPong
.bind(this));
635 async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
636 // Stop message sequence
637 await this._stopMessageSequence(reason
);
638 for (const connector
in this._connectors
) {
639 if (Utils
.convertToInt(connector
) > 0) {
640 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
643 if (this._isWebSocketOpen()) {
644 this._wsConnection
.close();
646 this._bootNotificationResponse
= null;
647 this._hasStopped
= true;
650 async _reconnect(error
): Promise
<void> {
652 this._stopHeartbeat();
653 // Stop the ATG if needed
654 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
655 this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
656 this._automaticTransactionGeneration
&&
657 !this._automaticTransactionGeneration
.timeToStop
) {
658 this._automaticTransactionGeneration
.stop().catch(() => { });
660 if (this._autoReconnectRetryCount
< this._getAutoReconnectMaxRetries() || this._getAutoReconnectMaxRetries() === -1) {
661 this._autoReconnectRetryCount
++;
662 const reconnectDelay
= (this._getReconnectExponentialDelay() ? Utils
.exponentialDelay(this._autoReconnectRetryCount
) : this._getConnectionTimeout() * 1000);
663 logger
.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
664 await Utils
.sleep(reconnectDelay
);
665 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
.toString());
666 this._openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
667 this._hasSocketRestarted
= true;
668 } else if (this._getAutoReconnectMaxRetries() !== -1) {
669 logger
.error(`${this._logPrefix()} Socket reconnect failure: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`);
673 async onOpen(): Promise
<void> {
674 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
675 if (!this._isRegistered()) {
676 // Send BootNotification
677 let registrationRetryCount
= 0;
679 this._bootNotificationResponse
= await this.sendBootNotification();
680 if (!this._isRegistered()) {
681 registrationRetryCount
++;
682 await Utils
.sleep(this._bootNotificationResponse
?.interval
? this._bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
684 } while (!this._isRegistered() && (registrationRetryCount
<= this._getRegistrationMaxRetries() || this._getRegistrationMaxRetries() === -1));
686 if (this._isRegistered()) {
687 await this._startMessageSequence();
688 if (this._hasSocketRestarted
&& this._isWebSocketOpen()) {
689 if (!Utils
.isEmptyArray(this._messageQueue
)) {
690 this._messageQueue
.forEach((message
, index
) => {
691 this._messageQueue
.splice(index
, 1);
692 this._wsConnection
.send(message
);
697 logger
.error(`${this._logPrefix()} Registration failure: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`);
699 this._autoReconnectRetryCount
= 0;
700 this._hasSocketRestarted
= false;
703 async onError(errorEvent
): Promise
<void> {
704 logger
.error(this._logPrefix() + ' Socket error: %j', errorEvent
);
705 // pragma switch (errorEvent.code) {
706 // case 'ECONNREFUSED':
707 // await this._reconnect(errorEvent);
712 async onClose(closeEvent
): Promise
<void> {
713 switch (closeEvent
) {
714 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
715 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
716 logger
.info(`${this._logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
717 this._autoReconnectRetryCount
= 0;
719 default: // Abnormal close
720 logger
.error(`${this._logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
721 await this._reconnect(closeEvent
);
727 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
731 logger
.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
734 async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
735 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
736 let responseCallback
: (payload
?: Record
<string, unknown
> | string, requestPayload
?: Record
<string, unknown
>) => void;
737 let rejectCallback
: (error
: OCPPError
) => void;
738 let requestPayload
: Record
<string, unknown
>;
742 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
744 // Check the Type of message
745 switch (messageType
) {
747 case MessageType
.CALL_MESSAGE
:
748 if (this.getEnableStatistics()) {
749 this._statistics
.addMessage(commandName
, messageType
);
752 await this.handleRequest(messageId
, commandName
, commandPayload
);
755 case MessageType
.CALL_RESULT_MESSAGE
:
757 if (Utils
.isIterable(this._requests
[messageId
])) {
758 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
760 throw new Error(`Response request for message id ${messageId} is not iterable`);
762 if (!responseCallback
) {
764 throw new Error(`Response request for unknown message id ${messageId}`);
766 delete this._requests
[messageId
];
767 responseCallback(commandName
, requestPayload
);
770 case MessageType
.CALL_ERROR_MESSAGE
:
771 if (!this._requests
[messageId
]) {
773 throw new Error(`Error request for unknown message id ${messageId}`);
775 if (Utils
.isIterable(this._requests
[messageId
])) {
776 [, rejectCallback
] = this._requests
[messageId
];
778 throw new Error(`Error request for message id ${messageId} is not iterable`);
780 delete this._requests
[messageId
];
781 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
785 errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
786 logger
.error(errMsg
);
787 throw new Error(errMsg
);
791 logger
.error('%s Incoming message %j processing error %j on request content type %j', this._logPrefix(), messageEvent
, error
, this._requests
[messageId
]);
793 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.sendError(messageId
, error
, commandName
);
797 async sendHeartbeat(): Promise
<void> {
799 const payload
: HeartbeatRequest
= {};
800 await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.HEARTBEAT
);
802 this.handleRequestError(RequestCommand
.HEARTBEAT
, error
);
806 async sendBootNotification(): Promise
<BootNotificationResponse
> {
808 return await this.sendMessage(Utils
.generateUUID(), this._bootNotificationRequest
, MessageType
.CALL_MESSAGE
, RequestCommand
.BOOT_NOTIFICATION
) as BootNotificationResponse
;
810 this.handleRequestError(RequestCommand
.BOOT_NOTIFICATION
, error
);
814 async sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
: ChargePointErrorCode
= ChargePointErrorCode
.NO_ERROR
): Promise
<void> {
815 this.getConnector(connectorId
).status = status;
817 const payload
: StatusNotificationRequest
= {
822 await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.STATUS_NOTIFICATION
);
824 this.handleRequestError(RequestCommand
.STATUS_NOTIFICATION
, error
);
828 async sendAuthorize(idTag
?: string): Promise
<AuthorizeResponse
> {
830 const payload
: AuthorizeRequest
= {
831 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_TAGID
},
833 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.AUTHORIZE
) as AuthorizeResponse
;
835 this.handleRequestError(RequestCommand
.AUTHORIZE
, error
);
839 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<StartTransactionResponse
> {
841 const payload
: StartTransactionRequest
= {
843 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_TAGID
},
845 timestamp
: new Date().toISOString(),
847 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.START_TRANSACTION
) as StartTransactionResponse
;
849 this.handleRequestError(RequestCommand
.START_TRANSACTION
, error
);
853 async sendStopTransaction(transactionId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
854 const idTag
= this._getTransactionIdTag(transactionId
);
856 const payload
: StopTransactionRequest
= {
858 ...!Utils
.isUndefined(idTag
) && { idTag
: idTag
},
859 meterStop
: this._getTransactionMeterStop(transactionId
),
860 timestamp
: new Date().toISOString(),
861 ...reason
&& { reason
},
863 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.STOP_TRANSACTION
) as StartTransactionResponse
;
865 this.handleRequestError(RequestCommand
.STOP_TRANSACTION
, error
);
869 async sendError(messageId
: string, error
: OCPPError
, commandName
: RequestCommand
| IncomingRequestCommand
): Promise
<unknown
> {
871 return this.sendMessage(messageId
, error
, MessageType
.CALL_ERROR_MESSAGE
, commandName
);
874 async sendMessage(messageId
: string, commandParams
: any, messageType
: MessageType
= MessageType
.CALL_RESULT_MESSAGE
, commandName
: RequestCommand
| IncomingRequestCommand
): Promise
<any> {
875 // eslint-disable-next-line @typescript-eslint/no-this-alias
877 // Send a message through wsConnection
878 return new Promise((resolve
: (value
?: any | PromiseLike
<any>) => void, reject
: (reason
?: any) => void) => {
879 let messageToSend
: string;
881 switch (messageType
) {
883 case MessageType
.CALL_MESSAGE
:
885 this._requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
] as Request
;
886 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
889 case MessageType
.CALL_RESULT_MESSAGE
:
891 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
894 case MessageType
.CALL_ERROR_MESSAGE
:
895 // Build Error Message
896 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: ErrorType
.GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
899 // Check if wsConnection opened and charging station registered
900 if (this._isWebSocketOpen() && (this._isRegistered() || commandName
=== RequestCommand
.BOOT_NOTIFICATION
)) {
901 if (this.getEnableStatistics()) {
902 this._statistics
.addMessage(commandName
, messageType
);
905 this._wsConnection
.send(messageToSend
);
906 } else if (commandName
!== RequestCommand
.BOOT_NOTIFICATION
) {
908 // Handle dups in buffer
909 for (const message
of this._messageQueue
) {
911 if (messageToSend
=== message
) {
918 this._messageQueue
.push(messageToSend
);
921 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
: {}));
924 if (messageType
=== MessageType
.CALL_RESULT_MESSAGE
) {
927 } else if (messageType
=== MessageType
.CALL_ERROR_MESSAGE
) {
929 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
);
932 // Function that will receive the request's response
933 async function responseCallback(payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>): Promise
<void> {
934 if (self.getEnableStatistics()) {
935 self._statistics
.addMessage(commandName
, messageType
);
938 await self.handleResponse(commandName
as RequestCommand
, payload
, requestPayload
);
942 // Function that will receive the request's rejection
943 function rejectCallback(error
: OCPPError
): void {
944 if (self.getEnableStatistics()) {
945 self._statistics
.addMessage(commandName
, messageType
);
947 logger
.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error
, commandName
, commandParams
);
949 // eslint-disable-next-line no-empty-function
950 self._requests
[messageId
] = [() => { }, () => { }, {}]; // Properly format the request
957 async handleResponse(commandName
: RequestCommand
, payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>): Promise
<void> {
958 const responseCallbackFn
= 'handleResponse' + commandName
;
959 if (typeof this[responseCallbackFn
] === 'function') {
960 await this[responseCallbackFn
](payload
, requestPayload
);
962 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
966 handleResponseBootNotification(payload
: BootNotificationResponse
, requestPayload
: BootNotificationRequest
): void {
967 if (payload
.status === RegistrationStatus
.ACCEPTED
) {
968 this._heartbeatSetInterval
? this._restartHeartbeat() : this._startHeartbeat();
969 this._addConfigurationKey(StandardParametersKey
.HeartBeatInterval
, payload
.interval
.toString());
970 this._addConfigurationKey(StandardParametersKey
.HeartbeatInterval
, payload
.interval
.toString(), false, false);
971 this._hasStopped
&& (this._hasStopped
= false);
972 } else if (payload
.status === RegistrationStatus
.PENDING
) {
973 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
975 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
979 _initTransactionOnConnector(connectorId
: number): void {
980 this.getConnector(connectorId
).transactionStarted
= false;
981 this.getConnector(connectorId
).transactionId
= null;
982 this.getConnector(connectorId
).idTag
= null;
983 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
986 _resetTransactionOnConnector(connectorId
: number): void {
987 this._initTransactionOnConnector(connectorId
);
988 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
989 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
993 async handleResponseStartTransaction(payload
: StartTransactionResponse
, requestPayload
: StartTransactionRequest
): Promise
<void> {
994 const connectorId
= requestPayload
.connectorId
;
996 let transactionConnectorId
: number;
997 for (const connector
in this._connectors
) {
998 if (Utils
.convertToInt(connector
) > 0 && Utils
.convertToInt(connector
) === connectorId
) {
999 transactionConnectorId
= Utils
.convertToInt(connector
);
1003 if (!transactionConnectorId
) {
1004 logger
.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId
.toString());
1007 if (this.getConnector(connectorId
)?.transactionStarted
) {
1008 logger
.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId
.toString() + ': %j', this.getConnector(connectorId
));
1012 if (payload
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1013 this.getConnector(connectorId
).transactionStarted
= true;
1014 this.getConnector(connectorId
).transactionId
= payload
.transactionId
;
1015 this.getConnector(connectorId
).idTag
= requestPayload
.idTag
;
1016 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1017 await this.sendStatusNotification(connectorId
, ChargePointStatus
.CHARGING
);
1018 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
.toString() + ' STARTED on ' + this._stationInfo
.name
+ '#' + connectorId
.toString() + ' for idTag ' + requestPayload
.idTag
);
1019 if (this._stationInfo
.powerSharedByConnectors
) {
1020 this._stationInfo
.powerDivider
++;
1022 const configuredMeterValueSampleInterval
= this._getConfigurationKey(StandardParametersKey
.MeterValueSampleInterval
);
1023 this._startMeterValues(connectorId
,
1024 configuredMeterValueSampleInterval
? Utils
.convertToInt(configuredMeterValueSampleInterval
.value
) * 1000 : 60000);
1026 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
.toString() + ' REJECTED with status ' + payload
?.idTagInfo
?.status + ', idTag ' + requestPayload
.idTag
);
1027 this._resetTransactionOnConnector(connectorId
);
1028 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1032 async handleResponseStopTransaction(payload
: StopTransactionResponse
, requestPayload
: StopTransactionRequest
): Promise
<void> {
1033 let transactionConnectorId
: number;
1034 for (const connector
in this._connectors
) {
1035 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
))?.transactionId
=== requestPayload
.transactionId
) {
1036 transactionConnectorId
= Utils
.convertToInt(connector
);
1040 if (!transactionConnectorId
) {
1041 logger
.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload
.transactionId
.toString());
1044 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1045 if (!this._isChargingStationAvailable() || !this._isConnectorAvailable(transactionConnectorId
)) {
1046 await this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.UNAVAILABLE
);
1048 await this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.AVAILABLE
);
1050 if (this._stationInfo
.powerSharedByConnectors
) {
1051 this._stationInfo
.powerDivider
--;
1053 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
.toString() + ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
.toString());
1054 this._resetTransactionOnConnector(transactionConnectorId
);
1056 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
?.status);
1060 handleResponseStatusNotification(payload
: StatusNotificationRequest
, requestPayload
: StatusNotificationResponse
): void {
1061 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1064 handleResponseMeterValues(payload
: MeterValuesRequest
, requestPayload
: MeterValuesResponse
): void {
1065 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1068 handleResponseHeartbeat(payload
: HeartbeatResponse
, requestPayload
: HeartbeatRequest
): void {
1069 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1072 async handleRequest(messageId
: string, commandName
: IncomingRequestCommand
, commandPayload
: Record
<string, unknown
>): Promise
<void> {
1075 if (typeof this['handleRequest' + commandName
] === 'function') {
1077 // Call the method to build the response
1078 response
= await this['handleRequest' + commandName
](commandPayload
);
1081 logger
.error(this._logPrefix() + ' Handle request error: %j', error
);
1082 // Send back response to inform backend
1083 await this.sendError(messageId
, error
, commandName
);
1088 await this.sendError(messageId
, new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1089 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1092 await this.sendMessage(messageId
, response
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
1095 // Simulate charging station restart
1096 handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
1097 setImmediate(async () => {
1098 await this.stop(commandPayload
.type + 'Reset' as StopTransactionReason
);
1099 await Utils
.sleep(this._stationInfo
.resetTime
);
1102 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`);
1103 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1106 handleRequestClearCache(): DefaultResponse
{
1107 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1110 async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
1111 const connectorId
= commandPayload
.connectorId
;
1112 if (connectorId
=== 0) {
1113 logger
.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
1114 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
1116 if (this.getConnector(connectorId
)?.transactionStarted
) {
1117 const stopResponse
= await this.sendStopTransaction(this.getConnector(connectorId
).transactionId
, StopTransactionReason
.UNLOCK_COMMAND
);
1118 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1119 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1121 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
1123 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1124 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1127 _getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
{
1128 const configurationKey
: ConfigurationKey
= this._configuration
.configurationKey
.find((configElement
) => {
1129 if (caseInsensitive
) {
1130 return configElement
.key
.toLowerCase() === key
.toLowerCase();
1132 return configElement
.key
=== key
;
1134 return configurationKey
;
1137 _addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
1138 const keyFound
= this._getConfigurationKey(key
);
1140 this._configuration
.configurationKey
.push({
1148 logger
.error(`${this._logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
1152 _setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
1153 const keyFound
= this._getConfigurationKey(key
);
1155 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1156 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1158 logger
.error(`${this._logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
1162 handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
1163 const configurationKey
: OCPPConfigurationKey
[] = [];
1164 const unknownKey
: string[] = [];
1165 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1166 for (const configuration
of this._configuration
.configurationKey
) {
1167 if (Utils
.isUndefined(configuration
.visible
)) {
1168 configuration
.visible
= true;
1170 if (!configuration
.visible
) {
1173 configurationKey
.push({
1174 key
: configuration
.key
,
1175 readonly: configuration
.readonly,
1176 value
: configuration
.value
,
1180 for (const key
of commandPayload
.key
) {
1181 const keyFound
= this._getConfigurationKey(key
);
1183 if (Utils
.isUndefined(keyFound
.visible
)) {
1184 keyFound
.visible
= true;
1186 if (!keyFound
.visible
) {
1189 configurationKey
.push({
1191 readonly: keyFound
.readonly,
1192 value
: keyFound
.value
,
1195 unknownKey
.push(key
);
1205 handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
1206 // JSON request fields type sanity check
1207 if (!Utils
.isString(commandPayload
.key
)) {
1208 logger
.error(`${this._logPrefix()} ChangeConfiguration request key field is not a string:`, commandPayload
);
1210 if (!Utils
.isString(commandPayload
.value
)) {
1211 logger
.error(`${this._logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload
);
1213 const keyToChange
= this._getConfigurationKey(commandPayload
.key
, true);
1215 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
1216 } else if (keyToChange
&& keyToChange
.readonly) {
1217 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
1218 } else if (keyToChange
&& !keyToChange
.readonly) {
1219 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1220 let valueChanged
= false;
1221 if (this._configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
1222 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1223 valueChanged
= true;
1225 let triggerHeartbeatRestart
= false;
1226 if (keyToChange
.key
=== StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
1227 this._setConfigurationKeyValue(StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
1228 triggerHeartbeatRestart
= true;
1230 if (keyToChange
.key
=== StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
1231 this._setConfigurationKeyValue(StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
1232 triggerHeartbeatRestart
= true;
1234 if (triggerHeartbeatRestart
) {
1235 this._restartHeartbeat();
1237 if (keyToChange
.key
=== StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
1238 this._restartWebSocketPing();
1240 if (keyToChange
.reboot
) {
1241 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
1243 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
1247 handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
1248 if (!this.getConnector(commandPayload
.connectorId
)) {
1249 logger
.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`);
1250 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1252 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& !this.getConnector(commandPayload
.connectorId
)?.transactionStarted
) {
1253 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1255 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
1256 if (chargingProfile
.chargingProfileId
=== commandPayload
.csChargingProfiles
.chargingProfileId
1257 || (chargingProfile
.stackLevel
=== commandPayload
.csChargingProfiles
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.csChargingProfiles
.chargingProfilePurpose
)) {
1258 this.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = chargingProfile
;
1259 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1262 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.push(commandPayload
.csChargingProfiles
);
1263 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1266 handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): ChangeAvailabilityResponse
{
1267 const connectorId
: number = commandPayload
.connectorId
;
1268 if (!this.getConnector(connectorId
)) {
1269 logger
.error(`${this._logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
1270 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
1272 const chargePointStatus
: ChargePointStatus
= commandPayload
.type === AvailabilityType
.OPERATIVE
? ChargePointStatus
.AVAILABLE
: ChargePointStatus
.UNAVAILABLE
;
1273 if (connectorId
=== 0) {
1274 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
1275 for (const connector
in this._connectors
) {
1276 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
1277 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
1279 this.getConnector(Utils
.convertToInt(connector
)).availability
= commandPayload
.type;
1280 response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
&& this.sendStatusNotification(Utils
.convertToInt(connector
), chargePointStatus
);
1283 } else if (connectorId
> 0 && (this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
|| (this.getConnector(0).availability
=== AvailabilityType
.INOPERATIVE
&& commandPayload
.type === AvailabilityType
.INOPERATIVE
))) {
1284 if (this.getConnector(connectorId
)?.transactionStarted
) {
1285 this.getConnector(connectorId
).availability
= commandPayload
.type;
1286 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
1288 this.getConnector(connectorId
).availability
= commandPayload
.type;
1289 void this.sendStatusNotification(connectorId
, chargePointStatus
);
1290 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
1292 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
1295 async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
1296 const transactionConnectorID
: number = commandPayload
.connectorId
? commandPayload
.connectorId
: 1;
1297 if (this._isChargingStationAvailable() && this._isConnectorAvailable(transactionConnectorID
)) {
1298 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1299 // Check if authorized
1300 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1301 await this.sendStatusNotification(transactionConnectorID
, ChargePointStatus
.PREPARING
);
1302 // Authorization successful start transaction
1303 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1304 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1305 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1307 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
1308 return Constants
.OCPP_RESPONSE_REJECTED
;
1310 await this.sendStatusNotification(transactionConnectorID
, ChargePointStatus
.PREPARING
);
1311 // No local authorization check required => start transaction
1312 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1313 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1314 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1316 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED on unavailable connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
1317 return Constants
.OCPP_RESPONSE_REJECTED
;
1320 async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
1321 const transactionId
= commandPayload
.transactionId
;
1322 for (const connector
in this._connectors
) {
1323 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
))?.transactionId
=== transactionId
) {
1324 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.FINISHING
);
1325 await this.sendStopTransaction(transactionId
);
1326 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1329 logger
.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
1330 return Constants
.OCPP_RESPONSE_REJECTED
;
1333 // eslint-disable-next-line consistent-this
1334 private async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
1336 const meterValue
: MeterValue
= {
1337 timestamp
: new Date().toISOString(),
1340 const meterValuesTemplate
: SampledValue
[] = self.getConnector(connectorId
).MeterValues
;
1341 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
1342 const connector
= self.getConnector(connectorId
);
1344 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.STATE_OF_CHARGE
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.STATE_OF_CHARGE
)) {
1345 meterValue
.sampledValue
.push({
1346 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.PERCENT
},
1347 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1348 measurand
: meterValuesTemplate
[index
].measurand
,
1349 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: MeterValueLocation
.EV
},
1350 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100).toString() },
1352 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1353 if (Utils
.convertToInt(meterValue
.sampledValue
[sampledValuesIndex
].value
) > 100 || debug
) {
1354 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`);
1356 // Voltage measurand
1357 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.VOLTAGE
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.VOLTAGE
)) {
1358 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
1359 meterValue
.sampledValue
.push({
1360 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
1361 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1362 measurand
: meterValuesTemplate
[index
].measurand
,
1363 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1364 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
1366 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
1367 let phaseValue
: string;
1368 if (self._getVoltageOut() >= 0 && self._getVoltageOut() <= 250) {
1369 phaseValue
= `L${phase}-N`;
1370 } else if (self._getVoltageOut() > 250) {
1371 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
1373 meterValue
.sampledValue
.push({
1374 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
1375 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1376 measurand
: meterValuesTemplate
[index
].measurand
,
1377 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1378 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
1379 phase
: phaseValue
as MeterValuePhase
,
1382 // Power.Active.Import measurand
1383 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.POWER_ACTIVE_IMPORT
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.POWER_ACTIVE_IMPORT
)) {
1384 // FIXME: factor out powerDivider checks
1385 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
1386 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1387 logger
.error(errMsg
);
1388 throw Error(errMsg
);
1389 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
1390 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}`;
1391 logger
.error(errMsg
);
1392 throw Error(errMsg
);
1394 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`;
1395 const powerMeasurandValues
= {} as MeasurandValues
;
1396 const maxPower
= Math.round(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
);
1397 const maxPowerPerPhase
= Math.round((self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
) / self._getNumberOfPhases());
1398 switch (self._getPowerOutType()) {
1399 case PowerOutType
.AC
:
1400 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1401 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
1402 powerMeasurandValues
.L2
= 0;
1403 powerMeasurandValues
.L3
= 0;
1404 if (self._getNumberOfPhases() === 3) {
1405 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
1406 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
1408 powerMeasurandValues
.allPhases
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
1411 case PowerOutType
.DC
:
1412 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1413 powerMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxPower
);
1417 logger
.error(errMsg
);
1418 throw Error(errMsg
);
1420 meterValue
.sampledValue
.push({
1421 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
1422 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1423 measurand
: meterValuesTemplate
[index
].measurand
,
1424 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1425 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.allPhases
.toString() },
1427 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1428 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxPower
|| debug
) {
1429 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}`);
1431 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
1432 const phaseValue
= `L${phase}-N`;
1433 meterValue
.sampledValue
.push({
1434 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
1435 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1436 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1437 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1438 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] as string },
1439 phase
: phaseValue
as MeterValuePhase
,
1442 // Current.Import measurand
1443 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.CURRENT_IMPORT
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.CURRENT_IMPORT
)) {
1444 // FIXME: factor out powerDivider checks
1445 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
1446 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1447 logger
.error(errMsg
);
1448 throw Error(errMsg
);
1449 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
1450 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}`;
1451 logger
.error(errMsg
);
1452 throw Error(errMsg
);
1454 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`;
1455 const currentMeasurandValues
: MeasurandValues
= {} as MeasurandValues
;
1456 let maxAmperage
: number;
1457 switch (self._getPowerOutType()) {
1458 case PowerOutType
.AC
:
1459 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
1460 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1461 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
1462 currentMeasurandValues
.L2
= 0;
1463 currentMeasurandValues
.L3
= 0;
1464 if (self._getNumberOfPhases() === 3) {
1465 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
1466 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
1468 currentMeasurandValues
.allPhases
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
1471 case PowerOutType
.DC
:
1472 maxAmperage
= ElectricUtils
.ampTotalFromPower(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
1473 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1474 currentMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxAmperage
);
1478 logger
.error(errMsg
);
1479 throw Error(errMsg
);
1481 meterValue
.sampledValue
.push({
1482 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
1483 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1484 measurand
: meterValuesTemplate
[index
].measurand
,
1485 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1486 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.allPhases
.toString() },
1488 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1489 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxAmperage
|| debug
) {
1490 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}`);
1492 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
1493 const phaseValue
= `L${phase}`;
1494 meterValue
.sampledValue
.push({
1495 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
1496 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1497 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1498 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1499 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] as string },
1500 phase
: phaseValue
as MeterValuePhase
,
1503 // Energy.Active.Import.Register measurand (default)
1504 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
1505 // FIXME: factor out powerDivider checks
1506 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
1507 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1508 logger
.error(errMsg
);
1509 throw Error(errMsg
);
1510 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
1511 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}`;
1512 logger
.error(errMsg
);
1513 throw Error(errMsg
);
1515 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1516 const measurandValue
= Utils
.getRandomInt(self._stationInfo
.maxPower
/ (self._stationInfo
.powerDivider
* 3600000) * interval
);
1517 // Persist previous value in connector
1518 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
1519 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
1521 connector
.lastEnergyActiveImportRegisterValue
= 0;
1524 meterValue
.sampledValue
.push({
1525 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT_HOUR
},
1526 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1527 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1528 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1529 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} :
1530 { value
: connector
.lastEnergyActiveImportRegisterValue
.toString() },
1532 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1533 const maxConsumption
= Math.round(self._stationInfo
.maxPower
* 3600 / (self._stationInfo
.powerDivider
* interval
));
1534 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxConsumption
|| debug
) {
1535 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}`);
1537 // Unsupported measurand
1539 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
1542 const payload
: MeterValuesRequest
= {
1544 transactionId
: self.getConnector(connectorId
).transactionId
,
1545 meterValue
: meterValue
,
1547 await self.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.METERVALUES
);
1549 this.handleRequestError(RequestCommand
.METERVALUES
, error
);
1553 private handleRequestError(commandName
: RequestCommand
, error
: Error) {
1554 logger
.error(this._logPrefix() + ' Send ' + commandName
+ ' error: %j', error
);