1 import { AuthorizationStatus
, StartTransactionRequest
, StartTransactionResponse
, StopTransactionReason
, StopTransactionRequest
, StopTransactionResponse
} from
'../types/ocpp/1.6/Transaction';
2 import { BootNotificationResponse
, ChangeConfigurationResponse
, DefaultResponse
, GetConfigurationResponse
, HeartbeatResponse
, RegistrationStatus
, SetChargingProfileResponse
, StatusNotificationResponse
, UnlockConnectorResponse
} from
'../types/ocpp/1.6/RequestResponses';
3 import { ChargingProfile
, ChargingProfilePurposeType
} from
'../types/ocpp/1.6/ChargingProfile';
4 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
5 import ChargingStationTemplate
, { PowerOutType
} from
'../types/ChargingStationTemplate';
6 import Connectors
, { Connector
} from
'../types/Connectors';
7 import { MeterValue
, MeterValueLocation
, MeterValueMeasurand
, MeterValuePhase
, MeterValueUnit
, MeterValuesRequest
, MeterValuesResponse
, SampledValue
} from
'../types/ocpp/1.6/MeterValues';
8 import { PerformanceObserver
, performance
} from
'perf_hooks';
9 import Requests
, { BootNotificationRequest
, ChangeConfigurationRequest
, GetConfigurationRequest
, HeartbeatRequest
, RemoteStartTransactionRequest
, RemoteStopTransactionRequest
, ResetRequest
, SetChargingProfileRequest
, StatusNotificationRequest
, UnlockConnectorRequest
} from
'../types/ocpp/1.6/Requests';
10 import WebSocket
, { MessageEvent
} from
'ws';
12 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
13 import { ChargePointErrorCode
} from
'../types/ocpp/1.6/ChargePointErrorCode';
14 import { ChargePointStatus
} from
'../types/ocpp/1.6/ChargePointStatus';
15 import ChargingStationInfo from
'../types/ChargingStationInfo';
16 import Configuration from
'../utils/Configuration';
17 import Constants from
'../utils/Constants';
18 import ElectricUtils from
'../utils/ElectricUtils';
19 import MeasurandValues from
'../types/MeasurandValues';
20 import OCPPError from
'./OcppError';
21 import Statistics from
'../utils/Statistics';
22 import Utils from
'../utils/Utils';
23 import crypto from
'crypto';
25 import logger from
'../utils/Logger';
27 export default class ChargingStation
{
28 private _index
: number;
29 private _stationTemplateFile
: string;
30 private _stationInfo
: ChargingStationInfo
;
31 private _bootNotificationRequest
: BootNotificationRequest
;
32 private _bootNotificationResponse
: BootNotificationResponse
;
33 private _connectors
: Connectors
;
34 private _configuration
: ChargingStationConfiguration
;
35 private _connectorsConfigurationHash
: string;
36 private _supervisionUrl
: string;
37 private _wsConnectionUrl
: string;
38 private _wsConnection
: WebSocket
;
39 private _hasStopped
: boolean;
40 private _hasSocketRestarted
: boolean;
41 private _connectionTimeout
: number;
42 private _autoReconnectRetryCount
: number;
43 private _autoReconnectMaxRetries
: number;
44 private _requests
: Requests
;
45 private _messageQueue
: string[];
46 private _automaticTransactionGeneration
: AutomaticTransactionGenerator
;
47 private _authorizedTags
: string[];
48 private _heartbeatInterval
: number;
49 private _heartbeatSetInterval
: NodeJS
.Timeout
;
50 private _webSocketPingSetInterval
: NodeJS
.Timeout
;
51 private _statistics
: Statistics
;
52 private _performanceObserver
: PerformanceObserver
;
54 constructor(index
: number, stationTemplateFile
: string) {
56 this._stationTemplateFile
= stationTemplateFile
;
57 this._connectors
= {} as Connectors
;
60 this._hasStopped
= false;
61 this._hasSocketRestarted
= false;
62 this._autoReconnectRetryCount
= 0;
64 this._requests
= {} as Requests
;
65 this._messageQueue
= [] as string[];
67 this._authorizedTags
= this._loadAndGetAuthorizedTags();
70 _getStationName(stationTemplate
: ChargingStationTemplate
): string {
71 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
.toString()).substr(('000000000' + this._index
.toString()).length
- 4);
74 _buildStationInfo(): ChargingStationInfo
{
75 let stationTemplateFromFile
: ChargingStationTemplate
;
78 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
79 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
80 fs
.closeSync(fileDescriptor
);
82 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: %j', error
);
85 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
86 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
87 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
88 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
90 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
92 stationInfo
.name
= this._getStationName(stationTemplateFromFile
);
93 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
97 get
stationInfo(): ChargingStationInfo
{
98 return this._stationInfo
;
101 _initialize(): void {
102 this._stationInfo
= this._buildStationInfo();
103 this._bootNotificationRequest
= {
104 chargePointModel
: this._stationInfo
.chargePointModel
,
105 chargePointVendor
: this._stationInfo
.chargePointVendor
,
106 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
107 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && { firmwareVersion
: this._stationInfo
.firmwareVersion
},
109 this._configuration
= this._getTemplateChargingStationConfiguration();
110 this._supervisionUrl
= this._getSupervisionURL();
111 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
112 this._connectionTimeout
= this._getConnectionTimeout() * 1000; // Ms, zero for disabling
113 this._autoReconnectMaxRetries
= this._getAutoReconnectMaxRetries(); // -1 for unlimited
114 // Build connectors if needed
115 const maxConnectors
= this._getMaxNumberOfConnectors();
116 if (maxConnectors
<= 0) {
117 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
119 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
120 if (templateMaxConnectors
<= 0) {
121 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`);
124 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this._stationInfo
.randomConnectors
) {
125 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
126 this._stationInfo
.randomConnectors
= true;
128 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
129 // FIXME: Handle shrinking the number of connectors
130 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
131 this._connectorsConfigurationHash
= connectorsConfigHash
;
132 // Add connector Id 0
133 let lastConnector
= '0';
134 for (lastConnector
in this._stationInfo
.Connectors
) {
135 if (Utils
.convertToInt(lastConnector
) === 0 && this._stationInfo
.useConnectorId0
&& this._stationInfo
.Connectors
[lastConnector
]) {
136 this._connectors
[lastConnector
] = Utils
.cloneObject(this._stationInfo
.Connectors
[lastConnector
]) as Connector
;
139 // Generate all connectors
140 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
141 for (let index
= 1; index
<= maxConnectors
; index
++) {
142 const randConnectorID
= this._stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
143 this._connectors
[index
] = Utils
.cloneObject(this._stationInfo
.Connectors
[randConnectorID
]) as Connector
;
147 // Avoid duplication of connectors related information
148 delete this._stationInfo
.Connectors
;
149 // Initialize transaction attributes on connectors
150 for (const connector
in this._connectors
) {
151 if (!this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
152 this._initTransactionOnConnector(Utils
.convertToInt(connector
));
156 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors().toString(), true);
157 if (!this._getConfigurationKey('MeterValuesSampledData')) {
158 this._addConfigurationKey('MeterValuesSampledData', MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
160 this._stationInfo
.powerDivider
= this._getPowerDivider();
161 if (this.getEnableStatistics()) {
162 this._statistics
= Statistics
.getInstance();
163 this._statistics
.objName
= this._stationInfo
.name
;
164 this._performanceObserver
= new PerformanceObserver((list
) => {
165 const entry
= list
.getEntries()[0];
166 this._statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
167 this._performanceObserver
.disconnect();
172 get
connectors(): Connectors
{
173 return this._connectors
;
176 get
statistics(): Statistics
{
177 return this._statistics
;
180 _logPrefix(): string {
181 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
184 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
185 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
188 _getAuthorizationFile(): string {
189 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
192 _loadAndGetAuthorizedTags(): string[] {
193 let authorizedTags
: string[] = [];
194 const authorizationFile
= this._getAuthorizationFile();
195 if (authorizationFile
) {
197 // Load authorization file
198 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
199 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
200 fs
.closeSync(fileDescriptor
);
202 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
206 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
208 return authorizedTags
;
211 getRandomTagId(): string {
212 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
213 return this._authorizedTags
[index
];
216 hasAuthorizedTags(): boolean {
217 return !Utils
.isEmptyArray(this._authorizedTags
);
220 getEnableStatistics(): boolean {
221 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? this._stationInfo
.enableStatistics
: true;
224 _getNumberOfPhases(): number {
225 switch (this._getPowerOutType()) {
226 case PowerOutType
.AC
:
227 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? Utils
.convertToInt(this._stationInfo
.numberOfPhases
) : 3;
228 case PowerOutType
.DC
:
233 _getNumberOfRunningTransactions(): number {
235 for (const connector
in this._connectors
) {
236 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
243 _getConnectionTimeout(): number {
244 if (!Utils
.isUndefined(this._stationInfo
.connectionTimeout
)) {
245 return this._stationInfo
.connectionTimeout
;
247 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
248 return Configuration
.getConnectionTimeout();
253 _getAutoReconnectMaxRetries(): number {
254 if (!Utils
.isUndefined(this._stationInfo
.autoReconnectMaxRetries
)) {
255 return this._stationInfo
.autoReconnectMaxRetries
;
257 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
258 return Configuration
.getAutoReconnectMaxRetries();
263 _getPowerDivider(): number {
264 let powerDivider
= this._getNumberOfConnectors();
265 if (this._stationInfo
.powerSharedByConnectors
) {
266 powerDivider
= this._getNumberOfRunningTransactions();
271 getConnector(id
: number): Connector
{
272 return this._connectors
[id
];
275 _getTemplateMaxNumberOfConnectors(): number {
276 return Object.keys(this._stationInfo
.Connectors
).length
;
279 _getMaxNumberOfConnectors(): number {
280 let maxConnectors
= 0;
281 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
282 const numberOfConnectors
= this._stationInfo
.numberOfConnectors
as number[];
283 // Distribute evenly the number of connectors
284 maxConnectors
= numberOfConnectors
[(this._index
- 1) % numberOfConnectors
.length
];
285 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
286 maxConnectors
= this._stationInfo
.numberOfConnectors
as number;
288 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
290 return maxConnectors
;
293 _getNumberOfConnectors(): number {
294 return this._connectors
[0] ? Object.keys(this._connectors
).length
- 1 : Object.keys(this._connectors
).length
;
297 _getVoltageOut(): number {
298 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
299 let defaultVoltageOut
: number;
300 switch (this._getPowerOutType()) {
301 case PowerOutType
.AC
:
302 defaultVoltageOut
= 230;
304 case PowerOutType
.DC
:
305 defaultVoltageOut
= 400;
308 logger
.error(errMsg
);
311 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? Utils
.convertToInt(this._stationInfo
.voltageOut
) : defaultVoltageOut
;
314 _getTransactionIdTag(transactionId
: number): string {
315 for (const connector
in this._connectors
) {
316 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
317 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
322 _getTransactionMeterStop(transactionId
: number): number {
323 for (const connector
in this._connectors
) {
324 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
325 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
330 _getPowerOutType(): PowerOutType
{
331 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: PowerOutType
.AC
;
334 _getSupervisionURL(): string {
335 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs()) as string | string[];
337 if (!Utils
.isEmptyArray(supervisionUrls
)) {
338 if (Configuration
.getDistributeStationsToTenantsEqually()) {
339 indexUrl
= this._index
% supervisionUrls
.length
;
342 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
344 return supervisionUrls
[indexUrl
];
346 return supervisionUrls
as string;
349 _getReconnectExponentialDelay(): boolean {
350 return !Utils
.isUndefined(this._stationInfo
.reconnectExponentialDelay
) ? this._stationInfo
.reconnectExponentialDelay
: false;
353 _getAuthorizeRemoteTxRequests(): boolean {
354 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
355 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
358 _getLocalAuthListEnabled(): boolean {
359 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
360 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
363 async _startMessageSequence(): Promise
<void> {
364 // Start WebSocket ping
365 this._startWebSocketPing();
367 this._startHeartbeat();
368 // Initialize connectors status
369 for (const connector
in this._connectors
) {
370 if (!this._hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
)).status && this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
371 // Send status in template at startup
372 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
373 } else if (this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
374 // Send status in template after reset
375 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
376 } else if (!this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
)).status) {
377 // Send previous status at template reload
378 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
380 // Send default status
381 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
385 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
) {
386 if (!this._automaticTransactionGeneration
) {
387 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
389 if (this._automaticTransactionGeneration
.timeToStop
) {
390 this._automaticTransactionGeneration
.start();
393 if (this.getEnableStatistics()) {
394 this._statistics
.start();
398 async _stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
399 // Stop WebSocket ping
400 this._stopWebSocketPing();
402 this._stopHeartbeat();
404 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
405 this._automaticTransactionGeneration
&&
406 !this._automaticTransactionGeneration
.timeToStop
) {
407 await this._automaticTransactionGeneration
.stop(reason
);
409 for (const connector
in this._connectors
) {
410 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
411 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
417 _startWebSocketPing(): void {
418 const webSocketPingInterval
: number = this._getConfigurationKey('WebSocketPingInterval') ? Utils
.convertToInt(this._getConfigurationKey('WebSocketPingInterval').value
) : 0;
419 if (webSocketPingInterval
> 0 && !this._webSocketPingSetInterval
) {
420 this._webSocketPingSetInterval
= setInterval(() => {
421 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
422 this._wsConnection
.ping((): void => { });
424 }, webSocketPingInterval
* 1000);
425 logger
.info(this._logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
426 } else if (this._webSocketPingSetInterval
) {
427 logger
.info(this._logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
429 logger
.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
433 _stopWebSocketPing(): void {
434 if (this._webSocketPingSetInterval
) {
435 clearInterval(this._webSocketPingSetInterval
);
436 this._webSocketPingSetInterval
= null;
440 _restartWebSocketPing(): void {
441 // Stop WebSocket ping
442 this._stopWebSocketPing();
443 // Start WebSocket ping
444 this._startWebSocketPing();
447 _startHeartbeat(): void {
448 if (this._heartbeatInterval
&& this._heartbeatInterval
> 0 && !this._heartbeatSetInterval
) {
449 this._heartbeatSetInterval
= setInterval(async () => {
450 await this.sendHeartbeat();
451 }, this._heartbeatInterval
);
452 logger
.info(this._logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this._heartbeatInterval
));
453 } else if (this._heartbeatSetInterval
) {
454 logger
.info(this._logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this._heartbeatInterval
) + ' already started');
456 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval ? Utils.milliSecondsToHHMMSS(this._heartbeatInterval) : this._heartbeatInterval}, not starting the heartbeat`);
460 _stopHeartbeat(): void {
461 if (this._heartbeatSetInterval
) {
462 clearInterval(this._heartbeatSetInterval
);
463 this._heartbeatSetInterval
= null;
467 _restartHeartbeat(): void {
469 this._stopHeartbeat();
471 this._startHeartbeat();
474 _startAuthorizationFileMonitoring(): void {
475 // eslint-disable-next-line @typescript-eslint/no-unused-vars
476 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
478 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
479 // Initialize _authorizedTags
480 this._authorizedTags
= this._loadAndGetAuthorizedTags();
482 logger
.error(this._logPrefix() + ' Authorization file monitoring error: %j', error
);
487 _startStationTemplateFileMonitoring(): void {
488 // eslint-disable-next-line @typescript-eslint/no-unused-vars
489 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
491 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
494 if (!this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
495 this._automaticTransactionGeneration
) {
496 this._automaticTransactionGeneration
.stop().catch(() => { });
498 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
500 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error
);
505 _startMeterValues(connectorId
: number, interval
: number): void {
506 if (!this.getConnector(connectorId
).transactionStarted
) {
507 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
509 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
510 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
514 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
515 if (this.getEnableStatistics()) {
516 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
517 this._performanceObserver
.observe({
518 entryTypes
: ['function'],
520 await sendMeterValues(connectorId
, interval
, this);
522 await this.sendMeterValues(connectorId
, interval
, this);
526 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
530 _openWSConnection(options
?: WebSocket
.ClientOptions
): void {
531 if (Utils
.isUndefined(options
)) {
532 options
= {} as WebSocket
.ClientOptions
;
534 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
535 options
.handshakeTimeout
= this._connectionTimeout
;
537 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
, options
);
538 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
542 this._openWSConnection();
543 // Monitor authorization file
544 this._startAuthorizationFileMonitoring();
545 // Monitor station template file
546 this._startStationTemplateFileMonitoring();
547 // Handle Socket incoming messages
548 this._wsConnection
.on('message', this.onMessage
.bind(this));
549 // Handle Socket error
550 this._wsConnection
.on('error', this.onError
.bind(this));
551 // Handle Socket close
552 this._wsConnection
.on('close', this.onClose
.bind(this));
553 // Handle Socket opening connection
554 this._wsConnection
.on('open', this.onOpen
.bind(this));
555 // Handle Socket ping
556 this._wsConnection
.on('ping', this.onPing
.bind(this));
557 // Handle Socket pong
558 this._wsConnection
.on('pong', this.onPong
.bind(this));
561 async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
562 // Stop message sequence
563 await this._stopMessageSequence(reason
);
564 // eslint-disable-next-line guard-for-in
565 for (const connector
in this._connectors
) {
566 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
568 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
569 this._wsConnection
.close();
571 this._bootNotificationResponse
= null;
572 this._hasStopped
= true;
575 async _reconnect(error
): Promise
<void> {
576 logger
.error(this._logPrefix() + ' Socket: abnormally closed: %j', error
);
578 this._stopHeartbeat();
579 // Stop the ATG if needed
580 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
581 this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
582 this._automaticTransactionGeneration
&&
583 !this._automaticTransactionGeneration
.timeToStop
) {
584 this._automaticTransactionGeneration
.stop().catch(() => { });
586 if (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1) {
587 this._autoReconnectRetryCount
++;
588 const reconnectDelay
= (this._getReconnectExponentialDelay() ? Utils
.exponentialDelay(this._autoReconnectRetryCount
) : this._connectionTimeout
);
589 logger
.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
590 await Utils
.sleep(reconnectDelay
);
591 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
.toString());
592 this._openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
593 } else if (this._autoReconnectMaxRetries
!== -1) {
594 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectMaxRetries})`);
598 async onOpen(): Promise
<void> {
599 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
600 if (!this._hasSocketRestarted
|| this._hasStopped
) {
601 // Send BootNotification
602 this._bootNotificationResponse
= await this.sendBootNotification();
604 if (this._bootNotificationResponse
.status === RegistrationStatus
.ACCEPTED
) {
605 await this._startMessageSequence();
608 await Utils
.sleep(this._bootNotificationResponse
.interval
* 1000);
609 // Resend BootNotification
610 this._bootNotificationResponse
= await this.sendBootNotification();
611 } while (this._bootNotificationResponse
.status !== RegistrationStatus
.ACCEPTED
);
613 if (this._hasSocketRestarted
&& this._bootNotificationResponse
.status === RegistrationStatus
.ACCEPTED
) {
614 if (!Utils
.isEmptyArray(this._messageQueue
)) {
615 this._messageQueue
.forEach((message
, index
) => {
616 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
617 this._messageQueue
.splice(index
, 1);
618 this._wsConnection
.send(message
);
623 this._autoReconnectRetryCount
= 0;
624 this._hasSocketRestarted
= false;
627 async onError(errorEvent
): Promise
<void> {
628 switch (errorEvent
.code
) {
630 this._hasSocketRestarted
= true;
631 await this._reconnect(errorEvent
);
634 logger
.error(this._logPrefix() + ' Socket error: %j', errorEvent
);
639 async onClose(closeEvent
): Promise
<void> {
640 switch (closeEvent
) {
641 case 1000: // Normal close
643 logger
.info(this._logPrefix() + ' Socket normally closed: %j', closeEvent
);
644 this._autoReconnectRetryCount
= 0;
646 default: // Abnormal close
647 this._hasSocketRestarted
= true;
648 await this._reconnect(closeEvent
);
654 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
658 logger
.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
661 async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
662 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
665 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString());
667 // Check the Type of message
668 switch (messageType
) {
670 case Constants
.OCPP_JSON_CALL_MESSAGE
:
671 if (this.getEnableStatistics()) {
672 this._statistics
.addMessage(commandName
, messageType
);
675 await this.handleRequest(messageId
, commandName
, commandPayload
);
678 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
680 // eslint-disable-next-line no-case-declarations
681 let responseCallback
; let requestPayload
;
682 if (Utils
.isIterable(this._requests
[messageId
])) {
683 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
685 throw new Error(`Response request for message id ${messageId} is not iterable`);
687 if (!responseCallback
) {
689 throw new Error(`Response request for unknown message id ${messageId}`);
691 delete this._requests
[messageId
];
692 responseCallback(commandName
, requestPayload
);
695 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
696 if (!this._requests
[messageId
]) {
698 throw new Error(`Error request for unknown message id ${messageId}`);
700 // eslint-disable-next-line no-case-declarations
702 if (Utils
.isIterable(this._requests
[messageId
])) {
703 [, rejectCallback
] = this._requests
[messageId
];
705 throw new Error(`Error request for message id ${messageId} is not iterable`);
707 delete this._requests
[messageId
];
708 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
712 // eslint-disable-next-line no-case-declarations
713 const errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
714 logger
.error(errMsg
);
715 throw new Error(errMsg
);
719 logger
.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent
, error
, this._requests
[messageId
]);
721 messageType
!== Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
&& await this.sendError(messageId
, error
, commandName
);
725 async sendHeartbeat(): Promise
<void> {
727 const payload
: HeartbeatRequest
= {};
728 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
730 logger
.error(this._logPrefix() + ' Send Heartbeat error: %j', error
);
735 async sendBootNotification(): Promise
<BootNotificationResponse
> {
737 return await this.sendMessage(Utils
.generateUUID(), this._bootNotificationRequest
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification') as BootNotificationResponse
;
739 logger
.error(this._logPrefix() + ' Send BootNotification error: %j', error
);
744 async sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
: ChargePointErrorCode
= ChargePointErrorCode
.NO_ERROR
): Promise
<void> {
745 this.getConnector(connectorId
).status = status;
747 const payload
: StatusNotificationRequest
= {
752 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
754 logger
.error(this._logPrefix() + ' Send StatusNotification error: %j', error
);
759 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<StartTransactionResponse
> {
761 const payload
: StartTransactionRequest
= {
763 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_IDTAG
},
765 timestamp
: new Date().toISOString(),
767 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction') as StartTransactionResponse
;
769 logger
.error(this._logPrefix() + ' Send StartTransaction error: %j', error
);
774 async sendStopTransaction(transactionId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
775 const idTag
= this._getTransactionIdTag(transactionId
);
777 const payload
: StopTransactionRequest
= {
779 ...!Utils
.isUndefined(idTag
) && { idTag
: idTag
},
780 meterStop
: this._getTransactionMeterStop(transactionId
),
781 timestamp
: new Date().toISOString(),
782 ...reason
&& { reason
},
784 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction') as StartTransactionResponse
;
786 logger
.error(this._logPrefix() + ' Send StopTransaction error: %j', error
);
791 // eslint-disable-next-line consistent-this
792 async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
794 const meterValue
: MeterValue
= {
795 timestamp
: new Date().toISOString(),
798 const meterValuesTemplate
: SampledValue
[] = self.getConnector(connectorId
).MeterValues
;
799 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
800 const connector
= self.getConnector(connectorId
);
802 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.STATE_OF_CHARGE
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.STATE_OF_CHARGE
)) {
803 meterValue
.sampledValue
.push({
804 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.PERCENT
},
805 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
806 measurand
: meterValuesTemplate
[index
].measurand
,
807 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: MeterValueLocation
.EV
},
808 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100).toString() },
810 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
811 if (Utils
.convertToInt(meterValue
.sampledValue
[sampledValuesIndex
].value
) > 100 || debug
) {
812 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/100`);
815 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.VOLTAGE
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.VOLTAGE
)) {
816 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
817 meterValue
.sampledValue
.push({
818 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
819 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
820 measurand
: meterValuesTemplate
[index
].measurand
,
821 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
822 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
824 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
825 const voltageValue
= Utils
.convertToFloat(meterValue
.sampledValue
[meterValue
.sampledValue
.length
- 1].value
);
826 let phaseValue
: string;
827 if (voltageValue
>= 0 && voltageValue
<= 250) {
828 phaseValue
= `L${phase}-N`;
829 } else if (voltageValue
> 250) {
830 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
832 meterValue
.sampledValue
.push({
833 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
834 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
835 measurand
: meterValuesTemplate
[index
].measurand
,
836 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
837 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
838 phase
: phaseValue
as MeterValuePhase
,
841 // Power.Active.Import measurand
842 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.POWER_ACTIVE_IMPORT
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.POWER_ACTIVE_IMPORT
)) {
843 // FIXME: factor out powerDivider checks
844 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
845 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
846 logger
.error(errMsg
);
848 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
849 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
850 logger
.error(errMsg
);
853 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
854 const powerMeasurandValues
= {} as MeasurandValues
;
855 const maxPower
= Math.round(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
);
856 const maxPowerPerPhase
= Math.round((self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
) / self._getNumberOfPhases());
857 switch (self._getPowerOutType()) {
858 case PowerOutType
.AC
:
859 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
860 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
861 powerMeasurandValues
.L2
= 0;
862 powerMeasurandValues
.L3
= 0;
863 if (self._getNumberOfPhases() === 3) {
864 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
865 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
867 powerMeasurandValues
.allPhases
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
870 case PowerOutType
.DC
:
871 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
872 powerMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxPower
);
876 logger
.error(errMsg
);
879 meterValue
.sampledValue
.push({
880 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
881 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
882 measurand
: meterValuesTemplate
[index
].measurand
,
883 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
884 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.allPhases
.toString() },
886 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
887 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxPower
|| debug
) {
888 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxPower}`);
890 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
891 const phaseValue
= `L${phase}-N`;
892 meterValue
.sampledValue
.push({
893 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
894 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
895 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
896 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
897 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] as string },
898 phase
: phaseValue
as MeterValuePhase
,
901 // Current.Import measurand
902 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.CURRENT_IMPORT
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.CURRENT_IMPORT
)) {
903 // FIXME: factor out powerDivider checks
904 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
905 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
906 logger
.error(errMsg
);
908 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
909 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
910 logger
.error(errMsg
);
913 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
914 const currentMeasurandValues
: MeasurandValues
= {} as MeasurandValues
;
915 let maxAmperage
: number;
916 switch (self._getPowerOutType()) {
917 case PowerOutType
.AC
:
918 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
919 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
920 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
921 currentMeasurandValues
.L2
= 0;
922 currentMeasurandValues
.L3
= 0;
923 if (self._getNumberOfPhases() === 3) {
924 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
925 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
927 currentMeasurandValues
.allPhases
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
930 case PowerOutType
.DC
:
931 maxAmperage
= ElectricUtils
.ampTotalFromPower(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
932 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
933 currentMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxAmperage
);
937 logger
.error(errMsg
);
940 meterValue
.sampledValue
.push({
941 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
942 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
943 measurand
: meterValuesTemplate
[index
].measurand
,
944 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
945 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.allPhases
.toString() },
947 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
948 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxAmperage
|| debug
) {
949 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxAmperage}`);
951 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
952 const phaseValue
= `L${phase}`;
953 meterValue
.sampledValue
.push({
954 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
955 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
956 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
957 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
958 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] as string },
959 phase
: phaseValue
as MeterValuePhase
,
962 // Energy.Active.Import.Register measurand (default)
963 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
964 // FIXME: factor out powerDivider checks
965 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
966 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
967 logger
.error(errMsg
);
969 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
970 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
971 logger
.error(errMsg
);
974 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
975 const measurandValue
= Utils
.getRandomInt(self._stationInfo
.maxPower
/ (self._stationInfo
.powerDivider
* 3600000) * interval
);
976 // Persist previous value in connector
977 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
978 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
980 connector
.lastEnergyActiveImportRegisterValue
= 0;
983 meterValue
.sampledValue
.push({
984 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT_HOUR
},
985 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
986 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
987 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
988 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} :
989 { value
: connector
.lastEnergyActiveImportRegisterValue
.toString() },
991 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
992 const maxConsumption
= Math.round(self._stationInfo
.maxPower
* 3600 / (self._stationInfo
.powerDivider
* interval
));
993 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxConsumption
|| debug
) {
994 logger
.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxConsumption}`);
996 // Unsupported measurand
998 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
1001 const payload
: MeterValuesRequest
= {
1003 transactionId
: self.getConnector(connectorId
).transactionId
,
1004 meterValue
: meterValue
,
1006 await self.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
1008 logger
.error(self._logPrefix() + ' Send MeterValues error: %j', error
);
1013 async sendError(messageId
: string, err
: Error | OCPPError
, commandName
: string): Promise
<unknown
> {
1014 // Check exception type: only OCPP error are accepted
1015 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
, err
.stack
&& err
.stack
);
1017 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
, commandName
);
1020 async sendMessage(messageId
: string, commandParams
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
: string): Promise
<any> {
1021 // eslint-disable-next-line @typescript-eslint/no-this-alias
1023 // Send a message through wsConnection
1024 return new Promise((resolve
: (value
?: any | PromiseLike
<any>) => void, reject
: (reason
?: any) => void) => {
1027 switch (messageType
) {
1029 case Constants
.OCPP_JSON_CALL_MESSAGE
:
1031 this._requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
];
1032 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
1035 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
1037 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
1040 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
1041 // Build Error Message
1042 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
1045 // Check if wsConnection is ready
1046 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
1047 if (this.getEnableStatistics()) {
1048 this._statistics
.addMessage(commandName
, messageType
);
1050 // Yes: Send Message
1051 this._wsConnection
.send(messageToSend
);
1054 // Handle dups in buffer
1055 for (const message
of this._messageQueue
) {
1057 if (JSON
.stringify(messageToSend
) === JSON
.stringify(message
)) {
1064 this._messageQueue
.push(messageToSend
);
1067 return rejectCallback(new OCPPError(commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams
.details
? commandParams
.details
: {}));
1070 if (messageType
=== Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
) {
1073 } else if (messageType
=== Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
) {
1075 setTimeout(() => rejectCallback(new OCPPError(commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams
.details
? commandParams
.details
: {})), Constants
.OCPP_SOCKET_TIMEOUT
);
1078 // Function that will receive the request's response
1079 function responseCallback(payload
, requestPayload
): void {
1080 if (self.getEnableStatistics()) {
1081 self._statistics
.addMessage(commandName
, messageType
);
1083 // Send the response
1084 self.handleResponse(commandName
, payload
, requestPayload
);
1088 // Function that will receive the request's rejection
1089 function rejectCallback(error
: OCPPError
): void {
1090 if (self.getEnableStatistics()) {
1091 self._statistics
.addMessage(commandName
, messageType
);
1093 logger
.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error
, commandName
, commandParams
);
1095 // eslint-disable-next-line no-empty-function
1096 self._requests
[messageId
] = [() => { }, () => { }, {}]; // Properly format the request
1103 handleResponse(commandName
: string, payload
, requestPayload
): void {
1104 const responseCallbackFn
= 'handleResponse' + commandName
;
1105 if (typeof this[responseCallbackFn
] === 'function') {
1106 this[responseCallbackFn
](payload
, requestPayload
);
1108 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
1112 handleResponseBootNotification(payload
: BootNotificationResponse
, requestPayload
: BootNotificationRequest
): void {
1113 if (payload
.status === RegistrationStatus
.ACCEPTED
) {
1114 this._heartbeatInterval
= Utils
.convertToInt(payload
.interval
) * 1000;
1115 this._heartbeatSetInterval
? this._restartHeartbeat() : this._startHeartbeat();
1116 this._addConfigurationKey('HeartBeatInterval', payload
.interval
.toString());
1117 this._addConfigurationKey('HeartbeatInterval', payload
.interval
.toString(), false, false);
1118 this._hasStopped
&& (this._hasStopped
= false);
1119 } else if (payload
.status === RegistrationStatus
.PENDING
) {
1120 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
1122 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
1126 _initTransactionOnConnector(connectorId
: number): void {
1127 this.getConnector(connectorId
).transactionStarted
= false;
1128 this.getConnector(connectorId
).transactionId
= null;
1129 this.getConnector(connectorId
).idTag
= null;
1130 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
1133 _resetTransactionOnConnector(connectorId
: number): void {
1134 this._initTransactionOnConnector(connectorId
);
1135 if (this.getConnector(connectorId
).transactionSetInterval
) {
1136 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
1140 handleResponseStartTransaction(payload
: StartTransactionResponse
, requestPayload
: StartTransactionRequest
): void {
1141 const connectorId
= Utils
.convertToInt(requestPayload
.connectorId
);
1142 if (this.getConnector(connectorId
).transactionStarted
) {
1143 logger
.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId
.toString() + ': %j', this.getConnector(connectorId
));
1147 let transactionConnectorId
: number;
1148 for (const connector
in this._connectors
) {
1149 if (Utils
.convertToInt(connector
) === connectorId
) {
1150 transactionConnectorId
= Utils
.convertToInt(connector
);
1154 if (!transactionConnectorId
) {
1155 logger
.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId
.toString());
1158 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1159 this.getConnector(connectorId
).transactionStarted
= true;
1160 this.getConnector(connectorId
).transactionId
= payload
.transactionId
;
1161 this.getConnector(connectorId
).idTag
= requestPayload
.idTag
;
1162 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1163 this.sendStatusNotification(connectorId
, ChargePointStatus
.CHARGING
).catch(() => { });
1164 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
.toString() + ' STARTED on ' + this._stationInfo
.name
+ '#' + connectorId
.toString() + ' for idTag ' + requestPayload
.idTag
);
1165 if (this._stationInfo
.powerSharedByConnectors
) {
1166 this._stationInfo
.powerDivider
++;
1168 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
1169 this._startMeterValues(connectorId
,
1170 configuredMeterValueSampleInterval
? Utils
.convertToInt(configuredMeterValueSampleInterval
.value
) * 1000 : 60000);
1172 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
.status + ', idTag ' + requestPayload
.idTag
);
1173 this._resetTransactionOnConnector(connectorId
);
1174 this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
).catch(() => { });
1178 handleResponseStopTransaction(payload
: StopTransactionResponse
, requestPayload
: StopTransactionRequest
): void {
1179 let transactionConnectorId
: number;
1180 for (const connector
in this._connectors
) {
1181 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== Utils
.convertToInt(requestPayload
.transactionId
)) {
1182 transactionConnectorId
= Utils
.convertToInt(connector
);
1186 if (!transactionConnectorId
) {
1187 logger
.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload
.transactionId
.toString());
1190 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1191 this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.AVAILABLE
).catch(() => { });
1192 if (this._stationInfo
.powerSharedByConnectors
) {
1193 this._stationInfo
.powerDivider
--;
1195 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
.toString() + ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
.toString());
1196 this._resetTransactionOnConnector(transactionConnectorId
);
1198 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
?.status);
1202 handleResponseStatusNotification(payload
: StatusNotificationRequest
, requestPayload
: StatusNotificationResponse
): void {
1203 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1206 handleResponseMeterValues(payload
: MeterValuesRequest
, requestPayload
: MeterValuesResponse
): void {
1207 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1210 handleResponseHeartbeat(payload
: HeartbeatResponse
, requestPayload
: HeartbeatRequest
): void {
1211 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1214 async handleRequest(messageId
: string, commandName
: string, commandPayload
): Promise
<void> {
1217 if (typeof this['handleRequest' + commandName
] === 'function') {
1219 // Call the method to build the response
1220 response
= await this['handleRequest' + commandName
](commandPayload
);
1223 logger
.error(this._logPrefix() + ' Handle request error: %j', error
);
1224 // Send back response to inform backend
1225 await this.sendError(messageId
, error
, commandName
);
1230 await this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1231 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1234 await this.sendMessage(messageId
, response
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
);
1237 // Simulate charging station restart
1238 handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
1239 setImmediate(async () => {
1240 await this.stop(commandPayload
.type + 'Reset' as StopTransactionReason
);
1241 await Utils
.sleep(this._stationInfo
.resetTime
);
1244 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`);
1245 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1248 handleRequestClearCache(): DefaultResponse
{
1249 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1252 async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
1253 const connectorId
= Utils
.convertToInt(commandPayload
.connectorId
);
1254 if (connectorId
=== 0) {
1255 logger
.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
1256 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
1258 if (this.getConnector(connectorId
).transactionStarted
) {
1259 const stopResponse
= await this.sendStopTransaction(this.getConnector(connectorId
).transactionId
, StopTransactionReason
.UNLOCK_COMMAND
);
1260 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1261 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1263 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
1265 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1266 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1269 _getConfigurationKey(key
: string): ConfigurationKey
{
1270 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
1273 _addConfigurationKey(key
: string, value
: string, readonly = false, visible
= true, reboot
= false): void {
1274 const keyFound
= this._getConfigurationKey(key
);
1276 this._configuration
.configurationKey
.push({
1286 _setConfigurationKeyValue(key
: string, value
: string): void {
1287 const keyFound
= this._getConfigurationKey(key
);
1289 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1290 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1294 handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
1295 const configurationKey
: ConfigurationKey
[] = [];
1296 const unknownKey
: string[] = [];
1297 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1298 for (const configuration
of this._configuration
.configurationKey
) {
1299 if (Utils
.isUndefined(configuration
.visible
)) {
1300 configuration
.visible
= true;
1302 if (!configuration
.visible
) {
1305 configurationKey
.push({
1306 key
: configuration
.key
,
1307 readonly: configuration
.readonly,
1308 value
: configuration
.value
,
1312 for (const key
of commandPayload
.key
) {
1313 const keyFound
= this._getConfigurationKey(key
);
1315 if (Utils
.isUndefined(keyFound
.visible
)) {
1316 keyFound
.visible
= true;
1318 if (!keyFound
.visible
) {
1321 configurationKey
.push({
1323 readonly: keyFound
.readonly,
1324 value
: keyFound
.value
,
1327 unknownKey
.push(key
);
1337 handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
1338 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1340 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
1341 } else if (keyToChange
&& keyToChange
.readonly) {
1342 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
1343 } else if (keyToChange
&& !keyToChange
.readonly) {
1344 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1345 let valueChanged
= false;
1346 if (this._configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
1347 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1348 valueChanged
= true;
1350 let triggerHeartbeatRestart
= false;
1351 if (keyToChange
.key
=== 'HeartBeatInterval' && valueChanged
) {
1352 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1353 triggerHeartbeatRestart
= true;
1355 if (keyToChange
.key
=== 'HeartbeatInterval' && valueChanged
) {
1356 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1357 triggerHeartbeatRestart
= true;
1359 if (triggerHeartbeatRestart
) {
1360 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1361 this._restartHeartbeat();
1363 if (keyToChange
.key
=== 'WebSocketPingInterval' && valueChanged
) {
1364 this._restartWebSocketPing();
1366 if (keyToChange
.reboot
) {
1367 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
1369 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
1373 handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
1374 if (!this.getConnector(commandPayload
.connectorId
)) {
1375 logger
.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`);
1376 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1378 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& !this.getConnector(commandPayload
.connectorId
)?.transactionStarted
) {
1379 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1381 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
1382 if (chargingProfile
.chargingProfileId
=== commandPayload
.csChargingProfiles
.chargingProfileId
1383 || (chargingProfile
.stackLevel
=== commandPayload
.csChargingProfiles
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.csChargingProfiles
.chargingProfilePurpose
)) {
1384 this.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = chargingProfile
;
1385 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1388 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.push(commandPayload
.csChargingProfiles
);
1389 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1392 async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
1393 const transactionConnectorID
: number = commandPayload
.connectorId
? Utils
.convertToInt(commandPayload
.connectorId
) : 1;
1394 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1395 // Check if authorized
1396 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1397 // Authorization successful start transaction
1398 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1399 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1400 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1402 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED, idTag ' + commandPayload
.idTag
);
1403 return Constants
.OCPP_RESPONSE_REJECTED
;
1405 // No local authorization check required => start transaction
1406 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1407 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1408 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1411 async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
1412 const transactionId
= Utils
.convertToInt(commandPayload
.transactionId
);
1413 for (const connector
in this._connectors
) {
1414 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
1415 await this.sendStopTransaction(transactionId
);
1416 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1419 logger
.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
1420 return Constants
.OCPP_RESPONSE_REJECTED
;