1 import { AuthorizationStatus
, StartTransactionRequest
, StartTransactionResponse
, StopTransactionReason
, StopTransactionRequest
, StopTransactionResponse
} from
'../types/ocpp/1.6/Transaction';
2 import { BootNotificationRequest
, ChangeConfigurationRequest
, GetConfigurationRequest
, HeartbeatRequest
, IncomingRequestCommand
, RemoteStartTransactionRequest
, RemoteStopTransactionRequest
, RequestCommand
, ResetRequest
, SetChargingProfileRequest
, StatusNotificationRequest
, UnlockConnectorRequest
} from
'../types/ocpp/1.6/Requests';
3 import { BootNotificationResponse
, ChangeConfigurationResponse
, DefaultResponse
, GetConfigurationResponse
, HeartbeatResponse
, RegistrationStatus
, SetChargingProfileResponse
, StatusNotificationResponse
, UnlockConnectorResponse
} from
'../types/ocpp/1.6/RequestResponses';
4 import { ChargingProfile
, ChargingProfilePurposeType
} from
'../types/ocpp/1.6/ChargingProfile';
5 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
6 import ChargingStationTemplate
, { PowerOutType
} from
'../types/ChargingStationTemplate';
7 import Connectors
, { Connector
} from
'../types/Connectors';
8 import { MeterValue
, MeterValueLocation
, MeterValueMeasurand
, MeterValuePhase
, MeterValueUnit
, MeterValuesRequest
, MeterValuesResponse
, SampledValue
} from
'../types/ocpp/1.6/MeterValues';
9 import { PerformanceObserver
, performance
} from
'perf_hooks';
10 import Requests
, { IncomingRequest
, Request
} from
'../types/ocpp/Requests';
11 import WebSocket
, { MessageEvent
} from
'ws';
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 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
.toString()).substr(('000000000' + this._index
.toString()).length
- 4);
77 _buildStationInfo(): ChargingStationInfo
{
78 let stationTemplateFromFile
: ChargingStationTemplate
;
81 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
82 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
83 fs
.closeSync(fileDescriptor
);
85 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: %j', error
);
88 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
89 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
90 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
91 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
93 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
95 stationInfo
.name
= this._getStationName(stationTemplateFromFile
);
96 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
100 get
stationInfo(): ChargingStationInfo
{
101 return this._stationInfo
;
104 _initialize(): void {
105 this._stationInfo
= this._buildStationInfo();
106 this._bootNotificationRequest
= {
107 chargePointModel
: this._stationInfo
.chargePointModel
,
108 chargePointVendor
: this._stationInfo
.chargePointVendor
,
109 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
110 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && { firmwareVersion
: this._stationInfo
.firmwareVersion
},
112 this._configuration
= this._getTemplateChargingStationConfiguration();
113 this._supervisionUrl
= this._getSupervisionURL();
114 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
115 // Build connectors if needed
116 const maxConnectors
= this._getMaxNumberOfConnectors();
117 if (maxConnectors
<= 0) {
118 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
120 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
121 if (templateMaxConnectors
<= 0) {
122 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configuration`);
124 if (!this._stationInfo
.Connectors
[0]) {
125 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector Id 0 configuration`);
128 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this._stationInfo
.randomConnectors
) {
129 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
130 this._stationInfo
.randomConnectors
= true;
132 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
133 // FIXME: Handle shrinking the number of connectors
134 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
135 this._connectorsConfigurationHash
= connectorsConfigHash
;
136 // Add connector Id 0
137 let lastConnector
= '0';
138 for (lastConnector
in this._stationInfo
.Connectors
) {
139 if (Utils
.convertToInt(lastConnector
) === 0 && this._getUseConnectorId0() && this._stationInfo
.Connectors
[lastConnector
]) {
140 this._connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this._stationInfo
.Connectors
[lastConnector
]);
143 // Generate all connectors
144 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
145 for (let index
= 1; index
<= maxConnectors
; index
++) {
146 const randConnectorID
= this._stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
147 this._connectors
[index
] = Utils
.cloneObject
<Connector
>(this._stationInfo
.Connectors
[randConnectorID
]);
151 // Avoid duplication of connectors related information
152 delete this._stationInfo
.Connectors
;
153 // Initialize transaction attributes on connectors
154 for (const connector
in this._connectors
) {
155 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
156 this._initTransactionOnConnector(Utils
.convertToInt(connector
));
160 this._addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this._getNumberOfConnectors().toString(), true);
161 if (!this._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
162 this._addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
164 this._stationInfo
.powerDivider
= this._getPowerDivider();
165 if (this.getEnableStatistics()) {
166 this._statistics
= Statistics
.getInstance();
167 this._statistics
.objName
= this._stationInfo
.name
;
168 this._performanceObserver
= new PerformanceObserver((list
) => {
169 const entry
= list
.getEntries()[0];
170 this._statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
171 this._performanceObserver
.disconnect();
176 get
connectors(): Connectors
{
177 return this._connectors
;
180 get
statistics(): Statistics
{
181 return this._statistics
;
184 _logPrefix(): string {
185 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
188 _isWebSocketOpen(): boolean {
189 return this._wsConnection
?.readyState
=== WebSocket
.OPEN
;
192 _isRegistered(): boolean {
193 return this._bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
196 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
197 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
200 _getAuthorizationFile(): string {
201 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
204 _getUseConnectorId0(): boolean {
205 return !Utils
.isUndefined(this._stationInfo
.useConnectorId0
) ? this._stationInfo
.useConnectorId0
: true;
208 _loadAndGetAuthorizedTags(): string[] {
209 let authorizedTags
: string[] = [];
210 const authorizationFile
= this._getAuthorizationFile();
211 if (authorizationFile
) {
213 // Load authorization file
214 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
215 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
216 fs
.closeSync(fileDescriptor
);
218 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
222 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
224 return authorizedTags
;
227 getRandomTagId(): string {
228 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
229 return this._authorizedTags
[index
];
232 hasAuthorizedTags(): boolean {
233 return !Utils
.isEmptyArray(this._authorizedTags
);
236 getEnableStatistics(): boolean {
237 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? this._stationInfo
.enableStatistics
: true;
240 _getNumberOfPhases(): number {
241 switch (this._getPowerOutType()) {
242 case PowerOutType
.AC
:
243 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? this._stationInfo
.numberOfPhases
: 3;
244 case PowerOutType
.DC
:
249 _getNumberOfRunningTransactions(): number {
251 for (const connector
in this._connectors
) {
252 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
260 _getConnectionTimeout(): number {
261 if (!Utils
.isUndefined(this._stationInfo
.connectionTimeout
)) {
262 return this._stationInfo
.connectionTimeout
;
264 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
265 return Configuration
.getConnectionTimeout();
270 // -1 for unlimited, 0 for disabling
271 _getAutoReconnectMaxRetries(): number {
272 if (!Utils
.isUndefined(this._stationInfo
.autoReconnectMaxRetries
)) {
273 return this._stationInfo
.autoReconnectMaxRetries
;
275 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
276 return Configuration
.getAutoReconnectMaxRetries();
282 _getRegistrationMaxRetries(): number {
283 if (!Utils
.isUndefined(this._stationInfo
.registrationMaxRetries
)) {
284 return this._stationInfo
.registrationMaxRetries
;
289 _getPowerDivider(): number {
290 let powerDivider
= this._getNumberOfConnectors();
291 if (this._stationInfo
.powerSharedByConnectors
) {
292 powerDivider
= this._getNumberOfRunningTransactions();
297 getConnector(id
: number): Connector
{
298 return this._connectors
[id
];
301 _getTemplateMaxNumberOfConnectors(): number {
302 return Object.keys(this._stationInfo
.Connectors
).length
;
305 _getMaxNumberOfConnectors(): number {
306 let maxConnectors
= 0;
307 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
308 const numberOfConnectors
= this._stationInfo
.numberOfConnectors
as number[];
309 // Distribute evenly the number of connectors
310 maxConnectors
= numberOfConnectors
[(this._index
- 1) % numberOfConnectors
.length
];
311 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
312 maxConnectors
= this._stationInfo
.numberOfConnectors
as number;
314 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
316 return maxConnectors
;
319 _getNumberOfConnectors(): number {
320 return this._connectors
[0] ? Object.keys(this._connectors
).length
- 1 : Object.keys(this._connectors
).length
;
323 _getVoltageOut(): number {
324 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
325 let defaultVoltageOut
: number;
326 switch (this._getPowerOutType()) {
327 case PowerOutType
.AC
:
328 defaultVoltageOut
= 230;
330 case PowerOutType
.DC
:
331 defaultVoltageOut
= 400;
334 logger
.error(errMsg
);
337 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? this._stationInfo
.voltageOut
: defaultVoltageOut
;
340 _getTransactionIdTag(transactionId
: number): string {
341 for (const connector
in this._connectors
) {
342 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
343 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
348 _getTransactionMeterStop(transactionId
: number): number {
349 for (const connector
in this._connectors
) {
350 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
351 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
356 _getPowerOutType(): PowerOutType
{
357 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: PowerOutType
.AC
;
360 _getSupervisionURL(): string {
361 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
363 if (!Utils
.isEmptyArray(supervisionUrls
)) {
364 if (Configuration
.getDistributeStationsToTenantsEqually()) {
365 indexUrl
= this._index
% supervisionUrls
.length
;
368 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
370 return supervisionUrls
[indexUrl
];
372 return supervisionUrls
as string;
375 _getReconnectExponentialDelay(): boolean {
376 return !Utils
.isUndefined(this._stationInfo
.reconnectExponentialDelay
) ? this._stationInfo
.reconnectExponentialDelay
: false;
379 _getHeartbeatInterval(): number {
380 const HeartbeatInterval
= this._getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
381 if (HeartbeatInterval
) {
382 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
384 const HeartBeatInterval
= this._getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
385 if (HeartBeatInterval
) {
386 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
391 _getAuthorizeRemoteTxRequests(): boolean {
392 const authorizeRemoteTxRequests
= this._getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
393 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
396 _getLocalAuthListEnabled(): boolean {
397 const localAuthListEnabled
= this._getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
398 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
401 async _startMessageSequence(): Promise
<void> {
402 // Start WebSocket ping
403 this._startWebSocketPing();
405 this._startHeartbeat();
406 // Initialize connectors status
407 for (const connector
in this._connectors
) {
408 if (Utils
.convertToInt(connector
) === 0) {
410 } else if (!this._hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
)).status && this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
411 // Send status in template at startup
412 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
413 } else if (this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
414 // Send status in template after reset
415 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
416 } else if (!this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
)).status) {
417 // Send previous status at template reload
418 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
420 // Send default status
421 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
425 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
) {
426 if (!this._automaticTransactionGeneration
) {
427 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
429 if (this._automaticTransactionGeneration
.timeToStop
) {
430 this._automaticTransactionGeneration
.start();
433 if (this.getEnableStatistics()) {
434 this._statistics
.start();
438 async _stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
439 // Stop WebSocket ping
440 this._stopWebSocketPing();
442 this._stopHeartbeat();
444 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
445 this._automaticTransactionGeneration
&&
446 !this._automaticTransactionGeneration
.timeToStop
) {
447 await this._automaticTransactionGeneration
.stop(reason
);
449 for (const connector
in this._connectors
) {
450 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
451 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
457 _startWebSocketPing(): void {
458 const webSocketPingInterval
: number = this._getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
) ? Utils
.convertToInt(this._getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
) : 0;
459 if (webSocketPingInterval
> 0 && !this._webSocketPingSetInterval
) {
460 this._webSocketPingSetInterval
= setInterval(() => {
461 if (this._isWebSocketOpen()) {
462 this._wsConnection
.ping((): void => { });
464 }, webSocketPingInterval
* 1000);
465 logger
.info(this._logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
466 } else if (this._webSocketPingSetInterval
) {
467 logger
.info(this._logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
469 logger
.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
473 _stopWebSocketPing(): void {
474 if (this._webSocketPingSetInterval
) {
475 clearInterval(this._webSocketPingSetInterval
);
476 this._webSocketPingSetInterval
= null;
480 _restartWebSocketPing(): void {
481 // Stop WebSocket ping
482 this._stopWebSocketPing();
483 // Start WebSocket ping
484 this._startWebSocketPing();
487 _startHeartbeat(): void {
488 if (this._getHeartbeatInterval() && this._getHeartbeatInterval() > 0 && !this._heartbeatSetInterval
) {
489 this._heartbeatSetInterval
= setInterval(async () => {
490 await this.sendHeartbeat();
491 }, this._getHeartbeatInterval());
492 logger
.info(this._logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this._getHeartbeatInterval()));
493 } else if (this._heartbeatSetInterval
) {
494 logger
.info(this._logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this._getHeartbeatInterval()) + ' already started');
496 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this._getHeartbeatInterval()) : this._getHeartbeatInterval()}, not starting the heartbeat`);
500 _stopHeartbeat(): void {
501 if (this._heartbeatSetInterval
) {
502 clearInterval(this._heartbeatSetInterval
);
503 this._heartbeatSetInterval
= null;
507 _restartHeartbeat(): void {
509 this._stopHeartbeat();
511 this._startHeartbeat();
514 _startAuthorizationFileMonitoring(): void {
515 // eslint-disable-next-line @typescript-eslint/no-unused-vars
516 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
518 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
519 // Initialize _authorizedTags
520 this._authorizedTags
= this._loadAndGetAuthorizedTags();
522 logger
.error(this._logPrefix() + ' Authorization file monitoring error: %j', error
);
527 _startStationTemplateFileMonitoring(): void {
528 // eslint-disable-next-line @typescript-eslint/no-unused-vars
529 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
531 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
534 if (!this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
535 this._automaticTransactionGeneration
) {
536 this._automaticTransactionGeneration
.stop().catch(() => { });
538 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
540 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error
);
545 _startMeterValues(connectorId
: number, interval
: number): void {
546 if (!this.getConnector(connectorId
).transactionStarted
) {
547 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
549 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
550 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
554 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
555 if (this.getEnableStatistics()) {
556 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
557 this._performanceObserver
.observe({
558 entryTypes
: ['function'],
560 await sendMeterValues(connectorId
, interval
, this);
562 await this.sendMeterValues(connectorId
, interval
, this);
566 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
570 _openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
571 if (Utils
.isUndefined(options
)) {
572 options
= {} as WebSocket
.ClientOptions
;
574 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
575 options
.handshakeTimeout
= this._getConnectionTimeout() * 1000;
577 if (this._isWebSocketOpen() && forceCloseOpened
) {
578 this._wsConnection
.close();
580 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
, options
);
581 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
585 this._openWSConnection();
586 // Monitor authorization file
587 this._startAuthorizationFileMonitoring();
588 // Monitor station template file
589 this._startStationTemplateFileMonitoring();
590 // Handle Socket incoming messages
591 this._wsConnection
.on('message', this.onMessage
.bind(this));
592 // Handle Socket error
593 this._wsConnection
.on('error', this.onError
.bind(this));
594 // Handle Socket close
595 this._wsConnection
.on('close', this.onClose
.bind(this));
596 // Handle Socket opening connection
597 this._wsConnection
.on('open', this.onOpen
.bind(this));
598 // Handle Socket ping
599 this._wsConnection
.on('ping', this.onPing
.bind(this));
600 // Handle Socket pong
601 this._wsConnection
.on('pong', this.onPong
.bind(this));
604 async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
605 // Stop message sequence
606 await this._stopMessageSequence(reason
);
607 for (const connector
in this._connectors
) {
608 if (Utils
.convertToInt(connector
) > 0) {
609 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
612 if (this._isWebSocketOpen()) {
613 this._wsConnection
.close();
615 this._bootNotificationResponse
= null;
616 this._hasStopped
= true;
619 async _reconnect(error
): Promise
<void> {
621 this._stopHeartbeat();
622 // Stop the ATG if needed
623 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
624 this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
625 this._automaticTransactionGeneration
&&
626 !this._automaticTransactionGeneration
.timeToStop
) {
627 this._automaticTransactionGeneration
.stop().catch(() => { });
629 if (this._autoReconnectRetryCount
< this._getAutoReconnectMaxRetries() || this._getAutoReconnectMaxRetries() === -1) {
630 this._autoReconnectRetryCount
++;
631 const reconnectDelay
= (this._getReconnectExponentialDelay() ? Utils
.exponentialDelay(this._autoReconnectRetryCount
) : this._getConnectionTimeout() * 1000);
632 logger
.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
633 await Utils
.sleep(reconnectDelay
);
634 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
.toString());
635 this._openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
636 this._hasSocketRestarted
= true;
637 } else if (this._getAutoReconnectMaxRetries() !== -1) {
638 logger
.error(`${this._logPrefix()} Socket reconnect failure: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`);
642 async onOpen(): Promise
<void> {
643 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
644 if (!this._isRegistered()) {
645 // Send BootNotification
646 let registrationRetryCount
= 0;
648 this._bootNotificationResponse
= await this.sendBootNotification();
649 if (!this._isRegistered()) {
650 registrationRetryCount
++;
651 await Utils
.sleep(this._bootNotificationResponse
.interval
* 1000);
653 } while (!this._isRegistered() && (registrationRetryCount
<= this._getRegistrationMaxRetries() || this._getRegistrationMaxRetries() === -1));
655 if (this._isRegistered()) {
656 await this._startMessageSequence();
657 if (this._hasSocketRestarted
&& this._isWebSocketOpen()) {
658 if (!Utils
.isEmptyArray(this._messageQueue
)) {
659 this._messageQueue
.forEach((message
, index
) => {
660 this._messageQueue
.splice(index
, 1);
661 this._wsConnection
.send(message
);
666 logger
.error(`${this._logPrefix()} Registration failure: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`);
668 this._autoReconnectRetryCount
= 0;
669 this._hasSocketRestarted
= false;
672 async onError(errorEvent
): Promise
<void> {
673 logger
.error(this._logPrefix() + ' Socket error: %j', errorEvent
);
674 // pragma switch (errorEvent.code) {
675 // case 'ECONNREFUSED':
676 // await this._reconnect(errorEvent);
681 async onClose(closeEvent
): Promise
<void> {
682 switch (closeEvent
) {
683 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
684 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
685 logger
.info(`${this._logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
686 this._autoReconnectRetryCount
= 0;
688 default: // Abnormal close
689 logger
.error(`${this._logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
690 await this._reconnect(closeEvent
);
696 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
700 logger
.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
703 async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
704 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, '', ''];
705 let responseCallback
: (payload
?, requestPayload
?) => void;
706 let rejectCallback
: (error
: OCPPError
) => void;
707 let requestPayload
: Record
<string, unknown
>;
711 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
713 // Check the Type of message
714 switch (messageType
) {
716 case MessageType
.CALL_MESSAGE
:
717 if (this.getEnableStatistics()) {
718 this._statistics
.addMessage(commandName
, messageType
);
721 await this.handleRequest(messageId
, commandName
, commandPayload
);
724 case MessageType
.CALL_RESULT_MESSAGE
:
726 if (Utils
.isIterable(this._requests
[messageId
])) {
727 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
729 throw new Error(`Response request for message id ${messageId} is not iterable`);
731 if (!responseCallback
) {
733 throw new Error(`Response request for unknown message id ${messageId}`);
735 delete this._requests
[messageId
];
736 responseCallback(commandName
, requestPayload
);
739 case MessageType
.CALL_ERROR_MESSAGE
:
740 if (!this._requests
[messageId
]) {
742 throw new Error(`Error request for unknown message id ${messageId}`);
744 if (Utils
.isIterable(this._requests
[messageId
])) {
745 [, rejectCallback
] = this._requests
[messageId
];
747 throw new Error(`Error request for message id ${messageId} is not iterable`);
749 delete this._requests
[messageId
];
750 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
754 errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
755 logger
.error(errMsg
);
756 throw new Error(errMsg
);
760 logger
.error('%s Incoming message %j processing error %j on request content type %j', this._logPrefix(), messageEvent
, error
, this._requests
[messageId
]);
762 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.sendError(messageId
, error
, commandName
);
766 async sendHeartbeat(): Promise
<void> {
768 const payload
: HeartbeatRequest
= {};
769 await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.HEARTBEAT
);
771 this.handleRequestError(RequestCommand
.HEARTBEAT
, error
);
775 async sendBootNotification(): Promise
<BootNotificationResponse
> {
777 return await this.sendMessage(Utils
.generateUUID(), this._bootNotificationRequest
, MessageType
.CALL_MESSAGE
, RequestCommand
.BOOT_NOTIFICATION
) as BootNotificationResponse
;
779 this.handleRequestError(RequestCommand
.BOOT_NOTIFICATION
, error
);
783 async sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
: ChargePointErrorCode
= ChargePointErrorCode
.NO_ERROR
): Promise
<void> {
784 this.getConnector(connectorId
).status = status;
786 const payload
: StatusNotificationRequest
= {
791 await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.STATUS_NOTIFICATION
);
793 this.handleRequestError(RequestCommand
.STATUS_NOTIFICATION
, error
);
797 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<StartTransactionResponse
> {
799 const payload
: StartTransactionRequest
= {
801 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_IDTAG
},
803 timestamp
: new Date().toISOString(),
805 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.START_TRANSACTION
) as StartTransactionResponse
;
807 this.handleRequestError(RequestCommand
.START_TRANSACTION
, error
);
811 async sendStopTransaction(transactionId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
812 const idTag
= this._getTransactionIdTag(transactionId
);
814 const payload
: StopTransactionRequest
= {
816 ...!Utils
.isUndefined(idTag
) && { idTag
: idTag
},
817 meterStop
: this._getTransactionMeterStop(transactionId
),
818 timestamp
: new Date().toISOString(),
819 ...reason
&& { reason
},
821 return await this.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.STOP_TRANSACTION
) as StartTransactionResponse
;
823 this.handleRequestError(RequestCommand
.STOP_TRANSACTION
, error
);
827 // eslint-disable-next-line consistent-this
828 async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
830 const meterValue
: MeterValue
= {
831 timestamp
: new Date().toISOString(),
834 const meterValuesTemplate
: SampledValue
[] = self.getConnector(connectorId
).MeterValues
;
835 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
836 const connector
= self.getConnector(connectorId
);
838 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.STATE_OF_CHARGE
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.STATE_OF_CHARGE
)) {
839 meterValue
.sampledValue
.push({
840 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.PERCENT
},
841 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
842 measurand
: meterValuesTemplate
[index
].measurand
,
843 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: MeterValueLocation
.EV
},
844 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100).toString() },
846 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
847 if (Utils
.convertToInt(meterValue
.sampledValue
[sampledValuesIndex
].value
) > 100 || debug
) {
848 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/100`);
851 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.VOLTAGE
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.VOLTAGE
)) {
852 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
853 meterValue
.sampledValue
.push({
854 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
855 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
856 measurand
: meterValuesTemplate
[index
].measurand
,
857 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
858 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
860 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
861 let phaseValue
: string;
862 if (self._getVoltageOut() >= 0 && self._getVoltageOut() <= 250) {
863 phaseValue
= `L${phase}-N`;
864 } else if (self._getVoltageOut() > 250) {
865 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
867 meterValue
.sampledValue
.push({
868 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
869 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
870 measurand
: meterValuesTemplate
[index
].measurand
,
871 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
872 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
873 phase
: phaseValue
as MeterValuePhase
,
876 // Power.Active.Import measurand
877 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.POWER_ACTIVE_IMPORT
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.POWER_ACTIVE_IMPORT
)) {
878 // FIXME: factor out powerDivider checks
879 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
880 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
881 logger
.error(errMsg
);
883 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
884 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
885 logger
.error(errMsg
);
888 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
889 const powerMeasurandValues
= {} as MeasurandValues
;
890 const maxPower
= Math.round(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
);
891 const maxPowerPerPhase
= Math.round((self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
) / self._getNumberOfPhases());
892 switch (self._getPowerOutType()) {
893 case PowerOutType
.AC
:
894 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
895 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
896 powerMeasurandValues
.L2
= 0;
897 powerMeasurandValues
.L3
= 0;
898 if (self._getNumberOfPhases() === 3) {
899 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
900 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
902 powerMeasurandValues
.allPhases
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
905 case PowerOutType
.DC
:
906 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
907 powerMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxPower
);
911 logger
.error(errMsg
);
914 meterValue
.sampledValue
.push({
915 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
916 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
917 measurand
: meterValuesTemplate
[index
].measurand
,
918 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
919 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.allPhases
.toString() },
921 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
922 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxPower
|| debug
) {
923 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxPower}`);
925 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
926 const phaseValue
= `L${phase}-N`;
927 meterValue
.sampledValue
.push({
928 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
929 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
930 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
931 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
932 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] as string },
933 phase
: phaseValue
as MeterValuePhase
,
936 // Current.Import measurand
937 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.CURRENT_IMPORT
&& self._getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(MeterValueMeasurand
.CURRENT_IMPORT
)) {
938 // FIXME: factor out powerDivider checks
939 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
940 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
941 logger
.error(errMsg
);
943 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
944 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
945 logger
.error(errMsg
);
948 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
949 const currentMeasurandValues
: MeasurandValues
= {} as MeasurandValues
;
950 let maxAmperage
: number;
951 switch (self._getPowerOutType()) {
952 case PowerOutType
.AC
:
953 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
954 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
955 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
956 currentMeasurandValues
.L2
= 0;
957 currentMeasurandValues
.L3
= 0;
958 if (self._getNumberOfPhases() === 3) {
959 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
960 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
962 currentMeasurandValues
.allPhases
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
965 case PowerOutType
.DC
:
966 maxAmperage
= ElectricUtils
.ampTotalFromPower(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
967 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
968 currentMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxAmperage
);
972 logger
.error(errMsg
);
975 meterValue
.sampledValue
.push({
976 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
977 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
978 measurand
: meterValuesTemplate
[index
].measurand
,
979 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
980 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.allPhases
.toString() },
982 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
983 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxAmperage
|| debug
) {
984 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxAmperage}`);
986 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
987 const phaseValue
= `L${phase}`;
988 meterValue
.sampledValue
.push({
989 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
990 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
991 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
992 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
993 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] as string },
994 phase
: phaseValue
as MeterValuePhase
,
997 // Energy.Active.Import.Register measurand (default)
998 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
999 // FIXME: factor out powerDivider checks
1000 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
1001 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
1002 logger
.error(errMsg
);
1003 throw Error(errMsg
);
1004 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
1005 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
1006 logger
.error(errMsg
);
1007 throw Error(errMsg
);
1009 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
1010 const measurandValue
= Utils
.getRandomInt(self._stationInfo
.maxPower
/ (self._stationInfo
.powerDivider
* 3600000) * interval
);
1011 // Persist previous value in connector
1012 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
1013 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
1015 connector
.lastEnergyActiveImportRegisterValue
= 0;
1018 meterValue
.sampledValue
.push({
1019 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT_HOUR
},
1020 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
1021 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
1022 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
1023 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} :
1024 { value
: connector
.lastEnergyActiveImportRegisterValue
.toString() },
1026 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1027 const maxConsumption
= Math.round(self._stationInfo
.maxPower
* 3600 / (self._stationInfo
.powerDivider
* interval
));
1028 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxConsumption
|| debug
) {
1029 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxConsumption}`);
1031 // Unsupported measurand
1033 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
1036 const payload
: MeterValuesRequest
= {
1038 transactionId
: self.getConnector(connectorId
).transactionId
,
1039 meterValue
: meterValue
,
1041 await self.sendMessage(Utils
.generateUUID(), payload
, MessageType
.CALL_MESSAGE
, RequestCommand
.METERVALUES
);
1043 this.handleRequestError(RequestCommand
.METERVALUES
, error
);
1047 async sendError(messageId
: string, err
: Error | OCPPError
, commandName
: RequestCommand
| IncomingRequestCommand
): Promise
<unknown
> {
1048 // Check exception type: only OCPP error are accepted
1049 const error
= err
instanceof OCPPError
? err
: new OCPPError(ErrorType
.INTERNAL_ERROR
, err
.message
, err
.stack
&& err
.stack
);
1051 return this.sendMessage(messageId
, error
, MessageType
.CALL_ERROR_MESSAGE
, commandName
);
1054 async sendMessage(messageId
: string, commandParams
, messageType
: MessageType
= MessageType
.CALL_RESULT_MESSAGE
, commandName
: RequestCommand
| IncomingRequestCommand
): Promise
<any> {
1055 // eslint-disable-next-line @typescript-eslint/no-this-alias
1057 // Send a message through wsConnection
1058 return new Promise((resolve
: (value
?: any | PromiseLike
<any>) => void, reject
: (reason
?: any) => void) => {
1059 let messageToSend
: string;
1061 switch (messageType
) {
1063 case MessageType
.CALL_MESSAGE
:
1065 this._requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
] as Request
;
1066 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
1069 case MessageType
.CALL_RESULT_MESSAGE
:
1071 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
1074 case MessageType
.CALL_ERROR_MESSAGE
:
1075 // Build Error Message
1076 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: ErrorType
.GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
1079 // Check if wsConnection opened and charging station registered
1080 if (this._isWebSocketOpen() && (this._isRegistered() || commandName
=== RequestCommand
.BOOT_NOTIFICATION
)) {
1081 if (this.getEnableStatistics()) {
1082 this._statistics
.addMessage(commandName
, messageType
);
1084 // Yes: Send Message
1085 this._wsConnection
.send(messageToSend
);
1088 // Handle dups in buffer
1089 for (const message
of this._messageQueue
) {
1091 if (messageToSend
=== message
) {
1098 this._messageQueue
.push(messageToSend
);
1101 return rejectCallback(new OCPPError(commandParams
.code
? commandParams
.code
: ErrorType
.GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams
.details
? commandParams
.details
: {}));
1104 if (messageType
=== MessageType
.CALL_RESULT_MESSAGE
) {
1107 } else if (messageType
=== MessageType
.CALL_ERROR_MESSAGE
) {
1109 setTimeout(() => rejectCallback(new OCPPError(commandParams
.code
? commandParams
.code
: ErrorType
.GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams
.details
? commandParams
.details
: {})), Constants
.OCPP_ERROR_TIMEOUT
);
1112 // Function that will receive the request's response
1113 async function responseCallback(payload
, requestPayload
): Promise
<void> {
1114 if (self.getEnableStatistics()) {
1115 self._statistics
.addMessage(commandName
, messageType
);
1117 // Send the response
1118 await self.handleResponse(commandName
as RequestCommand
, payload
, requestPayload
);
1122 // Function that will receive the request's rejection
1123 function rejectCallback(error
: OCPPError
): void {
1124 if (self.getEnableStatistics()) {
1125 self._statistics
.addMessage(commandName
, messageType
);
1127 logger
.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error
, commandName
, commandParams
);
1129 // eslint-disable-next-line no-empty-function
1130 self._requests
[messageId
] = [() => { }, () => { }, {}]; // Properly format the request
1137 async handleResponse(commandName
: RequestCommand
, payload
, requestPayload
): Promise
<void> {
1138 const responseCallbackFn
= 'handleResponse' + commandName
;
1139 if (typeof this[responseCallbackFn
] === 'function') {
1140 await this[responseCallbackFn
](payload
, requestPayload
);
1142 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
1146 handleResponseBootNotification(payload
: BootNotificationResponse
, requestPayload
: BootNotificationRequest
): void {
1147 if (payload
.status === RegistrationStatus
.ACCEPTED
) {
1148 this._heartbeatSetInterval
? this._restartHeartbeat() : this._startHeartbeat();
1149 this._addConfigurationKey(StandardParametersKey
.HeartBeatInterval
, payload
.interval
.toString());
1150 this._addConfigurationKey(StandardParametersKey
.HeartbeatInterval
, payload
.interval
.toString(), false, false);
1151 this._hasStopped
&& (this._hasStopped
= false);
1152 } else if (payload
.status === RegistrationStatus
.PENDING
) {
1153 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
1155 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
1159 _initTransactionOnConnector(connectorId
: number): void {
1160 this.getConnector(connectorId
).transactionStarted
= false;
1161 this.getConnector(connectorId
).transactionId
= null;
1162 this.getConnector(connectorId
).idTag
= null;
1163 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
1166 _resetTransactionOnConnector(connectorId
: number): void {
1167 this._initTransactionOnConnector(connectorId
);
1168 if (this.getConnector(connectorId
).transactionSetInterval
) {
1169 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
1173 async handleResponseStartTransaction(payload
: StartTransactionResponse
, requestPayload
: StartTransactionRequest
): Promise
<void> {
1174 const connectorId
= requestPayload
.connectorId
;
1175 if (this.getConnector(connectorId
).transactionStarted
) {
1176 logger
.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId
.toString() + ': %j', this.getConnector(connectorId
));
1180 let transactionConnectorId
: number;
1181 for (const connector
in this._connectors
) {
1182 if (Utils
.convertToInt(connector
) > 0 && Utils
.convertToInt(connector
) === connectorId
) {
1183 transactionConnectorId
= Utils
.convertToInt(connector
);
1187 if (!transactionConnectorId
) {
1188 logger
.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId
.toString());
1191 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1192 this.getConnector(connectorId
).transactionStarted
= true;
1193 this.getConnector(connectorId
).transactionId
= payload
.transactionId
;
1194 this.getConnector(connectorId
).idTag
= requestPayload
.idTag
;
1195 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1196 await this.sendStatusNotification(connectorId
, ChargePointStatus
.CHARGING
);
1197 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
.toString() + ' STARTED on ' + this._stationInfo
.name
+ '#' + connectorId
.toString() + ' for idTag ' + requestPayload
.idTag
);
1198 if (this._stationInfo
.powerSharedByConnectors
) {
1199 this._stationInfo
.powerDivider
++;
1201 const configuredMeterValueSampleInterval
= this._getConfigurationKey(StandardParametersKey
.MeterValueSampleInterval
);
1202 this._startMeterValues(connectorId
,
1203 configuredMeterValueSampleInterval
? Utils
.convertToInt(configuredMeterValueSampleInterval
.value
) * 1000 : 60000);
1205 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
.status + ', idTag ' + requestPayload
.idTag
);
1206 this._resetTransactionOnConnector(connectorId
);
1207 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1211 async handleResponseStopTransaction(payload
: StopTransactionResponse
, requestPayload
: StopTransactionRequest
): Promise
<void> {
1212 let transactionConnectorId
: number;
1213 for (const connector
in this._connectors
) {
1214 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== requestPayload
.transactionId
) {
1215 transactionConnectorId
= Utils
.convertToInt(connector
);
1219 if (!transactionConnectorId
) {
1220 logger
.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload
.transactionId
.toString());
1223 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1224 await this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.AVAILABLE
);
1225 if (this._stationInfo
.powerSharedByConnectors
) {
1226 this._stationInfo
.powerDivider
--;
1228 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
.toString() + ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
.toString());
1229 this._resetTransactionOnConnector(transactionConnectorId
);
1231 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
?.status);
1235 handleResponseStatusNotification(payload
: StatusNotificationRequest
, requestPayload
: StatusNotificationResponse
): void {
1236 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1239 handleResponseMeterValues(payload
: MeterValuesRequest
, requestPayload
: MeterValuesResponse
): void {
1240 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1243 handleResponseHeartbeat(payload
: HeartbeatResponse
, requestPayload
: HeartbeatRequest
): void {
1244 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1247 async handleRequest(messageId
: string, commandName
: IncomingRequestCommand
, commandPayload
): Promise
<void> {
1250 if (typeof this['handleRequest' + commandName
] === 'function') {
1252 // Call the method to build the response
1253 response
= await this['handleRequest' + commandName
](commandPayload
);
1256 logger
.error(this._logPrefix() + ' Handle request error: %j', error
);
1257 // Send back response to inform backend
1258 await this.sendError(messageId
, error
, commandName
);
1263 await this.sendError(messageId
, new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1264 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1267 await this.sendMessage(messageId
, response
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
1270 // Simulate charging station restart
1271 handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
1272 setImmediate(async () => {
1273 await this.stop(commandPayload
.type + 'Reset' as StopTransactionReason
);
1274 await Utils
.sleep(this._stationInfo
.resetTime
);
1277 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`);
1278 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1281 handleRequestClearCache(): DefaultResponse
{
1282 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1285 async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
1286 const connectorId
= commandPayload
.connectorId
;
1287 if (connectorId
=== 0) {
1288 logger
.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
1289 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
1291 if (this.getConnector(connectorId
).transactionStarted
) {
1292 const stopResponse
= await this.sendStopTransaction(this.getConnector(connectorId
).transactionId
, StopTransactionReason
.UNLOCK_COMMAND
);
1293 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1294 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1296 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
1298 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1299 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1302 _getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
{
1303 const configurationKey
: ConfigurationKey
= this._configuration
.configurationKey
.find((configElement
) => {
1304 if (caseInsensitive
) {
1305 return configElement
.key
.toLowerCase() === key
.toLowerCase();
1307 return configElement
.key
=== key
;
1309 if (configurationKey
&& Utils
.isUndefined(configurationKey
.readonly)) {
1310 configurationKey
.readonly = false;
1312 return configurationKey
;
1315 _addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
1316 const keyFound
= this._getConfigurationKey(key
);
1318 this._configuration
.configurationKey
.push({
1326 logger
.error(`${this._logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
1330 _setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
1331 const keyFound
= this._getConfigurationKey(key
);
1333 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1334 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1336 logger
.error(`${this._logPrefix()} Trying to set a value on a non existing configuration key: %j`, keyFound
);
1340 handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
1341 const configurationKey
: OCPPConfigurationKey
[] = [];
1342 const unknownKey
: string[] = [];
1343 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1344 for (const configuration
of this._configuration
.configurationKey
) {
1345 if (Utils
.isUndefined(configuration
.visible
)) {
1346 configuration
.visible
= true;
1348 if (!configuration
.visible
) {
1351 configurationKey
.push({
1352 key
: configuration
.key
,
1353 readonly: configuration
.readonly,
1354 value
: configuration
.value
,
1358 for (const key
of commandPayload
.key
) {
1359 const keyFound
= this._getConfigurationKey(key
);
1361 if (Utils
.isUndefined(keyFound
.visible
)) {
1362 keyFound
.visible
= true;
1364 if (!keyFound
.visible
) {
1367 configurationKey
.push({
1369 readonly: keyFound
.readonly,
1370 value
: keyFound
.value
,
1373 unknownKey
.push(key
);
1383 handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
1384 // JSON request fields type sanity check
1385 if (!Utils
.isString(commandPayload
.key
)) {
1386 logger
.error(`${this._logPrefix()} ChangeConfiguration request key field is not a string:`, commandPayload
);
1388 if (!Utils
.isString(commandPayload
.value
)) {
1389 logger
.error(`${this._logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload
);
1391 const keyToChange
= this._getConfigurationKey(commandPayload
.key
, true);
1393 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
1394 } else if (keyToChange
&& keyToChange
.readonly) {
1395 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
1396 } else if (keyToChange
&& !keyToChange
.readonly) {
1397 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1398 let valueChanged
= false;
1399 if (this._configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
1400 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1401 valueChanged
= true;
1403 let triggerHeartbeatRestart
= false;
1404 if (keyToChange
.key
=== StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
1405 this._setConfigurationKeyValue(StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
1406 triggerHeartbeatRestart
= true;
1408 if (keyToChange
.key
=== StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
1409 this._setConfigurationKeyValue(StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
1410 triggerHeartbeatRestart
= true;
1412 if (triggerHeartbeatRestart
) {
1413 this._restartHeartbeat();
1415 if (keyToChange
.key
=== StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
1416 this._restartWebSocketPing();
1418 if (keyToChange
.reboot
) {
1419 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
1421 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
1425 handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
1426 if (!this.getConnector(commandPayload
.connectorId
)) {
1427 logger
.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`);
1428 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1430 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& !this.getConnector(commandPayload
.connectorId
)?.transactionStarted
) {
1431 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1433 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
1434 if (chargingProfile
.chargingProfileId
=== commandPayload
.csChargingProfiles
.chargingProfileId
1435 || (chargingProfile
.stackLevel
=== commandPayload
.csChargingProfiles
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.csChargingProfiles
.chargingProfilePurpose
)) {
1436 this.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = chargingProfile
;
1437 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1440 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.push(commandPayload
.csChargingProfiles
);
1441 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1444 async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
1445 const transactionConnectorID
: number = commandPayload
.connectorId
? commandPayload
.connectorId
: 1;
1446 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1447 // Check if authorized
1448 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1449 // Authorization successful start transaction
1450 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1451 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1452 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1454 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED, idTag ' + commandPayload
.idTag
);
1455 return Constants
.OCPP_RESPONSE_REJECTED
;
1457 // No local authorization check required => start transaction
1458 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1459 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1460 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1463 async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
1464 const transactionId
= commandPayload
.transactionId
;
1465 for (const connector
in this._connectors
) {
1466 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
1467 await this.sendStopTransaction(transactionId
);
1468 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1471 logger
.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
1472 return Constants
.OCPP_RESPONSE_REJECTED
;
1475 private handleRequestError(commandName
: RequestCommand
, error
: Error) {
1476 logger
.error(this._logPrefix() + ' Send ' + commandName
+ ' error: %j', error
);