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;
29 this._stationInfo
= this._buildStationInfo();
30 this._bootNotificationMessage
= {
31 chargePointModel
: this._stationInfo
.chargePointModel
,
32 chargePointVendor
: this._stationInfo
.chargePointVendor
,
34 this._configuration
= this._getConfiguration();
35 this._authorizedTags
= this._getAuthorizedTags();
36 this._supervisionUrl
= this._getSupervisionURL();
37 this._statistics
= new Statistics(this._stationInfo
.name
);
38 this._performanceObserver
= new PerformanceObserver((list
) => {
39 const entry
= list
.getEntries()[0];
40 this._statistics
.logPerformance(entry
, 'ChargingStation');
41 this._performanceObserver
.disconnect();
46 return Utils
.basicFormatLog(` ${this._stationInfo.name}:`);
50 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
53 _getAuthorizationFile() {
54 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
57 _getAuthorizedTags() {
58 let authorizedTags
= [];
59 const authorizationFile
= this._getAuthorizationFile();
60 if (authorizationFile
) {
62 // Load authorization file
63 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
64 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
65 fs
.closeSync(fileDescriptor
);
67 logger
.error(this._basicFormatLog() + ' Authorization file loading error: ' + error
);
70 logger
.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile
);
72 return authorizedTags
;
75 _startAuthorizationFileMonitoring() {
76 // eslint-disable-next-line no-unused-vars
77 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
79 logger
.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
80 // Initialize _authorizedTags
81 this._authorizedTags
= this._getAuthorizedTags();
83 logger
.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error
);
88 _startStationTemplateFileMonitoring() {
89 // eslint-disable-next-line no-unused-vars
90 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
92 logger
.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
96 logger
.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error
);
101 _getSupervisionURL() {
102 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
104 if (Array
.isArray(supervisionUrls
)) {
105 if (Configuration
.getDistributeStationToTenantEqually()) {
106 indexUrl
= this._index
% supervisionUrls
.length
;
109 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
111 return supervisionUrls
[indexUrl
];
113 return supervisionUrls
;
116 _getStationName(stationTemplate
) {
117 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
120 _getAuthorizeRemoteTxRequests() {
121 const authorizeRemoteTxRequests
= this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== 'AuthorizeRemoteTxRequests');
122 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
125 _getLocalAuthListEnabled() {
126 const localAuthListEnabled
= this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== 'LocalAuthListEnabled');
127 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
130 _buildStationInfo() {
131 let stationTemplateFromFile
;
133 // Load template file
134 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
135 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
136 fs
.closeSync(fileDescriptor
);
138 logger
.error(this._basicFormatLog() + ' Template file loading error: ' + error
);
140 const stationTemplate
= stationTemplateFromFile
|| {};
141 if (Array
.isArray(stationTemplateFromFile
.power
)) {
142 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
144 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
146 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
147 return stationTemplate
;
151 logger
.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl
);
152 // Monitor authorization file
153 this._startAuthorizationFileMonitoring();
154 // Monitor station template file
155 this._startStationTemplateFileMonitoring();
156 this._url
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
157 this._wsConnection
= new WebSocket(this._url
, 'ocpp1.6');
158 // Handle Socket incoming messages
159 this._wsConnection
.on('message', this.onMessage
.bind(this));
160 // Handle Socket error
161 this._wsConnection
.on('error', this.onError
.bind(this));
162 // Handle Socket close
163 this._wsConnection
.on('close', this.onClose
.bind(this));
164 // Handle Socket opening connection
165 this._wsConnection
.on('open', this.onOpen
.bind(this));
166 // Handle Socket ping
167 this._wsConnection
.on('ping', this.onPing
.bind(this));
171 logger
.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`);
172 if (this._isSocketRestart
) {
173 this._basicStartMessageSequence();
174 if (this._messageQueue
.length
> 0) {
175 this._messageQueue
.forEach((message
) => {
176 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
177 this._wsConnection
.send(message
);
182 // At first start, send BootNotification
184 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
186 logger
.error(this._basicFormatLog() + ' Send boot notification error: ' + error
);
189 this._autoReconnectRetryCount
= 0;
190 this._isSocketRestart
= false;
196 this._isSocketRestart
= true;
197 this._reconnect(error
);
200 logger
.error(this._basicFormatLog() + ' Socket error: ' + error
);
207 case 1000: // Normal close
209 logger
.info(this._basicFormatLog() + ' Socket normally closed ' + error
);
210 this._autoReconnectRetryCount
= 0;
212 default: // Abnormal close
213 this._isSocketRestart
= true;
214 this._reconnect(error
);
220 logger
.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
223 async
onMessage(message
) {
224 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
227 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
229 // Check the Type of message
230 switch (messageType
) {
232 case Constants
.OCPP_JSON_CALL_MESSAGE
:
234 this._statistics
.addMessage(commandName
);
235 await
this.handleRequest(messageId
, commandName
, commandPayload
);
238 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
240 // eslint-disable-next-line no-case-declarations
241 let responseCallback
; let requestPayload
;
242 if (Utils
.isIterable(this._requests
[messageId
])) {
243 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
245 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
247 if (!responseCallback
) {
249 throw new Error(`Response for unknown message id ${messageId}`);
251 delete this._requests
[messageId
];
252 // this._statistics.addMessage(commandName)
253 responseCallback(commandName
, requestPayload
);
256 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
257 if (!this._requests
[messageId
]) {
259 throw new Error(`Error for unknown message id ${messageId}`);
261 // eslint-disable-next-line no-case-declarations
263 if (Utils
.isIterable(this._requests
[messageId
])) {
264 [, rejectCallback
] = this._requests
[messageId
];
266 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
268 delete this._requests
[messageId
];
269 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
273 throw new Error(`Wrong message type ${messageType}`);
277 logger
.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message
, error
, this._requests
[messageId
]);
279 // await this.sendError(messageId, error);
283 // eslint-disable-next-line class-methods-use-this
284 async
_startHeartbeat(self
) {
285 if (self
._heartbeatInterval
&& !self
._heartbeatSetInterval
) {
286 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
287 self
._heartbeatSetInterval
= setInterval(() => {
290 currentTime
: new Date().toISOString(),
292 self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
294 logger
.error(self
._basicFormatLog() + ' Send heartbeat error: ' + error
);
296 }, self
._heartbeatInterval
);
298 logger
.error(self
._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
303 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
304 // Stop heartbeat interval
305 if (this._heartbeatSetInterval
) {
306 clearInterval(this._heartbeatSetInterval
);
307 this._heartbeatSetInterval
= null;
310 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&& this._automaticTransactionGeneration
&&
311 !this._automaticTransactionGeneration
._timeToStop
) {
312 this._automaticTransactionGeneration
.stop();
314 if (this._autoReconnectTimeout
!== 0 &&
315 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
316 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
317 this._autoReconnectRetryCount
++;
319 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
321 }, this._autoReconnectTimeout
);
322 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
323 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
327 send(command
, messageType
= Constants
.OCPP_JSON_CALL_MESSAGE
) {
329 return this.sendMessage(Utils
.generateUUID(), command
, messageType
);
332 sendError(messageId
, err
) {
333 // Check exception: only OCPP error are accepted
334 const error
= (err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
));
336 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
339 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
346 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
348 logger
.error(this._basicFormatLog() + ' Send status error: ' + error
);
352 async
sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
353 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
356 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
357 // Send a message through wsConnection
360 return new Promise((resolve
, reject
) => {
363 switch (messageType
) {
365 case Constants
.OCPP_JSON_CALL_MESSAGE
:
366 this._statistics
.addMessage(commandName
);
368 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
369 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
372 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
374 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
377 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
379 this._statistics
.addMessage(`Error ${command.code}`);
380 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
383 // Check if wsConnection is ready
384 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
386 this._wsConnection
.send(messageToSend
);
388 // Buffer message until connection is back
389 this._messageQueue
.push(messageToSend
);
392 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
395 } else if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
396 // Send timeout in case connection is open otherwise wait for ever
397 // FIXME: Handle message on timeout
398 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
401 // Function that will receive the request's response
402 function responseCallback(payload
, requestPayload
) {
403 self
._statistics
.addMessage(commandName
, true);
404 const responseCallbackFn
= 'handleResponse' + commandName
;
405 if (typeof self
[responseCallbackFn
] === 'function') {
406 self
[responseCallbackFn
](payload
, requestPayload
, self
);
408 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn
);
414 // Function that will receive the request's rejection
415 function rejectCallback(reason
) {
417 // eslint-disable-next-line no-empty-function
418 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
419 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
426 async
_basicStartMessageSequence() {
427 this._startHeartbeat(this);
429 if (!this._connectors
) {
430 this._connectors
= {};
431 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
432 // determine number of customized connectors
434 for (lastConnector
in connectorsConfig
) {
435 // add connector 0, OCPP specification violation that for example KEBA have
436 if (Utils
.convertToInt(lastConnector
) === 0 && this._stationInfo
.useConnectorId0
) {
437 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
440 let maxConnectors
= 0;
441 if (Array
.isArray(this._stationInfo
.numberOfConnectors
)) {
442 // generate some connectors
443 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
445 maxConnectors
= this._stationInfo
.numberOfConnectors
;
447 // generate all connectors
448 for (let index
= 1; index
<= maxConnectors
; index
++) {
449 const randConnectorID
= this._stationInfo
.randomConnectors
? Utils
.getRandomInt(maxConnectors
, 1) : index
;
450 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
454 for (const connector
in this._connectors
) {
455 if (!this._connectors
[connector
].transactionStarted
) {
456 if (this._connectors
[connector
].bootStatus
) {
457 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
459 this.sendStatusNotificationWithTimeout(connector
, 'Available');
462 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
466 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
) {
467 if (!this._automaticTransactionGeneration
) {
468 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
470 this._automaticTransactionGeneration
.start();
472 this._statistics
.start();
475 _resetTransactionOnConnector(connectorID
) {
476 this._connectors
[connectorID
].transactionStarted
= false;
477 this._connectors
[connectorID
].transactionId
= null;
478 this._connectors
[connectorID
].lastConsumptionValue
= -1;
479 this._connectors
[connectorID
].lastSoC
= -1;
480 if (this._connectors
[connectorID
].transactionInterval
) {
481 clearInterval(this._connectors
[connectorID
].transactionInterval
);
485 handleResponseBootNotification(payload
) {
486 if (payload
.status
=== 'Accepted') {
487 this._heartbeatInterval
= payload
.interval
* 1000;
488 this._basicStartMessageSequence();
490 logger
.info(this._basicFormatLog() + ' Boot Notification rejected');
494 handleResponseStartTransaction(payload
, requestPayload
) {
495 // Reset connector transaction related attributes
496 this._connectors
[requestPayload
.connectorId
].transactionStarted
= false;
497 this._connectors
[requestPayload
.connectorId
].idTag
= requestPayload
.idTag
;
499 if (payload
.idTagInfo
.status
=== 'Accepted') {
500 for (const connector
in this._connectors
) {
501 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
502 this._connectors
[connector
].transactionStarted
= true;
503 this._connectors
[connector
].transactionId
= payload
.transactionId
;
504 this._connectors
[connector
].lastConsumptionValue
= 0;
505 this._connectors
[connector
].lastSoC
= 0;
506 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[connector
].transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
507 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
508 const configuredMeterValueSampleInterval
= this._configuration
.configurationKey
.find((value
) => value
.key
=== 'MeterValueSampleInterval');
509 this.startMeterValues(requestPayload
.connectorId
,
510 (configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000),
515 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
516 for (const connector
in this._connectors
) {
517 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
518 this._resetTransactionOnConnector(connector
);
521 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
525 handleResponseStatusNotification(payload
) {
526 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j', payload
);
529 handleResponseMeterValues(payload
) {
530 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j', payload
);
533 handleResponseHeartbeat(payload
) {
534 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j', payload
);
537 async
handleRequest(messageId
, commandName
, commandPayload
) {
539 this._statistics
.addMessage(commandName
, true);
541 if (typeof this['handle' + commandName
] === 'function') {
544 result
= await
this['handle' + commandName
](commandPayload
);
547 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
548 // Send back response to inform back end
549 await
this.sendError(messageId
, error
);
553 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
554 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
557 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
560 async
handleGetConfiguration() {
561 return this._configuration
;
564 async
handleChangeConfiguration(commandPayload
) {
565 const keyToChange
= this._configuration
.configurationKey
.find((element
) => element
.key
=== commandPayload
.key
);
566 if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
567 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
568 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
569 return Constants
.OCPP_RESPONSE_ACCEPTED
;
571 return Constants
.OCPP_RESPONSE_REJECTED
;
574 async
handleRemoteStartTransaction(commandPayload
) {
575 const transactionConnectorID
= (commandPayload
.connectorId
? commandPayload
.connectorId
: '1');
576 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
577 // Check if authorized
578 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
579 // Authorization successful start transaction
580 setTimeout(() => this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
), Constants
.START_TRANSACTION_TIMEOUT
);
581 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
582 return Constants
.OCPP_RESPONSE_ACCEPTED
;
584 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
585 return Constants
.OCPP_RESPONSE_REJECTED
;
587 // No local authorization check required => start transaction
588 setTimeout(() => this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
), Constants
.START_TRANSACTION_TIMEOUT
);
589 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
590 return Constants
.OCPP_RESPONSE_ACCEPTED
;
593 async
handleRemoteStopTransaction(commandPayload
) {
594 for (const connector
in this._connectors
) {
595 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
596 this.sendStopTransaction(commandPayload
.transactionId
, connector
);
599 return Constants
.OCPP_RESPONSE_ACCEPTED
;
602 async
sendStartTransaction(connectorID
, idTag
) {
605 connectorId
: connectorID
,
608 timestamp
: new Date().toISOString(),
610 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
612 logger
.error(this._basicFormatLog() + ' Send start transaction error: ' + error
);
613 this._resetTransactionOnConnector(connectorID
);
618 async
sendStopTransaction(transactionId
, connectorID
) {
623 timestamp
: new Date().toISOString(),
625 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
626 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[connectorID
].transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + connectorID
);
627 this.sendStatusNotification(connectorID
, 'Available');
629 logger
.error(this._basicFormatLog() + ' Send stop transaction error: ' + error
);
632 this._resetTransactionOnConnector(connectorID
);
636 // eslint-disable-next-line class-methods-use-this
637 async
sendMeterValues(connectorID
, interval
, self
) {
639 const sampledValueLcl
= {
640 timestamp
: new Date().toISOString(),
642 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
643 if (Array
.isArray(meterValuesClone
)) {
644 sampledValueLcl
.sampledValue
= meterValuesClone
;
646 sampledValueLcl
.sampledValue
= [meterValuesClone
];
648 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
649 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
650 sampledValueLcl
.sampledValue
[index
].value
= Math
.floor(Math
.random() * 100) + 1;
651 if (sampledValueLcl
.sampledValue
[index
].value
> 100) {
652 logger
.info(self
._basicFormatLog() + ' Meter type: ' +
653 (sampledValueLcl
.sampledValue
[index
].measurand
? sampledValueLcl
.sampledValue
[index
].measurand
: 'default') +
654 ', value: ' + sampledValueLcl
.sampledValue
[index
].value
);
657 // Persist previous value in connector
658 const connector
= self
._connectors
[connectorID
];
660 consumption
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
, 4);
661 if (connector
&& connector
.lastConsumptionValue
>= 0) {
662 connector
.lastConsumptionValue
+= consumption
;
664 connector
.lastConsumptionValue
= 0;
666 consumption
= Math
.round(connector
.lastConsumptionValue
* 3600 / interval
);
667 logger
.info(self
._basicFormatLog() + ' ConnectorID ' + connectorID
+ ' transaction ' + connector
.transactionId
+ ' value ' + connector
.lastConsumptionValue
);
668 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastConsumptionValue
;
669 if (sampledValueLcl
.sampledValue
[index
].value
> (self
._stationInfo
.maxPower
* 3600 / interval
) || sampledValueLcl
.sampledValue
[index
].value
< 500) {
670 logger
.info(self
._basicFormatLog() + ' Meter type: ' +
671 (sampledValueLcl
.sampledValue
[index
].measurand
? sampledValueLcl
.sampledValue
[index
].measurand
: 'default') +
672 ', value: ' + sampledValueLcl
.sampledValue
[index
].value
+ '/' + (self
._stationInfo
.maxPower
* 3600 / interval
));
678 connectorId
: connectorID
,
679 transactionId
: self
._connectors
[connectorID
].transactionId
,
680 meterValue
: [sampledValueLcl
],
682 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
684 logger
.error(self
._basicFormatLog() + ' Send meter values error: ' + error
);
688 async
startMeterValues(connectorID
, interval
, self
) {
689 if (!this._connectors
[connectorID
].transactionStarted
) {
690 logger
.debug(`${self._basicFormatLog()} Trying to start meter values on connector ID ${connectorID} with no transaction started`);
691 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
692 logger
.debug(`${self._basicFormatLog()} Trying to start meter values on connector ID ${connectorID} with no transaction id`);
694 this._connectors
[connectorID
].transactionInterval
= setInterval(async () => {
695 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
696 this._performanceObserver
.observe({
697 entryTypes
: ['function'],
699 await
sendMeterValues(connectorID
, interval
, self
);
703 hasAuthorizedTags() {
704 return Array
.isArray(this._authorizedTags
) && this._authorizedTags
.length
> 0;
708 const index
= Math
.round(Math
.floor(Math
.random() * this._authorizedTags
.length
- 1));
709 return this._authorizedTags
[index
];
712 _getConnector(number
) {
713 return this._stationInfo
.Connectors
[number
];
717 module
.exports
= ChargingStation
;