1 const Configuration
= require('../utils/Configuration');
2 const logger
= require('../utils/Logger');
3 const WebSocket
= require('ws');
4 const Constants
= require('../utils/Constants');
5 const Utils
= require('../utils/Utils');
6 const OCPPError
= require('./OcppError');
7 const AutomaticTransactionGenerator
= require('./AutomaticTransactionGenerator');
8 const Statistics
= require('../utils/Statistics');
9 const fs
= require('fs');
10 const {performance
, PerformanceObserver
} = require('perf_hooks');
12 class ChargingStation
{
13 constructor(index
, stationTemplateFile
) {
15 this._stationTemplateFile
= stationTemplateFile
;
18 this._autoReconnectRetryCount
= 0;
19 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
20 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
23 this._messageQueue
= [];
25 this._isSocketRestart
= false;
27 this._authorizedTags
= this._getAuthorizedTags();
31 this._stationInfo
= this._buildStationInfo();
32 this._bootNotificationMessage
= {
33 chargePointModel
: this._stationInfo
.chargePointModel
,
34 chargePointVendor
: this._stationInfo
.chargePointVendor
,
35 // chargePointSerialNumber: this._stationInfo.chargePointSerialNumber,
36 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
38 this._configuration
= this._getConfiguration();
39 this._supervisionUrl
= this._getSupervisionURL();
40 this._statistics
= new Statistics(this._stationInfo
.name
);
41 this._performanceObserver
= new PerformanceObserver((list
) => {
42 const entry
= list
.getEntries()[0];
43 this._statistics
.logPerformance(entry
, 'ChargingStation');
44 this._performanceObserver
.disconnect();
49 return Utils
.basicFormatLog(` ${this._stationInfo.name}:`);
53 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
56 _getAuthorizationFile() {
57 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
60 _getAuthorizedTags() {
61 let authorizedTags
= [];
62 const authorizationFile
= this._getAuthorizationFile();
63 if (authorizationFile
) {
65 // Load authorization file
66 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
67 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
68 fs
.closeSync(fileDescriptor
);
70 logger
.error(this._basicFormatLog() + ' Authorization file loading error: ' + error
);
73 logger
.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile
);
75 return authorizedTags
;
78 _startAuthorizationFileMonitoring() {
79 // eslint-disable-next-line no-unused-vars
80 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
82 logger
.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
83 // Initialize _authorizedTags
84 this._authorizedTags
= this._getAuthorizedTags();
86 logger
.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error
);
91 _startStationTemplateFileMonitoring() {
92 // eslint-disable-next-line no-unused-vars
93 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
95 logger
.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
99 logger
.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error
);
104 _getSupervisionURL() {
105 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
107 if (Array
.isArray(supervisionUrls
)) {
108 if (Configuration
.getDistributeStationToTenantEqually()) {
109 indexUrl
= this._index
% supervisionUrls
.length
;
112 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
114 return supervisionUrls
[indexUrl
];
116 return supervisionUrls
;
119 _getStationName(stationTemplate
) {
120 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
123 _getAuthorizeRemoteTxRequests() {
124 const authorizeRemoteTxRequests
= this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== 'AuthorizeRemoteTxRequests');
125 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
128 _getLocalAuthListEnabled() {
129 const localAuthListEnabled
= this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== 'LocalAuthListEnabled');
130 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
133 _buildStationInfo() {
134 let stationTemplateFromFile
;
136 // Load template file
137 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
138 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
139 fs
.closeSync(fileDescriptor
);
141 logger
.error(this._basicFormatLog() + ' Template file loading error: ' + error
);
143 const stationTemplate
= stationTemplateFromFile
|| {};
144 if (Array
.isArray(stationTemplateFromFile
.power
)) {
145 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
147 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
149 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
150 return stationTemplate
;
154 this._url
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
155 this._wsConnection
= new WebSocket(this._url
, 'ocpp1.6');
156 logger
.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl
);
157 // Monitor authorization file
158 this._startAuthorizationFileMonitoring();
159 // Monitor station template file
160 this._startStationTemplateFileMonitoring();
161 // Handle Socket incoming messages
162 this._wsConnection
.on('message', this.onMessage
.bind(this));
163 // Handle Socket error
164 this._wsConnection
.on('error', this.onError
.bind(this));
165 // Handle Socket close
166 this._wsConnection
.on('close', this.onClose
.bind(this));
167 // Handle Socket opening connection
168 this._wsConnection
.on('open', this.onOpen
.bind(this));
169 // Handle Socket ping
170 this._wsConnection
.on('ping', this.onPing
.bind(this));
174 logger
.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`);
175 if (this._isSocketRestart
) {
176 this._basicStartMessageSequence();
177 if (this._messageQueue
.length
> 0) {
178 this._messageQueue
.forEach((message
) => {
179 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
180 this._wsConnection
.send(message
);
185 // At first start, send BootNotification
187 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
189 logger
.error(this._basicFormatLog() + ' Send boot notification error: ' + error
);
192 this._autoReconnectRetryCount
= 0;
193 this._isSocketRestart
= false;
199 this._isSocketRestart
= true;
200 this._reconnect(error
);
203 logger
.error(this._basicFormatLog() + ' Socket error: ' + error
);
210 case 1000: // Normal close
212 logger
.info(this._basicFormatLog() + ' Socket normally closed ' + error
);
213 this._autoReconnectRetryCount
= 0;
215 default: // Abnormal close
216 this._isSocketRestart
= true;
217 this._reconnect(error
);
223 logger
.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
226 async
onMessage(message
) {
227 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
230 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
232 // Check the Type of message
233 switch (messageType
) {
235 case Constants
.OCPP_JSON_CALL_MESSAGE
:
237 this._statistics
.addMessage(commandName
);
238 await
this.handleRequest(messageId
, commandName
, commandPayload
);
241 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
243 // eslint-disable-next-line no-case-declarations
244 let responseCallback
; let requestPayload
;
245 if (Utils
.isIterable(this._requests
[messageId
])) {
246 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
248 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
250 if (!responseCallback
) {
252 throw new Error(`Response for unknown message id ${messageId}`);
254 delete this._requests
[messageId
];
255 // this._statistics.addMessage(commandName)
256 responseCallback(commandName
, requestPayload
);
259 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
260 if (!this._requests
[messageId
]) {
262 throw new Error(`Error for unknown message id ${messageId}`);
264 // eslint-disable-next-line no-case-declarations
266 if (Utils
.isIterable(this._requests
[messageId
])) {
267 [, rejectCallback
] = this._requests
[messageId
];
269 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
271 delete this._requests
[messageId
];
272 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
276 throw new Error(`Wrong message type ${messageType}`);
280 logger
.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message
, error
, this._requests
[messageId
]);
282 // await this.sendError(messageId, error);
286 // eslint-disable-next-line class-methods-use-this
287 async
_startHeartbeat(self
) {
288 if (self
._heartbeatInterval
&& !self
._heartbeatSetInterval
) {
289 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
290 self
._heartbeatSetInterval
= setInterval(() => {
293 currentTime
: new Date().toISOString(),
295 self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
297 logger
.error(self
._basicFormatLog() + ' Send heartbeat error: ' + error
);
299 }, self
._heartbeatInterval
);
301 logger
.error(self
._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
306 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
307 // Stop heartbeat interval
308 if (this._heartbeatSetInterval
) {
309 clearInterval(this._heartbeatSetInterval
);
310 this._heartbeatSetInterval
= null;
312 // Stop the ATG if needed
313 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
314 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
315 this._automaticTransactionGeneration
&&
316 !this._automaticTransactionGeneration
.timeToStop
) {
317 this._automaticTransactionGeneration
.stop();
319 if (this._autoReconnectTimeout
!== 0 &&
320 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
321 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
322 this._autoReconnectRetryCount
++;
324 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
326 }, this._autoReconnectTimeout
);
327 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
328 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
332 send(command
, messageType
= Constants
.OCPP_JSON_CALL_MESSAGE
) {
334 return this.sendMessage(Utils
.generateUUID(), command
, messageType
);
337 sendError(messageId
, err
) {
338 // Check exception: only OCPP error are accepted
339 const error
= (err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
));
341 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
344 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
351 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
353 logger
.error(this._basicFormatLog() + ' Send status error: ' + error
);
357 async
sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
358 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
361 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
362 // Send a message through wsConnection
365 return new Promise((resolve
, reject
) => {
368 switch (messageType
) {
370 case Constants
.OCPP_JSON_CALL_MESSAGE
:
371 this._statistics
.addMessage(commandName
);
373 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
374 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
377 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
379 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
382 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
384 this._statistics
.addMessage(`Error ${command.code}`);
385 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
388 // Check if wsConnection is ready
389 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
391 this._wsConnection
.send(messageToSend
);
393 // Buffer message until connection is back
394 this._messageQueue
.push(messageToSend
);
397 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
400 } else if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
401 // Send timeout in case connection is open otherwise wait for ever
402 // FIXME: Handle message on timeout
403 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
406 // Function that will receive the request's response
407 function responseCallback(payload
, requestPayload
) {
408 self
._statistics
.addMessage(commandName
, true);
409 const responseCallbackFn
= 'handleResponse' + commandName
;
410 if (typeof self
[responseCallbackFn
] === 'function') {
411 self
[responseCallbackFn
](payload
, requestPayload
, self
);
413 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn
);
419 // Function that will receive the request's rejection
420 function rejectCallback(reason
) {
422 // eslint-disable-next-line no-empty-function
423 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
424 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
431 async
_basicStartMessageSequence() {
432 this._startHeartbeat(this);
434 if (!this._connectors
) {
435 this._connectors
= {};
436 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
437 // determine number of customized connectors
439 for (lastConnector
in connectorsConfig
) {
440 // add connector 0, OCPP specification violation that for example KEBA have
441 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
)) {
442 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
445 let maxConnectors
= 0;
446 if (Array
.isArray(this._stationInfo
.numberOfConnectors
)) {
447 // generate some connectors
448 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
450 maxConnectors
= this._stationInfo
.numberOfConnectors
;
452 // generate all connectors
453 for (let index
= 1; index
<= maxConnectors
; index
++) {
454 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
455 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
459 for (const connector
in this._connectors
) {
460 if (!this._connectors
[connector
].transactionStarted
) {
461 if (this._connectors
[connector
].bootStatus
) {
462 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
464 this.sendStatusNotificationWithTimeout(connector
, 'Available');
467 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
471 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
472 if (!this._automaticTransactionGeneration
) {
473 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
475 if (this._automaticTransactionGeneration
.timeToStop
) {
476 this._automaticTransactionGeneration
.start();
479 this._statistics
.start();
482 _resetTransactionOnConnector(connectorID
) {
483 this._connectors
[connectorID
].transactionStarted
= false;
484 this._connectors
[connectorID
].transactionId
= null;
485 this._connectors
[connectorID
].lastConsumptionValue
= -1;
486 this._connectors
[connectorID
].lastSoC
= -1;
487 if (this._connectors
[connectorID
].transactionInterval
) {
488 clearInterval(this._connectors
[connectorID
].transactionInterval
);
492 handleResponseBootNotification(payload
) {
493 if (payload
.status
=== 'Accepted') {
494 this._heartbeatInterval
= payload
.interval
* 1000;
495 this._basicStartMessageSequence();
497 logger
.info(this._basicFormatLog() + ' Boot Notification rejected');
501 handleResponseStartTransaction(payload
, requestPayload
) {
502 // Set connector transaction related attributes
503 this._connectors
[requestPayload
.connectorId
].transactionStarted
= false;
504 this._connectors
[requestPayload
.connectorId
].idTag
= requestPayload
.idTag
;
506 if (payload
.idTagInfo
.status
=== 'Accepted') {
507 for (const connector
in this._connectors
) {
508 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
509 this._connectors
[connector
].transactionStarted
= true;
510 this._connectors
[connector
].transactionId
= payload
.transactionId
;
511 this._connectors
[connector
].lastConsumptionValue
= 0;
512 this._connectors
[connector
].lastSoC
= 0;
513 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[connector
].transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
514 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
515 const configuredMeterValueSampleInterval
= this._configuration
.configurationKey
.find((value
) => value
.key
=== 'MeterValueSampleInterval');
516 this.startMeterValues(requestPayload
.connectorId
,
517 (configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000),
522 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
523 for (const connector
in this._connectors
) {
524 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
525 this._resetTransactionOnConnector(connector
);
528 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
532 handleResponseStopTransaction(payload
, requestPayload
) {
533 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
) {
534 logger
.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload
.transactionId
+ ' response status: ' + payload
.idTagInfo
.status
);
536 logger
.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload
.transactionId
+ ' response status: Unknown');
540 handleResponseStatusNotification(payload
, requestPayload
) {
541 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload
, requestPayload
);
544 handleResponseMeterValues(payload
, requestPayload
) {
545 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
548 handleResponseHeartbeat(payload
, requestPayload
) {
549 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
552 async
handleRequest(messageId
, commandName
, commandPayload
) {
554 this._statistics
.addMessage(commandName
, true);
556 if (typeof this['handle' + commandName
] === 'function') {
559 result
= await
this['handle' + commandName
](commandPayload
);
562 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
563 // Send back response to inform backend
564 await
this.sendError(messageId
, error
);
568 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
569 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
572 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
575 async
handleGetConfiguration(commandPayload
) {
576 const configurationKey
= [];
577 const unknownKey
= [];
578 for (const configuration
of this._configuration
.configurationKey
) {
579 if (Utils
.isUndefined(configuration
.visible
)) {
580 configuration
.visible
= true;
582 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
584 if (!configuration
.visible
) {
587 configurationKey
.push({
588 key
: configuration
.key
,
589 readonly
: configuration
.readonly
,
590 value
: configuration
.value
,
599 async
handleChangeConfiguration(commandPayload
) {
600 const keyToChange
= this._configuration
.configurationKey
.find((element
) => element
.key
=== commandPayload
.key
);
601 if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
602 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
603 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
604 return Constants
.OCPP_RESPONSE_ACCEPTED
;
606 return Constants
.OCPP_RESPONSE_REJECTED
;
609 async
handleRemoteStartTransaction(commandPayload
) {
610 const transactionConnectorID
= (commandPayload
.connectorId
? commandPayload
.connectorId
: '1');
611 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
612 // Check if authorized
613 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
614 // Authorization successful start transaction
615 setTimeout(() => this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
), Constants
.START_TRANSACTION_TIMEOUT
);
616 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
617 return Constants
.OCPP_RESPONSE_ACCEPTED
;
619 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
620 return Constants
.OCPP_RESPONSE_REJECTED
;
622 // No local authorization check required => start transaction
623 setTimeout(() => this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
), Constants
.START_TRANSACTION_TIMEOUT
);
624 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
625 return Constants
.OCPP_RESPONSE_ACCEPTED
;
628 async
handleRemoteStopTransaction(commandPayload
) {
629 for (const connector
in this._connectors
) {
630 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
631 this.sendStopTransaction(commandPayload
.transactionId
, connector
);
634 return Constants
.OCPP_RESPONSE_ACCEPTED
;
637 async
sendStartTransaction(connectorID
, idTag
) {
640 connectorId
: connectorID
,
643 timestamp
: new Date().toISOString(),
645 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
647 logger
.error(this._basicFormatLog() + ' Send start transaction error: ' + error
);
648 this._resetTransactionOnConnector(connectorID
);
653 async
sendStopTransaction(transactionId
, connectorID
) {
658 timestamp
: new Date().toISOString(),
660 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
661 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[connectorID
].transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + connectorID
);
662 this.sendStatusNotification(connectorID
, 'Available');
664 logger
.error(this._basicFormatLog() + ' Send stop transaction error: ' + error
);
667 this._resetTransactionOnConnector(connectorID
);
671 // eslint-disable-next-line class-methods-use-this
672 async
sendMeterValues(connectorID
, interval
, self
) {
674 const sampledValueLcl
= {
675 timestamp
: new Date().toISOString(),
677 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
678 if (Array
.isArray(meterValuesClone
)) {
679 sampledValueLcl
.sampledValue
= meterValuesClone
;
681 sampledValueLcl
.sampledValue
= [meterValuesClone
];
683 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
684 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
685 sampledValueLcl
.sampledValue
[index
].value
= Math
.floor(Math
.random() * 100) + 1;
686 if (sampledValueLcl
.sampledValue
[index
].value
> 100) {
687 logger
.info(self
._basicFormatLog() + ' MeterValues measurand: ' +
688 (sampledValueLcl
.sampledValue
[index
].measurand
? sampledValueLcl
.sampledValue
[index
].measurand
: 'default') +
689 ', value: ' + sampledValueLcl
.sampledValue
[index
].value
);
692 // Persist previous value in connector
693 const connector
= self
._connectors
[connectorID
];
695 consumption
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
, 4);
696 if (connector
&& connector
.lastConsumptionValue
>= 0) {
697 connector
.lastConsumptionValue
+= consumption
;
699 connector
.lastConsumptionValue
= 0;
701 consumption
= Math
.round(connector
.lastConsumptionValue
* 3600 / interval
);
702 logger
.info(self
._basicFormatLog() + ' MeterValues: connectorID ' + connectorID
+ ', transaction ' + connector
.transactionId
+ ', value ' + connector
.lastConsumptionValue
);
703 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastConsumptionValue
;
704 if (sampledValueLcl
.sampledValue
[index
].value
> (self
._stationInfo
.maxPower
* 3600 / interval
) || sampledValueLcl
.sampledValue
[index
].value
< 500) {
705 logger
.info(self
._basicFormatLog() + ' MeterValues measurand: ' +
706 (sampledValueLcl
.sampledValue
[index
].measurand
? sampledValueLcl
.sampledValue
[index
].measurand
: 'default') +
707 ', value: ' + sampledValueLcl
.sampledValue
[index
].value
+ '/' + (self
._stationInfo
.maxPower
* 3600 / interval
));
713 connectorId
: connectorID
,
714 transactionId
: self
._connectors
[connectorID
].transactionId
,
715 meterValue
: [sampledValueLcl
],
717 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
719 logger
.error(self
._basicFormatLog() + ' Send MeterValues error: ' + error
);
723 async
startMeterValues(connectorID
, interval
, self
) {
724 if (!this._connectors
[connectorID
].transactionStarted
) {
725 logger
.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
726 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
727 logger
.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
729 this._connectors
[connectorID
].transactionInterval
= setInterval(async () => {
730 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
731 this._performanceObserver
.observe({
732 entryTypes
: ['function'],
734 await
sendMeterValues(connectorID
, interval
, self
);
738 hasAuthorizedTags() {
739 return Array
.isArray(this._authorizedTags
) && this._authorizedTags
.length
> 0;
743 const index
= Math
.round(Math
.floor(Math
.random() * this._authorizedTags
.length
- 1));
744 return this._authorizedTags
[index
];
747 _getConnector(number
) {
748 return this._stationInfo
.Connectors
[number
];
752 module
.exports
= ChargingStation
;