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 public stationInfo
: ChargingStationInfo
;
35 public connectors
: Connectors
;
36 public statistics
: Statistics
;
37 private index
: number;
38 private stationTemplateFile
: string;
39 private bootNotificationRequest
: BootNotificationRequest
;
40 private bootNotificationResponse
: BootNotificationResponse
;
41 private configuration
: ChargingStationConfiguration
;
42 private connectorsConfigurationHash
: string;
43 private supervisionUrl
: string;
44 private wsConnectionUrl
: string;
45 private wsConnection
: WebSocket
;
46 private hasStopped
: boolean;
47 private hasSocketRestarted
: boolean;
48 private autoReconnectRetryCount
: number;
49 private requests
: Requests
;
50 private messageQueue
: string[];
51 private automaticTransactionGeneration
: AutomaticTransactionGenerator
;
52 private authorizedTags
: string[];
53 private heartbeatSetInterval
: NodeJS
.Timeout
;
54 private webSocketPingSetInterval
: NodeJS
.Timeout
;
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 _getChargingStationId(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
.chargingStationId
= this._getChargingStationId(stationTemplateFromFile
);
102 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
106 _initialize(): void {
107 this.stationInfo
= this._buildStationInfo();
108 this.bootNotificationRequest
= {
109 chargePointModel
: this.stationInfo
.chargePointModel
,
110 chargePointVendor
: this.stationInfo
.chargePointVendor
,
111 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
112 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
114 this.configuration
= this._getTemplateChargingStationConfiguration();
115 this.supervisionUrl
= this._getSupervisionURL();
116 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
117 // Build connectors if needed
118 const maxConnectors
= this._getMaxNumberOfConnectors();
119 if (maxConnectors
<= 0) {
120 logger
.warn(`${this._logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
122 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
123 if (templateMaxConnectors
<= 0) {
124 logger
.warn(`${this._logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
126 if (!this.stationInfo
.Connectors
[0]) {
127 logger
.warn(`${this._logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
130 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
131 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
132 this.stationInfo
.randomConnectors
= true;
134 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
135 // FIXME: Handle shrinking the number of connectors
136 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
137 this.connectorsConfigurationHash
= connectorsConfigHash
;
138 // Add connector Id 0
139 let lastConnector
= '0';
140 for (lastConnector
in this.stationInfo
.Connectors
) {
141 if (Utils
.convertToInt(lastConnector
) === 0 && this._getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
142 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
143 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
144 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
145 this.connectors
[lastConnector
].chargingProfiles
= [];
149 // Generate all connectors
150 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
151 for (let index
= 1; index
<= maxConnectors
; index
++) {
152 const randConnectorID
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
153 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorID
]);
154 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
155 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
156 this.connectors
[index
].chargingProfiles
= [];
161 // Avoid duplication of connectors related information
162 delete this.stationInfo
.Connectors
;
163 // Initialize transaction attributes on connectors
164 for (const connector
in this.connectors
) {
165 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
166 this._initTransactionOnConnector(Utils
.convertToInt(connector
));
170 this._addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this._getNumberOfConnectors().toString(), true);
171 if (!this._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
172 this._addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
174 this.stationInfo
.powerDivider
= this._getPowerDivider();
175 if (this.getEnableStatistics()) {
176 this.statistics
= new Statistics(this.stationInfo
.chargingStationId
);
177 this.performanceObserver
= new PerformanceObserver((list
) => {
178 const entry
= list
.getEntries()[0];
179 this.statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
180 this.performanceObserver
.disconnect();
185 _logPrefix(): string {
186 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId}:`);
189 _isWebSocketOpen(): boolean {
190 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
193 _isRegistered(): boolean {
194 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
197 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
198 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
201 _getAuthorizationFile(): string {
202 return this.stationInfo
.authorizationFile
&& this.stationInfo
.authorizationFile
;
205 _getUseConnectorId0(): boolean {
206 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
209 _loadAndGetAuthorizedTags(): string[] {
210 let authorizedTags
: string[] = [];
211 const authorizationFile
= this._getAuthorizationFile();
212 if (authorizationFile
) {
214 // Load authorization file
215 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
216 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
217 fs
.closeSync(fileDescriptor
);
219 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
223 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
225 return authorizedTags
;
228 getRandomTagId(): string {
229 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
230 return this.authorizedTags
[index
];
233 hasAuthorizedTags(): boolean {
234 return !Utils
.isEmptyArray(this.authorizedTags
);
237 getEnableStatistics(): boolean {
238 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
241 _getNumberOfPhases(): number {
242 switch (this._getPowerOutType()) {
243 case PowerOutType
.AC
:
244 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
245 case PowerOutType
.DC
:
250 _getNumberOfRunningTransactions(): number {
252 for (const connector
in this.connectors
) {
253 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
261 _getConnectionTimeout(): number {
262 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
263 return this.stationInfo
.connectionTimeout
;
265 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
266 return Configuration
.getConnectionTimeout();
271 // -1 for unlimited, 0 for disabling
272 _getAutoReconnectMaxRetries(): number {
273 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
274 return this.stationInfo
.autoReconnectMaxRetries
;
276 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
277 return Configuration
.getAutoReconnectMaxRetries();
283 _getRegistrationMaxRetries(): number {
284 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
285 return this.stationInfo
.registrationMaxRetries
;
290 _getPowerDivider(): number {
291 let powerDivider
= this._getNumberOfConnectors();
292 if (this.stationInfo
.powerSharedByConnectors
) {
293 powerDivider
= this._getNumberOfRunningTransactions();
298 getConnector(id
: number): Connector
{
299 return this.connectors
[id
];
302 _isConnectorAvailable(id
: number): boolean {
303 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
306 _isChargingStationAvailable(): boolean {
307 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
310 _getTemplateMaxNumberOfConnectors(): number {
311 return Object.keys(this.stationInfo
.Connectors
).length
;
314 _getMaxNumberOfConnectors(): number {
315 let maxConnectors
= 0;
316 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
317 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
318 // Distribute evenly the number of connectors
319 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
320 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
321 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
323 maxConnectors
= this.stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
325 return maxConnectors
;
328 _getNumberOfConnectors(): number {
329 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
332 _getVoltageOut(): number {
333 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
334 let defaultVoltageOut
: number;
335 switch (this._getPowerOutType()) {
336 case PowerOutType
.AC
:
337 defaultVoltageOut
= VoltageOut
.VOLTAGE_230
;
339 case PowerOutType
.DC
:
340 defaultVoltageOut
= VoltageOut
.VOLTAGE_400
;
343 logger
.error(errMsg
);
346 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
349 _getTransactionIdTag(transactionId
: number): string {
350 for (const connector
in this.connectors
) {
351 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
352 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
357 _getTransactionMeterStop(transactionId
: number): number {
358 for (const connector
in this.connectors
) {
359 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
360 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
365 _getPowerOutType(): PowerOutType
{
366 return !Utils
.isUndefined(this.stationInfo
.powerOutType
) ? this.stationInfo
.powerOutType
: PowerOutType
.AC
;
369 _getSupervisionURL(): string {
370 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
372 if (!Utils
.isEmptyArray(supervisionUrls
)) {
373 if (Configuration
.getDistributeStationsToTenantsEqually()) {
374 indexUrl
= this.index
% supervisionUrls
.length
;
377 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
379 return supervisionUrls
[indexUrl
];
381 return supervisionUrls
as string;
384 _getReconnectExponentialDelay(): boolean {
385 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
388 _getHeartbeatInterval(): number {
389 const HeartbeatInterval
= this._getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
390 if (HeartbeatInterval
) {
391 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
393 const HeartBeatInterval
= this._getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
394 if (HeartBeatInterval
) {
395 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
399 _getAuthorizeRemoteTxRequests(): boolean {
400 const authorizeRemoteTxRequests
= this._getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
401 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
404 _getLocalAuthListEnabled(): boolean {
405 const localAuthListEnabled
= this._getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
406 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
409 async _startMessageSequence(): Promise
<void> {
410 // Start WebSocket ping
411 this._startWebSocketPing();
413 this._startHeartbeat();
414 // Initialize connectors status
415 for (const connector
in this.connectors
) {
416 if (Utils
.convertToInt(connector
) === 0) {
418 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
419 // Send status in template at startup
420 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
421 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
422 // Send status in template after reset
423 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
424 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
425 // Send previous status at template reload
426 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
428 // Send default status
429 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
433 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
434 if (!this.automaticTransactionGeneration
) {
435 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
437 if (this.automaticTransactionGeneration
.timeToStop
) {
438 this.automaticTransactionGeneration
.start();
441 if (this.getEnableStatistics()) {
442 this.statistics
.start();
446 async _stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
447 // Stop WebSocket ping
448 this._stopWebSocketPing();
450 this._stopHeartbeat();
452 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
453 this.automaticTransactionGeneration
&&
454 !this.automaticTransactionGeneration
.timeToStop
) {
455 await this.automaticTransactionGeneration
.stop(reason
);
457 for (const connector
in this.connectors
) {
458 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
459 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
465 _startWebSocketPing(): void {
466 const webSocketPingInterval
: number = this._getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
) ? Utils
.convertToInt(this._getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
) : 0;
467 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
468 this.webSocketPingSetInterval
= setInterval(() => {
469 if (this._isWebSocketOpen()) {
470 this.wsConnection
.ping((): void => { });
472 }, webSocketPingInterval
* 1000);
473 logger
.info(this._logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
474 } else if (this.webSocketPingSetInterval
) {
475 logger
.info(this._logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
477 logger
.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
481 _stopWebSocketPing(): void {
482 if (this.webSocketPingSetInterval
) {
483 clearInterval(this.webSocketPingSetInterval
);
484 this.webSocketPingSetInterval
= null;
488 _restartWebSocketPing(): void {
489 // Stop WebSocket ping
490 this._stopWebSocketPing();
491 // Start WebSocket ping
492 this._startWebSocketPing();
495 _startHeartbeat(): void {
496 if (this._getHeartbeatInterval() && this._getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
497 this.heartbeatSetInterval
= setInterval(async () => {
498 await this.sendHeartbeat();
499 }, this._getHeartbeatInterval());
500 logger
.info(this._logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this._getHeartbeatInterval()));
501 } else if (this.heartbeatSetInterval
) {
502 logger
.info(this._logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this._getHeartbeatInterval()) + ' already started');
504 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this._getHeartbeatInterval()) : this._getHeartbeatInterval()}, not starting the heartbeat`);
508 _stopHeartbeat(): void {
509 if (this.heartbeatSetInterval
) {
510 clearInterval(this.heartbeatSetInterval
);
511 this.heartbeatSetInterval
= null;
515 _restartHeartbeat(): void {
517 this._stopHeartbeat();
519 this._startHeartbeat();
522 _startAuthorizationFileMonitoring(): void {
523 fs
.watch(this._getAuthorizationFile()).on('change', (e
) => {
525 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
526 // Initialize _authorizedTags
527 this.authorizedTags
= this._loadAndGetAuthorizedTags();
529 logger
.error(this._logPrefix() + ' Authorization file monitoring error: %j', error
);
534 _startStationTemplateFileMonitoring(): void {
535 fs
.watch(this.stationTemplateFile
).on('change', (e
) => {
537 logger
.debug(this._logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
541 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
542 this.automaticTransactionGeneration
) {
543 this.automaticTransactionGeneration
.stop().catch(() => { });
546 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
547 if (!this.automaticTransactionGeneration
) {
548 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
550 if (this.automaticTransactionGeneration
.timeToStop
) {
551 this.automaticTransactionGeneration
.start();
554 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
556 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error
);
561 _startMeterValues(connectorId
: number, interval
: number): void {
562 if (connectorId
=== 0) {
563 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
566 if (!this.getConnector(connectorId
)) {
567 logger
.error(`${this._logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
570 if (!this.getConnector(connectorId
)?.transactionStarted
) {
571 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
573 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
574 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
578 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
579 if (this.getEnableStatistics()) {
580 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
581 this.performanceObserver
.observe({
582 entryTypes
: ['function'],
584 await sendMeterValues(connectorId
, interval
, this);
586 await this.sendMeterValues(connectorId
, interval
, this);
590 logger
.error(`${this._logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
594 _openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
595 if (Utils
.isUndefined(options
)) {
596 options
= {} as WebSocket
.ClientOptions
;
598 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
599 options
.handshakeTimeout
= this._getConnectionTimeout() * 1000;
601 if (this._isWebSocketOpen() && forceCloseOpened
) {
602 this.wsConnection
.close();
604 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
, options
);
605 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
609 this._openWSConnection();
610 // Monitor authorization file
611 this._startAuthorizationFileMonitoring();
612 // Monitor station template file
613 this._startStationTemplateFileMonitoring();
614 // Handle Socket incoming messages
615 this.wsConnection
.on('message', this.onMessage
.bind(this));
616 // Handle Socket error
617 this.wsConnection
.on('error', this.onError
.bind(this));
618 // Handle Socket close
619 this.wsConnection
.on('close', this.onClose
.bind(this));
620 // Handle Socket opening connection
621 this.wsConnection
.on('open', this.onOpen
.bind(this));
622 // Handle Socket ping
623 this.wsConnection
.on('ping', this.onPing
.bind(this));
624 // Handle Socket pong
625 this.wsConnection
.on('pong', this.onPong
.bind(this));
628 async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
629 // Stop message sequence
630 await this._stopMessageSequence(reason
);
631 for (const connector
in this.connectors
) {
632 if (Utils
.convertToInt(connector
) > 0) {
633 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
636 if (this._isWebSocketOpen()) {
637 this.wsConnection
.close();
639 this.bootNotificationResponse
= null;
640 this.hasStopped
= true;
643 async _reconnect(error
): Promise
<void> {
645 this._stopHeartbeat();
646 // Stop the ATG if needed
647 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
648 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
649 this.automaticTransactionGeneration
&&
650 !this.automaticTransactionGeneration
.timeToStop
) {
651 this.automaticTransactionGeneration
.stop().catch(() => { });
653 if (this.autoReconnectRetryCount
< this._getAutoReconnectMaxRetries() || this._getAutoReconnectMaxRetries() === -1) {
654 this.autoReconnectRetryCount
++;
655 const reconnectDelay
= (this._getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this._getConnectionTimeout() * 1000);
656 logger
.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
657 await Utils
.sleep(reconnectDelay
);
658 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
659 this._openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
660 this.hasSocketRestarted
= true;
661 } else if (this._getAutoReconnectMaxRetries() !== -1) {
662 logger
.error(`${this._logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`);
666 async onOpen(): Promise
<void> {
667 logger
.info(`${this._logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
668 if (!this._isRegistered()) {
669 // Send BootNotification
670 let registrationRetryCount
= 0;
672 this.bootNotificationResponse
= await this.sendBootNotification();
673 if (!this._isRegistered()) {
674 registrationRetryCount
++;
675 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
677 } while (!this._isRegistered() && (registrationRetryCount
<= this._getRegistrationMaxRetries() || this._getRegistrationMaxRetries() === -1));
679 if (this._isRegistered()) {
680 await this._startMessageSequence();
681 if (this.hasSocketRestarted
&& this._isWebSocketOpen()) {
682 if (!Utils
.isEmptyArray(this.messageQueue
)) {
683 this.messageQueue
.forEach((message
, index
) => {
684 this.messageQueue
.splice(index
, 1);
685 this.wsConnection
.send(message
);
690 logger
.error(`${this._logPrefix()} Registration failure: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`);
692 this.autoReconnectRetryCount
= 0;
693 this.hasSocketRestarted
= false;
696 async onError(errorEvent
): Promise
<void> {
697 logger
.error(this._logPrefix() + ' Socket error: %j', errorEvent
);
698 // pragma switch (errorEvent.code) {
699 // case 'ECONNREFUSED':
700 // await this._reconnect(errorEvent);
705 async onClose(closeEvent
): Promise
<void> {
706 switch (closeEvent
) {
707 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
708 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
709 logger
.info(`${this._logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
710 this.autoReconnectRetryCount
= 0;
712 default: // Abnormal close
713 logger
.error(`${this._logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
714 await this._reconnect(closeEvent
);
720 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
724 logger
.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
727 async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
728 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
729 let responseCallback
: (payload
?: Record
<string, unknown
> | string, requestPayload
?: Record
<string, unknown
>) => void;
730 let rejectCallback
: (error
: OCPPError
) => void;
731 let requestPayload
: Record
<string, unknown
>;
735 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
737 // Check the Type of message
738 switch (messageType
) {
740 case MessageType
.CALL_MESSAGE
:
741 if (this.getEnableStatistics()) {
742 this.statistics
.addMessage(commandName
, messageType
);
745 await this.handleRequest(messageId
, commandName
, commandPayload
);
748 case MessageType
.CALL_RESULT_MESSAGE
:
750 if (Utils
.isIterable(this.requests
[messageId
])) {
751 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
753 throw new Error(`Response request for message id ${messageId} is not iterable`);
755 if (!responseCallback
) {
757 throw new Error(`Response request for unknown message id ${messageId}`);
759 delete this.requests
[messageId
];
760 responseCallback(commandName
, requestPayload
);
763 case MessageType
.CALL_ERROR_MESSAGE
:
764 if (!this.requests
[messageId
]) {
766 throw new Error(`Error request for unknown message id ${messageId}`);
768 if (Utils
.isIterable(this.requests
[messageId
])) {
769 [, rejectCallback
] = this.requests
[messageId
];
771 throw new Error(`Error request for message id ${messageId} is not iterable`);
773 delete this.requests
[messageId
];
774 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
778 errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
779 logger
.error(errMsg
);
780 throw new Error(errMsg
);
784 logger
.error('%s Incoming message %j processing error %j on request content type %j', this._logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
786 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.sendError(messageId
, error
, commandName
);
790 async sendHeartbeat(): Promise
<void> {
792 const payload
: HeartbeatRequest
= {};
793 await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.HEARTBEAT
);
795 this.handleRequestError(RequestCommand
.HEARTBEAT
, error
);
799 async sendBootNotification(): Promise
<BootNotificationResponse
> {
801 return await this.sendMessage(Utils
.generateUUID(), this.bootNotificationRequest
, MessageType
.CALL_MESSAGE
, RequestCommand
.BOOT_NOTIFICATION
) as BootNotificationResponse
;
803 this.handleRequestError(RequestCommand
.BOOT_NOTIFICATION
, error
);
807 async sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
: ChargePointErrorCode
= ChargePointErrorCode
.NO_ERROR
): Promise
<void> {
808 this.getConnector(connectorId
).status = status;
810 const payload
: StatusNotificationRequest
= {
815 await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.STATUS_NOTIFICATION
);
817 this.handleRequestError(RequestCommand
.STATUS_NOTIFICATION
, error
);
821 async sendAuthorize(idTag
?: string): Promise
<AuthorizeResponse
> {
823 const payload
: AuthorizeRequest
= {
824 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_TAGID
},
826 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.AUTHORIZE
) as AuthorizeResponse
;
828 this.handleRequestError(RequestCommand
.AUTHORIZE
, error
);
832 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<StartTransactionResponse
> {
834 const payload
: StartTransactionRequest
= {
836 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_TAGID
},
838 timestamp
: new Date().toISOString(),
840 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.START_TRANSACTION
) as StartTransactionResponse
;
842 this.handleRequestError(RequestCommand
.START_TRANSACTION
, error
);
846 async sendStopTransaction(transactionId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
847 const idTag
= this._getTransactionIdTag(transactionId
);
849 const payload
: StopTransactionRequest
= {
851 ...!Utils
.isUndefined(idTag
) && { idTag
: idTag
},
852 meterStop
: this._getTransactionMeterStop(transactionId
),
853 timestamp
: new Date().toISOString(),
854 ...reason
&& { reason
},
856 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.STOP_TRANSACTION
) as StartTransactionResponse
;
858 this.handleRequestError(RequestCommand
.STOP_TRANSACTION
, error
);
862 async sendError(messageId
: string, error
: OCPPError
, commandName
: RequestCommand
| IncomingRequestCommand
): Promise
<unknown
> {
864 return this.sendMessage(messageId
, error
, MessageType
.CALL_ERROR_MESSAGE
, commandName
);
867 async sendMessage(messageId
: string, commandParams
: any, messageType
: MessageType
= MessageType
.CALL_RESULT_MESSAGE
, commandName
: RequestCommand
| IncomingRequestCommand
): Promise
<any> {
868 // eslint-disable-next-line @typescript-eslint/no-this-alias
870 // Send a message through wsConnection
871 return new Promise((resolve
: (value
?: any | PromiseLike
<any>) => void, reject
: (reason
?: any) => void) => {
872 let messageToSend
: string;
874 switch (messageType
) {
876 case MessageType
.CALL_MESSAGE
:
878 this.requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
] as Request
;
879 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
882 case MessageType
.CALL_RESULT_MESSAGE
:
884 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
887 case MessageType
.CALL_ERROR_MESSAGE
:
888 // Build Error Message
889 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: ErrorType
.GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
892 // Check if wsConnection opened and charging station registered
893 if (this._isWebSocketOpen() && (this._isRegistered() || commandName
=== RequestCommand
.BOOT_NOTIFICATION
)) {
894 if (this.getEnableStatistics()) {
895 this.statistics
.addMessage(commandName
, messageType
);
898 this.wsConnection
.send(messageToSend
);
899 } else if (commandName
!== RequestCommand
.BOOT_NOTIFICATION
) {
901 // Handle dups in buffer
902 for (const message
of this.messageQueue
) {
904 if (messageToSend
=== message
) {
911 this.messageQueue
.push(messageToSend
);
914 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
: {}));
917 if (messageType
=== MessageType
.CALL_RESULT_MESSAGE
) {
920 } else if (messageType
=== MessageType
.CALL_ERROR_MESSAGE
) {
922 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
);
925 // Function that will receive the request's response
926 async function responseCallback(payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>): Promise
<void> {
927 if (self.getEnableStatistics()) {
928 self.statistics
.addMessage(commandName
, messageType
);
931 await self.handleResponse(commandName
as RequestCommand
, payload
, requestPayload
);
935 // Function that will receive the request's rejection
936 function rejectCallback(error
: OCPPError
): void {
937 if (self.getEnableStatistics()) {
938 self.statistics
.addMessage(commandName
, messageType
);
940 logger
.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error
, commandName
, commandParams
);
942 // eslint-disable-next-line no-empty-function
943 self.requests
[messageId
] = [() => { }, () => { }, {}]; // Properly format the request
950 async handleResponse(commandName
: RequestCommand
, payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>): Promise
<void> {
951 const responseCallbackFn
= 'handleResponse' + commandName
;
952 if (typeof this[responseCallbackFn
] === 'function') {
953 await this[responseCallbackFn
](payload
, requestPayload
);
955 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
959 handleResponseBootNotification(payload
: BootNotificationResponse
, requestPayload
: BootNotificationRequest
): void {
960 if (payload
.status === RegistrationStatus
.ACCEPTED
) {
961 this.heartbeatSetInterval
? this._restartHeartbeat() : this._startHeartbeat();
962 this._addConfigurationKey(StandardParametersKey
.HeartBeatInterval
, payload
.interval
.toString());
963 this._addConfigurationKey(StandardParametersKey
.HeartbeatInterval
, payload
.interval
.toString(), false, false);
964 this.hasStopped
&& (this.hasStopped
= false);
965 } else if (payload
.status === RegistrationStatus
.PENDING
) {
966 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
968 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
972 _initTransactionOnConnector(connectorId
: number): void {
973 this.getConnector(connectorId
).transactionStarted
= false;
974 this.getConnector(connectorId
).transactionId
= null;
975 this.getConnector(connectorId
).idTag
= null;
976 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
979 _resetTransactionOnConnector(connectorId
: number): void {
980 this._initTransactionOnConnector(connectorId
);
981 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
982 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
986 async handleResponseStartTransaction(payload
: StartTransactionResponse
, requestPayload
: StartTransactionRequest
): Promise
<void> {
987 const connectorId
= requestPayload
.connectorId
;
989 let transactionConnectorId
: number;
990 for (const connector
in this.connectors
) {
991 if (Utils
.convertToInt(connector
) > 0 && Utils
.convertToInt(connector
) === connectorId
) {
992 transactionConnectorId
= Utils
.convertToInt(connector
);
996 if (!transactionConnectorId
) {
997 logger
.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId
.toString());
1000 if (this.getConnector(connectorId
)?.transactionStarted
) {
1001 logger
.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId
.toString() + ': %j', this.getConnector(connectorId
));
1005 if (payload
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1006 this.getConnector(connectorId
).transactionStarted
= true;
1007 this.getConnector(connectorId
).transactionId
= payload
.transactionId
;
1008 this.getConnector(connectorId
).idTag
= requestPayload
.idTag
;
1009 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1010 await this.sendStatusNotification(connectorId
, ChargePointStatus
.CHARGING
);
1011 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
.toString() + ' STARTED on ' + this.stationInfo
.chargingStationId
+ '#' + connectorId
.toString() + ' for idTag ' + requestPayload
.idTag
);
1012 if (this.stationInfo
.powerSharedByConnectors
) {
1013 this.stationInfo
.powerDivider
++;
1015 const configuredMeterValueSampleInterval
= this._getConfigurationKey(StandardParametersKey
.MeterValueSampleInterval
);
1016 this._startMeterValues(connectorId
,
1017 configuredMeterValueSampleInterval
? Utils
.convertToInt(configuredMeterValueSampleInterval
.value
) * 1000 : 60000);
1019 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
.toString() + ' REJECTED with status ' + payload
?.idTagInfo
?.status + ', idTag ' + requestPayload
.idTag
);
1020 this._resetTransactionOnConnector(connectorId
);
1021 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1025 async handleResponseStopTransaction(payload
: StopTransactionResponse
, requestPayload
: StopTransactionRequest
): Promise
<void> {
1026 let transactionConnectorId
: number;
1027 for (const connector
in this.connectors
) {
1028 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
))?.transactionId
=== requestPayload
.transactionId
) {
1029 transactionConnectorId
= Utils
.convertToInt(connector
);
1033 if (!transactionConnectorId
) {
1034 logger
.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload
.transactionId
.toString());
1037 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1038 if (!this._isChargingStationAvailable() || !this._isConnectorAvailable(transactionConnectorId
)) {
1039 await this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.UNAVAILABLE
);
1041 await this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.AVAILABLE
);
1043 if (this.stationInfo
.powerSharedByConnectors
) {
1044 this.stationInfo
.powerDivider
--;
1046 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
.toString() + ' STOPPED on ' + this.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString());
1047 this._resetTransactionOnConnector(transactionConnectorId
);
1049 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
?.status);
1053 handleResponseStatusNotification(payload
: StatusNotificationRequest
, requestPayload
: StatusNotificationResponse
): void {
1054 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1057 handleResponseMeterValues(payload
: MeterValuesRequest
, requestPayload
: MeterValuesResponse
): void {
1058 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1061 handleResponseHeartbeat(payload
: HeartbeatResponse
, requestPayload
: HeartbeatRequest
): void {
1062 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1065 handleResponseAuthorize(payload
: AuthorizeResponse
, requestPayload
: AuthorizeRequest
): void {
1066 logger
.debug(this._logPrefix() + ' Authorize response received: %j to Authorize request: %j', payload
, requestPayload
);
1069 async handleRequest(messageId
: string, commandName
: IncomingRequestCommand
, commandPayload
: Record
<string, unknown
>): Promise
<void> {
1072 if (typeof this['handleRequest' + commandName
] === 'function') {
1074 // Call the method to build the response
1075 response
= await this['handleRequest' + commandName
](commandPayload
);
1078 logger
.error(this._logPrefix() + ' Handle request error: %j', error
);
1079 // Send back response to inform backend
1080 await this.sendError(messageId
, error
, commandName
);
1085 await this.sendError(messageId
, new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1086 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1089 await this.sendMessage(messageId
, response
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
1092 // Simulate charging station restart
1093 handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
1094 setImmediate(async () => {
1095 await this.stop(commandPayload
.type + 'Reset' as StopTransactionReason
);
1096 await Utils
.sleep(this.stationInfo
.resetTime
);
1099 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this.stationInfo.resetTime)}`);
1100 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1103 handleRequestClearCache(): DefaultResponse
{
1104 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1107 async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
1108 const connectorId
= commandPayload
.connectorId
;
1109 if (connectorId
=== 0) {
1110 logger
.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
1111 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
1113 if (this.getConnector(connectorId
)?.transactionStarted
) {
1114 const stopResponse
= await this.sendStopTransaction(this.getConnector(connectorId
).transactionId
, StopTransactionReason
.UNLOCK_COMMAND
);
1115 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1116 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1118 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
1120 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1121 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1124 _getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
{
1125 const configurationKey
: ConfigurationKey
= this.configuration
.configurationKey
.find((configElement
) => {
1126 if (caseInsensitive
) {
1127 return configElement
.key
.toLowerCase() === key
.toLowerCase();
1129 return configElement
.key
=== key
;
1131 return configurationKey
;
1134 _addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
1135 const keyFound
= this._getConfigurationKey(key
);
1137 this.configuration
.configurationKey
.push({
1145 logger
.error(`${this._logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
1149 _setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
1150 const keyFound
= this._getConfigurationKey(key
);
1152 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
1153 this.configuration
.configurationKey
[keyIndex
].value
= value
;
1155 logger
.error(`${this._logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
1159 handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
1160 const configurationKey
: OCPPConfigurationKey
[] = [];
1161 const unknownKey
: string[] = [];
1162 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1163 for (const configuration
of this.configuration
.configurationKey
) {
1164 if (Utils
.isUndefined(configuration
.visible
)) {
1165 configuration
.visible
= true;
1167 if (!configuration
.visible
) {
1170 configurationKey
.push({
1171 key
: configuration
.key
,
1172 readonly: configuration
.readonly,
1173 value
: configuration
.value
,
1177 for (const key
of commandPayload
.key
) {
1178 const keyFound
= this._getConfigurationKey(key
);
1180 if (Utils
.isUndefined(keyFound
.visible
)) {
1181 keyFound
.visible
= true;
1183 if (!keyFound
.visible
) {
1186 configurationKey
.push({
1188 readonly: keyFound
.readonly,
1189 value
: keyFound
.value
,
1192 unknownKey
.push(key
);
1202 handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
1203 // JSON request fields type sanity check
1204 if (!Utils
.isString(commandPayload
.key
)) {
1205 logger
.error(`${this._logPrefix()} ChangeConfiguration request key field is not a string:`, commandPayload
);
1207 if (!Utils
.isString(commandPayload
.value
)) {
1208 logger
.error(`${this._logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload
);
1210 const keyToChange
= this._getConfigurationKey(commandPayload
.key
, true);
1212 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
1213 } else if (keyToChange
&& keyToChange
.readonly) {
1214 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
1215 } else if (keyToChange
&& !keyToChange
.readonly) {
1216 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyToChange
);
1217 let valueChanged
= false;
1218 if (this.configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
1219 this.configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1220 valueChanged
= true;
1222 let triggerHeartbeatRestart
= false;
1223 if (keyToChange
.key
=== StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
1224 this._setConfigurationKeyValue(StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
1225 triggerHeartbeatRestart
= true;
1227 if (keyToChange
.key
=== StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
1228 this._setConfigurationKeyValue(StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
1229 triggerHeartbeatRestart
= true;
1231 if (triggerHeartbeatRestart
) {
1232 this._restartHeartbeat();
1234 if (keyToChange
.key
=== StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
1235 this._restartWebSocketPing();
1237 if (keyToChange
.reboot
) {
1238 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
1240 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
1244 handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
1245 if (!this.getConnector(commandPayload
.connectorId
)) {
1246 logger
.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`);
1247 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1249 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& !this.getConnector(commandPayload
.connectorId
)?.transactionStarted
) {
1250 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1252 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
1253 if (chargingProfile
.chargingProfileId
=== commandPayload
.csChargingProfiles
.chargingProfileId
1254 || (chargingProfile
.stackLevel
=== commandPayload
.csChargingProfiles
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.csChargingProfiles
.chargingProfilePurpose
)) {
1255 this.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = chargingProfile
;
1256 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1259 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.push(commandPayload
.csChargingProfiles
);
1260 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1263 handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): ChangeAvailabilityResponse
{
1264 const connectorId
: number = commandPayload
.connectorId
;
1265 if (!this.getConnector(connectorId
)) {
1266 logger
.error(`${this._logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
1267 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
1269 const chargePointStatus
: ChargePointStatus
= commandPayload
.type === AvailabilityType
.OPERATIVE
? ChargePointStatus
.AVAILABLE
: ChargePointStatus
.UNAVAILABLE
;
1270 if (connectorId
=== 0) {
1271 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
1272 for (const connector
in this.connectors
) {
1273 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
1274 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
1276 this.getConnector(Utils
.convertToInt(connector
)).availability
= commandPayload
.type;
1277 response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
&& this.sendStatusNotification(Utils
.convertToInt(connector
), chargePointStatus
);
1280 } else if (connectorId
> 0 && (this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
|| (this.getConnector(0).availability
=== AvailabilityType
.INOPERATIVE
&& commandPayload
.type === AvailabilityType
.INOPERATIVE
))) {
1281 if (this.getConnector(connectorId
)?.transactionStarted
) {
1282 this.getConnector(connectorId
).availability
= commandPayload
.type;
1283 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
1285 this.getConnector(connectorId
).availability
= commandPayload
.type;
1286 void this.sendStatusNotification(connectorId
, chargePointStatus
);
1287 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
1289 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
1292 async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
1293 const transactionConnectorID
: number = commandPayload
.connectorId
? commandPayload
.connectorId
: 1;
1294 if (this._isChargingStationAvailable() && this._isConnectorAvailable(transactionConnectorID
)) {
1295 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1296 // Check if authorized
1297 if (this.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1298 await this.sendStatusNotification(transactionConnectorID
, ChargePointStatus
.PREPARING
);
1299 // Authorization successful start transaction
1300 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1301 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this.stationInfo
.chargingStationId
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1302 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1304 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
1305 return Constants
.OCPP_RESPONSE_REJECTED
;
1307 await this.sendStatusNotification(transactionConnectorID
, ChargePointStatus
.PREPARING
);
1308 // No local authorization check required => start transaction
1309 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1310 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this.stationInfo
.chargingStationId
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1311 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1313 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED on unavailable connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
1314 return Constants
.OCPP_RESPONSE_REJECTED
;
1317 async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
1318 const transactionId
= commandPayload
.transactionId
;
1319 for (const connector
in this.connectors
) {
1320 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
))?.transactionId
=== transactionId
) {
1321 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.FINISHING
);
1322 await this.sendStopTransaction(transactionId
);
1323 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1326 logger
.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
1327 return Constants
.OCPP_RESPONSE_REJECTED
;
1330 // eslint-disable-next-line consistent-this
1331 private async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
1333 const meterValue
: MeterValue
= {
1334 timestamp
: new Date().toISOString(),
1337 const meterValuesTemplate
: SampledValue
[] = self.getConnector(connectorId
).MeterValues
;
1338 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
1339 const connector
= self.getConnector(connectorId
);
1341 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.STATE_OF_CHARGE
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.STATE_OF_CHARGE
)) {
1342 meterValue
.sampledValue
.push({
1343 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.PERCENT
},
1344 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1345 measurand
: meterValuesTemplate
[index
].measurand
,
1346 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: MeterValueLocation
.EV
},
1347 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100).toString() },
1349 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1350 if (Utils
.convertToInt(meterValue
.sampledValue
[sampledValuesIndex
].value
) > 100 || debug
) {
1351 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`);
1353 // Voltage measurand
1354 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.VOLTAGE
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.VOLTAGE
)) {
1355 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
1356 meterValue
.sampledValue
.push({
1357 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
1358 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1359 measurand
: meterValuesTemplate
[index
].measurand
,
1360 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1361 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
1363 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
1364 let phaseValue
: string;
1365 if (self._getVoltageOut() >= 0 && self._getVoltageOut() <= 250) {
1366 phaseValue
= `L${phase}-N`;
1367 } else if (self._getVoltageOut() > 250) {
1368 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
1370 meterValue
.sampledValue
.push({
1371 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
1372 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1373 measurand
: meterValuesTemplate
[index
].measurand
,
1374 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1375 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
1376 phase
: phaseValue
as MeterValuePhase
,
1379 // Power.Active.Import measurand
1380 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.POWER_ACTIVE_IMPORT
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.POWER_ACTIVE_IMPORT
)) {
1381 // FIXME: factor out powerDivider checks
1382 if (Utils
.isUndefined(self.stationInfo
.powerDivider
)) {
1383 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1384 logger
.error(errMsg
);
1385 throw Error(errMsg
);
1386 } else if (self.stationInfo
.powerDivider
&& self.stationInfo
.powerDivider
<= 0) {
1387 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}`;
1388 logger
.error(errMsg
);
1389 throw Error(errMsg
);
1391 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`;
1392 const powerMeasurandValues
= {} as MeasurandValues
;
1393 const maxPower
= Math.round(self.stationInfo
.maxPower
/ self.stationInfo
.powerDivider
);
1394 const maxPowerPerPhase
= Math.round((self.stationInfo
.maxPower
/ self.stationInfo
.powerDivider
) / self._getNumberOfPhases());
1395 switch (self._getPowerOutType()) {
1396 case PowerOutType
.AC
:
1397 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1398 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
1399 powerMeasurandValues
.L2
= 0;
1400 powerMeasurandValues
.L3
= 0;
1401 if (self._getNumberOfPhases() === 3) {
1402 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
1403 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
1405 powerMeasurandValues
.allPhases
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
1408 case PowerOutType
.DC
:
1409 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1410 powerMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxPower
);
1414 logger
.error(errMsg
);
1415 throw Error(errMsg
);
1417 meterValue
.sampledValue
.push({
1418 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
1419 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1420 measurand
: meterValuesTemplate
[index
].measurand
,
1421 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1422 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.allPhases
.toString() },
1424 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1425 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxPower
|| debug
) {
1426 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}`);
1428 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
1429 const phaseValue
= `L${phase}-N`;
1430 meterValue
.sampledValue
.push({
1431 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
1432 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1433 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1434 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1435 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] as string },
1436 phase
: phaseValue
as MeterValuePhase
,
1439 // Current.Import measurand
1440 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.CURRENT_IMPORT
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.CURRENT_IMPORT
)) {
1441 // FIXME: factor out powerDivider checks
1442 if (Utils
.isUndefined(self.stationInfo
.powerDivider
)) {
1443 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1444 logger
.error(errMsg
);
1445 throw Error(errMsg
);
1446 } else if (self.stationInfo
.powerDivider
&& self.stationInfo
.powerDivider
<= 0) {
1447 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}`;
1448 logger
.error(errMsg
);
1449 throw Error(errMsg
);
1451 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`;
1452 const currentMeasurandValues
: MeasurandValues
= {} as MeasurandValues
;
1453 let maxAmperage
: number;
1454 switch (self._getPowerOutType()) {
1455 case PowerOutType
.AC
:
1456 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self.stationInfo
.maxPower
/ self.stationInfo
.powerDivider
, self._getVoltageOut());
1457 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1458 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
1459 currentMeasurandValues
.L2
= 0;
1460 currentMeasurandValues
.L3
= 0;
1461 if (self._getNumberOfPhases() === 3) {
1462 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
1463 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
1465 currentMeasurandValues
.allPhases
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
1468 case PowerOutType
.DC
:
1469 maxAmperage
= ElectricUtils
.ampTotalFromPower(self.stationInfo
.maxPower
/ self.stationInfo
.powerDivider
, self._getVoltageOut());
1470 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1471 currentMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxAmperage
);
1475 logger
.error(errMsg
);
1476 throw Error(errMsg
);
1478 meterValue
.sampledValue
.push({
1479 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
1480 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1481 measurand
: meterValuesTemplate
[index
].measurand
,
1482 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1483 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.allPhases
.toString() },
1485 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1486 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxAmperage
|| debug
) {
1487 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}`);
1489 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
1490 const phaseValue
= `L${phase}`;
1491 meterValue
.sampledValue
.push({
1492 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
1493 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1494 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1495 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1496 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] as string },
1497 phase
: phaseValue
as MeterValuePhase
,
1500 // Energy.Active.Import.Register measurand (default)
1501 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
1502 // FIXME: factor out powerDivider checks
1503 if (Utils
.isUndefined(self.stationInfo
.powerDivider
)) {
1504 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1505 logger
.error(errMsg
);
1506 throw Error(errMsg
);
1507 } else if (self.stationInfo
.powerDivider
&& self.stationInfo
.powerDivider
<= 0) {
1508 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}`;
1509 logger
.error(errMsg
);
1510 throw Error(errMsg
);
1512 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1513 const measurandValue
= Utils
.getRandomInt(self.stationInfo
.maxPower
/ (self.stationInfo
.powerDivider
* 3600000) * interval
);
1514 // Persist previous value in connector
1515 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
1516 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
1518 connector
.lastEnergyActiveImportRegisterValue
= 0;
1521 meterValue
.sampledValue
.push({
1522 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT_HOUR
},
1523 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1524 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1525 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1526 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} :
1527 { value
: connector
.lastEnergyActiveImportRegisterValue
.toString() },
1529 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1530 const maxConsumption
= Math.round(self.stationInfo
.maxPower
* 3600 / (self.stationInfo
.powerDivider
* interval
));
1531 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxConsumption
|| debug
) {
1532 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}`);
1534 // Unsupported measurand
1536 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
1539 const payload
: MeterValuesRequest
= {
1541 transactionId
: self.getConnector(connectorId
).transactionId
,
1542 meterValue
: meterValue
,
1544 await self.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.METERVALUES
);
1546 this.handleRequestError(RequestCommand
.METERVALUES
, error
);
1550 private handleRequestError(commandName
: RequestCommand
, error
: Error) {
1551 logger
.error(this._logPrefix() + ' Send ' + commandName
+ ' error: %j', error
);