X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.js;h=52d54958fa4e0ad003de9de88465becd944a2c35;hb=0bbcb3dc3d1b75955b816452fc0050d401e96fca;hp=6b9bfc2aa983e923e0ce175d6fd0ff725b0ff159;hpb=2d8cee5a8b6816947f4455ef53e088572c5b1671;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.js b/src/charging-station/ChargingStation.js index 6b9bfc2a..52d54958 100644 --- a/src/charging-station/ChargingStation.js +++ b/src/charging-station/ChargingStation.js @@ -4,58 +4,109 @@ const WebSocket = require('ws'); const Constants = require('../utils/Constants'); const Utils = require('../utils/Utils'); const OCPPError = require('./OcppError'); -const {v4: uuid} = require('uuid'); const AutomaticTransactionGenerator = require('./AutomaticTransactionGenerator'); const Statistics = require('../utils/Statistics'); const fs = require('fs'); const {performance, PerformanceObserver} = require('perf_hooks'); class ChargingStation { - constructor(index, stationTemplate) { - this._requests = {}; + constructor(index, stationTemplateFile) { + this._index = index; + this._stationTemplateFile = stationTemplateFile; + this._initialize(); + this._autoReconnectRetryCount = 0; this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // ms, zero for disabling + + this._requests = {}; + this._messageQueue = []; + this._isSocketRestart = false; - this._stationInfo = this._buildChargingStation(index, stationTemplate); + + this._authorizedTags = this._getAuthorizedTags(); + } + + _initialize() { + this._stationInfo = this._buildStationInfo(); + this._bootNotificationMessage = { + chargePointModel: this._stationInfo.chargePointModel, + chargePointVendor: this._stationInfo.chargePointVendor, + // chargePointSerialNumber: this._stationInfo.chargePointSerialNumber, + firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '', + }; + this._configuration = this._getConfiguration(); + this._supervisionUrl = this._getSupervisionURL(); this._statistics = new Statistics(this._stationInfo.name); this._performanceObserver = new PerformanceObserver((list) => { const entry = list.getEntries()[0]; this._statistics.logPerformance(entry, 'ChargingStation'); this._performanceObserver.disconnect(); }); - this._index = index; - this._messageQueue = []; - this._bootNotificationMessage = { - chargePointModel: this._stationInfo.chargePointModel, - chargePointVendor: this._stationInfo.chargePointVendor, - }; - this._configuration = this._getConfiguration(stationTemplate); - this._authorizationFile = this._getAuthorizationFile(stationTemplate); - this._supervisionUrl = this._getSupervisionURL(index, stationTemplate); } _basicFormatLog() { return Utils.basicFormatLog(` ${this._stationInfo.name}:`); } - // eslint-disable-next-line class-methods-use-this - _getConfiguration(stationTemplate) { - return stationTemplate.Configuration ? stationTemplate.Configuration : {}; + _getConfiguration() { + return this._stationInfo.Configuration ? this._stationInfo.Configuration : {}; } - // eslint-disable-next-line class-methods-use-this - _getAuthorizationFile(stationTemplate) { - return stationTemplate.authorizationFile ? stationTemplate.authorizationFile : ''; + _getAuthorizationFile() { + return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : ''; } - // eslint-disable-next-line class-methods-use-this - _getSupervisionURL(index, stationTemplate) { - const supervisionUrls = JSON.parse(JSON.stringify(stationTemplate.supervisionURL ? stationTemplate.supervisionURL : Configuration.getSupervisionURLs())); + _getAuthorizedTags() { + let authorizedTags = []; + const authorizationFile = this._getAuthorizationFile(); + if (authorizationFile) { + try { + // Load authorization file + const fileDescriptor = fs.openSync(authorizationFile, 'r'); + authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); + fs.closeSync(fileDescriptor); + } catch (error) { + logger.error(this._basicFormatLog() + ' Authorization file loading error: ' + error); + } + } else { + logger.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile); + } + return authorizedTags; + } + + _startAuthorizationFileMonitoring() { + // eslint-disable-next-line no-unused-vars + fs.watchFile(this._getAuthorizationFile(), (current, previous) => { + try { + logger.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload'); + // Initialize _authorizedTags + this._authorizedTags = this._getAuthorizedTags(); + } catch (error) { + logger.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error); + } + }); + } + + _startStationTemplateFileMonitoring() { + // eslint-disable-next-line no-unused-vars + fs.watchFile(this._stationTemplateFile, (current, previous) => { + try { + logger.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile + ' have changed, reload'); + // Initialize + this._initialize(); + } catch (error) { + logger.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error); + } + }); + } + + _getSupervisionURL() { + const supervisionUrls = Utils.cloneJSonDocument(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()); let indexUrl = 0; if (Array.isArray(supervisionUrls)) { - if (Configuration.getEquallySupervisionDistribution()) { - indexUrl = index % supervisionUrls.length; + if (Configuration.getDistributeStationToTenantEqually()) { + indexUrl = this._index % supervisionUrls.length; } else { // Get a random url indexUrl = Math.floor(Math.random() * supervisionUrls.length); @@ -65,55 +116,48 @@ class ChargingStation { return supervisionUrls; } - // eslint-disable-next-line class-methods-use-this - _getStationName(index, stationTemplate) { - return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + index).substr(('000000000' + index).length - 4); + _getStationName(stationTemplate) { + return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4); } _getAuthorizeRemoteTxRequests() { const authorizeRemoteTxRequests = this._configuration.configurationKey.find((configElement) => configElement.key === 'AuthorizeRemoteTxRequests'); - return authorizeRemoteTxRequests ? authorizeRemoteTxRequests.value : false; + return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; + } + + _getLocalAuthListEnabled() { + const localAuthListEnabled = this._configuration.configurationKey.find((configElement) => configElement.key === 'LocalAuthListEnabled'); + return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; } - _buildChargingStation(index, stationTemplate) { - if (Array.isArray(stationTemplate.power)) { - stationTemplate.maxPower = stationTemplate.power[Math.floor(Math.random() * stationTemplate.power.length)]; + _buildStationInfo() { + let stationTemplateFromFile; + try { + // Load template file + const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r'); + stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); + fs.closeSync(fileDescriptor); + } catch (error) { + logger.error(this._basicFormatLog() + ' Template file loading error: ' + error); + } + const stationTemplate = stationTemplateFromFile || {}; + if (Array.isArray(stationTemplateFromFile.power)) { + stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)]; } else { - stationTemplate.maxPower = stationTemplate.power; + stationTemplate.maxPower = stationTemplateFromFile.power; } - stationTemplate.name = this._getStationName(index, stationTemplate); + stationTemplate.name = this._getStationName(stationTemplateFromFile); return stationTemplate; } async start() { - logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl); this._url = this._supervisionUrl + '/' + this._stationInfo.name; this._wsConnection = new WebSocket(this._url, 'ocpp1.6'); - if (this._authorizationFile !== '') { - try { - // load file - const fileDescriptor = fs.openSync(this._authorizationFile, 'r'); - this._authorizedKeys = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); - fs.closeSync(fileDescriptor); - // get remote authorization logic - // FIXME: move to the constructor - this._authorizeRemoteTxRequests = this._getAuthorizeRemoteTxRequests(); - // monitor authorization file - // eslint-disable-next-line no-unused-vars - fs.watchFile(this._authorizationFile, (current, previous) => { - try { - // reload file - const fileDescriptor = fs.openSync(this._authorizationFile, 'r'); - this._authorizedKeys = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); - fs.closeSync(fileDescriptor); - } catch (error) { - logger.error(this._basicFormatLog() + ' Authorization file error: ' + error); - } - }); - } catch (error) { - logger.error(this._basicFormatLog() + ' Authorization file error: ' + error); - } - } + logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl); + // Monitor authorization file + this._startAuthorizationFileMonitoring(); + // Monitor station template file + this._startStationTemplateFileMonitoring(); // Handle Socket incoming messages this._wsConnection.on('message', this.onMessage.bind(this)); // Handle Socket error @@ -128,8 +172,16 @@ class ChargingStation { onOpen() { logger.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`); + if (!this._heartbeatInterval) { + // Send BootNotification + try { + this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification'); + } catch (error) { + logger.error(this._basicFormatLog() + ' Send boot notification error: ' + error); + } + } if (this._isSocketRestart) { - this.basicStartMessageSequence(); + this._basicStartMessageSequence(); if (this._messageQueue.length > 0) { this._messageQueue.forEach((message) => { if (this._wsConnection.readyState === WebSocket.OPEN) { @@ -137,13 +189,6 @@ class ChargingStation { } }); } - } else { - // At first start, send Bootnotification - try { - this.sendMessage(uuid(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification'); - } catch (error) { - logger.error(this._basicFormatLog() + ' Send boot notification error: ' + error); - } } this._autoReconnectRetryCount = 0; this._isSocketRestart = false; @@ -176,7 +221,7 @@ class ChargingStation { } onPing() { - logger.info(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server'); + logger.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server'); } async onMessage(message) { @@ -239,6 +284,25 @@ class ChargingStation { } } + // eslint-disable-next-line class-methods-use-this + async _startHeartbeat(self) { + if (self._heartbeatInterval && !self._heartbeatSetInterval) { + self._heartbeatSetInterval = setInterval(() => { + try { + const payload = { + currentTime: new Date().toISOString(), + }; + self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat'); + } catch (error) { + logger.error(self._basicFormatLog() + ' Send heartbeat error: ' + error); + } + }, self._heartbeatInterval); + logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms'); + } else { + logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat'); + } + } + _reconnect(error) { logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error); // Stop heartbeat interval @@ -246,9 +310,11 @@ class ChargingStation { clearInterval(this._heartbeatSetInterval); this._heartbeatSetInterval = null; } - // Stop the ATG - if (this._stationInfo.AutomaticTransactionGenerator.enable && this._automaticTransactionGeneration && - !this._automaticTransactionGeneration._timeToStop) { + // Stop the ATG if needed + if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) && + Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) && + this._automaticTransactionGeneration && + !this._automaticTransactionGeneration.timeToStop) { this._automaticTransactionGeneration.stop(); } if (this._autoReconnectTimeout !== 0 && @@ -266,16 +332,33 @@ class ChargingStation { send(command, messageType = Constants.OCPP_JSON_CALL_MESSAGE) { // Send Message - return this.sendMessage(uuid(), command, messageType); + return this.sendMessage(Utils.generateUUID(), command, messageType); } sendError(messageId, err) { // Check exception: only OCPP error are accepted - const error = (err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message)); + const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message); // Send error return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE); } + async sendStatusNotification(connectorId, status, errorCode = 'NoError') { + try { + const payload = { + connectorId, + errorCode, + status, + }; + await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification'); + } catch (error) { + logger.error(this._basicFormatLog() + ' Send status error: ' + error); + } + } + + async sendStatusNotificationWithTimeout(connectorId, status, errorCode = 'NoError', timeout = Constants.STATUS_NOTIFICATION_TIMEOUT) { + setTimeout(() => this.sendStatusNotification(connectorId, status, errorCode), timeout); + } + sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') { // Send a message through wsConnection const self = this; @@ -299,17 +382,11 @@ class ChargingStation { // Error Message case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: // Build Message - // eslint-disable-next-line no-case-declarations - const { - code, - message, - details, - } = command; - this._statistics.addMessage(`Error ${code}`); - messageToSend = JSON.stringify([messageType, messageId, code, message, details]); + this._statistics.addMessage(`Error ${command.code}`); + messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]); break; } - // Check if wsConnection in ready + // Check if wsConnection is ready if (this._wsConnection.readyState === WebSocket.OPEN) { // Yes: Send Message this._wsConnection.send(messageToSend); @@ -334,7 +411,7 @@ class ChargingStation { if (typeof self[responseCallbackFn] === 'function') { self[responseCallbackFn](payload, requestPayload, self); } else { - // logger.error(this._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn) + logger.debug(self._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn); } // Send the response resolve(payload); @@ -352,22 +429,17 @@ class ChargingStation { }); } - handleResponseBootNotification(payload) { - if (payload.status === 'Accepted') { - this._heartbeatInterval = payload.interval * 1000; - this.basicStartMessageSequence(); - } - } - - async basicStartMessageSequence() { + async _basicStartMessageSequence() { this._startHeartbeat(this); - if (!this._connectors) { // build connectors + // build connectors + if (!this._connectors) { this._connectors = {}; - const connectorsConfig = JSON.parse(JSON.stringify(this._stationInfo.Connectors)); + const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors); // determine number of customized connectors let lastConnector; for (lastConnector in connectorsConfig) { - if (lastConnector === 0 && this._stationInfo.usedConnectorId0) { + // add connector 0, OCPP specification violation that for example KEBA have + if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0)) { this._connectors[lastConnector] = connectorsConfig[lastConnector]; } } @@ -380,7 +452,7 @@ class ChargingStation { } // generate all connectors for (let index = 1; index <= maxConnectors; index++) { - const randConnectorID = (this._stationInfo.randomConnectors ? Utils.getRandomInt(lastConnector, 1) : index); + const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index; this._connectors[index] = connectorsConfig[randConnectorID]; } } @@ -388,48 +460,69 @@ class ChargingStation { for (const connector in this._connectors) { if (!this._connectors[connector].transactionStarted) { if (this._connectors[connector].bootStatus) { - setTimeout(() => this.sendStatusNotification(connector, this._connectors[connector].bootStatus), 500); + this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus); } else { - setTimeout(() => this.sendStatusNotification(connector, 'Available'), 500); + this.sendStatusNotificationWithTimeout(connector, 'Available'); } } else { - setTimeout(() => this.sendStatusNotification(connector, 'Charging'), 500); + this.sendStatusNotificationWithTimeout(connector, 'Charging'); } } - if (this._stationInfo.AutomaticTransactionGenerator.enable) { + if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) { if (!this._automaticTransactionGeneration) { this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this); } - this._automaticTransactionGeneration.start(); + if (this._automaticTransactionGeneration.timeToStop) { + this._automaticTransactionGeneration.start(); + } } this._statistics.start(); } + _resetTransactionOnConnector(connectorID) { + this._connectors[connectorID].transactionStarted = false; + this._connectors[connectorID].transactionId = null; + this._connectors[connectorID].lastConsumptionValue = -1; + this._connectors[connectorID].lastSoC = -1; + if (this._connectors[connectorID].transactionInterval) { + clearInterval(this._connectors[connectorID].transactionInterval); + } + } + + handleResponseBootNotification(payload) { + if (payload.status === 'Accepted') { + this._heartbeatInterval = payload.interval * 1000; + this._basicStartMessageSequence(); + } else { + logger.info(this._basicFormatLog() + ' Boot Notification rejected'); + } + } + handleResponseStartTransaction(payload, requestPayload) { - this._connectors[requestPayload.connectorId] = { - transactionStarted: false, - idTag: requestPayload.idTag, - }; + // Set connector transaction related attributes + this._connectors[requestPayload.connectorId].transactionStarted = false; + this._connectors[requestPayload.connectorId].idTag = requestPayload.idTag; + if (payload.idTagInfo.status === 'Accepted') { for (const connector in this._connectors) { - if (connector === requestPayload.connectorId) { + if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { this._connectors[connector].transactionStarted = true; this._connectors[connector].transactionId = payload.transactionId; this._connectors[connector].lastConsumptionValue = 0; this._connectors[connector].lastSoC = 0; - logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connector].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId); + logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connector].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag); this.sendStatusNotification(requestPayload.connectorId, 'Charging'); - const configuredMeterInterval = this._configuration.configurationKey.find((value) => value.key === 'meterValueInterval'); + const configuredMeterValueSampleInterval = this._configuration.configurationKey.find((value) => value.key === 'MeterValueSampleInterval'); this.startMeterValues(requestPayload.connectorId, - (configuredMeterInterval ? configuredMeterInterval.value * 1000 : 60000), - this); + configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000, + this); } } } else { logger.error(this._basicFormatLog() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag); for (const connector in this._connectors) { - if (connector === requestPayload.connectorId) { + if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { this._resetTransactionOnConnector(connector); } } @@ -437,36 +530,24 @@ class ChargingStation { } } - async sendStatusNotification(connectorId, status, errorCode = 'NoError') { - try { - const payload = { - connectorId, - errorCode, - status, - }; - await this.sendMessage(uuid(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification'); - } catch (error) { - logger.error(this._basicFormatLog() + ' Send status error: ' + error); + handleResponseStopTransaction(payload, requestPayload) { + if (payload.idTagInfo && payload.idTagInfo.status) { + logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: ' + payload.idTagInfo.status); + } else { + logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: Unknown'); } } - // eslint-disable-next-line class-methods-use-this - async _startHeartbeat(self) { - if (self._heartbeatInterval && !self._heartbeatSetInterval) { - logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms'); - self._heartbeatSetInterval = setInterval(() => { - try { - const payload = { - currentTime: new Date().toISOString(), - }; - self.sendMessage(uuid(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat'); - } catch (error) { - logger.error(self._basicFormatLog() + ' Send heartbeat error: ' + error); - } - }, self._heartbeatInterval); - } else { - logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat'); - } + handleResponseStatusNotification(payload, requestPayload) { + logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload); + } + + handleResponseMeterValues(payload, requestPayload) { + logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload); + } + + handleResponseHeartbeat(payload, requestPayload) { + logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload); } async handleRequest(messageId, commandName, commandPayload) { @@ -480,45 +561,77 @@ class ChargingStation { } catch (error) { // Log logger.error(this._basicFormatLog() + ' Handle request error: ' + error); - // Send back response to inform back end + // Send back response to inform backend await this.sendError(messageId, error); } } else { - // Throw Exception + // Throw exception await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {})); throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`); } - // Send Response + // Send response await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE); } - async handleGetConfiguration() { - return this._configuration; + async handleGetConfiguration(commandPayload) { + const configurationKey = []; + const unknownKey = []; + for (const configuration of this._configuration.configurationKey) { + if (Utils.isUndefined(configuration.visible)) { + configuration.visible = true; + } else { + configuration.visible = Utils.convertToBoolean(configuration.visible); + } + if (!configuration.visible) { + continue; + } + configurationKey.push({ + key: configuration.key, + readonly: configuration.readonly, + value: configuration.value, + }); + } + return { + configurationKey, + unknownKey, + }; } async handleChangeConfiguration(commandPayload) { const keyToChange = this._configuration.configurationKey.find((element) => element.key === commandPayload.key); - if (keyToChange) { - keyToChange.value = commandPayload.value; + if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) { + const keyIndex = this._configuration.configurationKey.indexOf(keyToChange); + this._configuration.configurationKey[keyIndex].value = commandPayload.value; return Constants.OCPP_RESPONSE_ACCEPTED; } return Constants.OCPP_RESPONSE_REJECTED; } async handleRemoteStartTransaction(commandPayload) { - const transactionConnectorID = (commandPayload.connectorId ? commandPayload.connectorId : '1'); - if (this.isAuthorizationRequested() && this._authorizeRemoteTxRequests) { + const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1'; + if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) { // Check if authorized - if (this._authorizedKeys.find((value) => value === commandPayload.idTag)) { + if (this._authorizedTags.find((value) => value === commandPayload.idTag)) { // Authorization successful start transaction - setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), 500); + setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT); + logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag); return Constants.OCPP_RESPONSE_ACCEPTED; } - // Start authorization checks + logger.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag); return Constants.OCPP_RESPONSE_REJECTED; } // No local authorization check required => start transaction - setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), 500); + setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT); + logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag); + return Constants.OCPP_RESPONSE_ACCEPTED; + } + + async handleRemoteStopTransaction(commandPayload) { + for (const connector in this._connectors) { + if (this._connectors[connector].transactionId === commandPayload.transactionId) { + this.sendStopTransaction(commandPayload.transactionId, connector); + } + } return Constants.OCPP_RESPONSE_ACCEPTED; } @@ -530,7 +643,7 @@ class ChargingStation { meterStart: 0, timestamp: new Date().toISOString(), }; - return await this.sendMessage(uuid(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction'); + return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction'); } catch (error) { logger.error(this._basicFormatLog() + ' Send start transaction error: ' + error); this._resetTransactionOnConnector(connectorID); @@ -545,7 +658,7 @@ class ChargingStation { meterStop: 0, timestamp: new Date().toISOString(), }; - await this.sendMessage(uuid(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction'); + await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction'); logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connectorID].transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + connectorID); this.sendStatusNotification(connectorID, 'Available'); } catch (error) { @@ -556,23 +669,13 @@ class ChargingStation { } } - _resetTransactionOnConnector(connectorID) { - this._connectors[connectorID].transactionStarted = false; - this._connectors[connectorID].transactionId = null; - this._connectors[connectorID].lastConsumptionValue = -1; - this._connectors[connectorID].lastSoC = -1; - if (this._connectors[connectorID].transactionInterval) { - clearInterval(this._connectors[connectorID].transactionInterval); - } - } - // eslint-disable-next-line class-methods-use-this async sendMeterValues(connectorID, interval, self) { try { const sampledValueLcl = { timestamp: new Date().toISOString(), }; - const meterValuesClone = JSON.parse(JSON.stringify(self._getConnector(connectorID).MeterValues)); + const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorID).MeterValues); if (Array.isArray(meterValuesClone)) { sampledValueLcl.sampledValue = meterValuesClone; } else { @@ -582,27 +685,27 @@ class ChargingStation { if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') { sampledValueLcl.sampledValue[index].value = Math.floor(Math.random() * 100) + 1; if (sampledValueLcl.sampledValue[index].value > 100) { - logger.info(self._basicFormatLog() + ' Meter type: ' + - (sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'default') + - ' value: ' + sampledValueLcl.sampledValue[index].value); + logger.info(self._basicFormatLog() + ' MeterValues measurand: ' + + sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' + + ', value: ' + sampledValueLcl.sampledValue[index].value); } } else { // Persist previous value in connector const connector = self._connectors[connectorID]; let consumption; - consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval, 3); + consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval, 4); if (connector && connector.lastConsumptionValue >= 0) { connector.lastConsumptionValue += consumption; } else { connector.lastConsumptionValue = 0; } consumption = Math.round(connector.lastConsumptionValue * 3600 / interval); - logger.info(self._basicFormatLog() + ' ConnectorID ' + connectorID + ' transaction ' + connector.transactionId + ' value ' + connector.lastConsumptionValue); + logger.info(self._basicFormatLog() + ' MeterValues: connectorID ' + connectorID + ', transaction ' + connector.transactionId + ', value ' + connector.lastConsumptionValue); sampledValueLcl.sampledValue[index].value = connector.lastConsumptionValue; if (sampledValueLcl.sampledValue[index].value > (self._stationInfo.maxPower * 3600 / interval) || sampledValueLcl.sampledValue[index].value < 500) { - logger.info(self._basicFormatLog() + ' Meter type: ' + - (sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'default') + - ' value: ' + sampledValueLcl.sampledValue[index].value + '/' + (self._stationInfo.maxPower * 3600 / interval)); + logger.info(self._basicFormatLog() + ' MeterValues measurand: ' + + sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' + + ', value: ' + sampledValueLcl.sampledValue[index].value + '/' + (self._stationInfo.maxPower * 3600 / interval)); } } } @@ -612,18 +715,18 @@ class ChargingStation { transactionId: self._connectors[connectorID].transactionId, meterValue: [sampledValueLcl], }; - await self.sendMessage(uuid(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues'); + await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues'); } catch (error) { - logger.error(self._basicFormatLog() + ' Send meter values error: ' + error); + logger.error(self._basicFormatLog() + ' Send MeterValues error: ' + error); } } async startMeterValues(connectorID, interval, self) { - // if (!this._connectors[connectorID].transactionStarted) { - // logger.debug(`${self._basicFormatLog()} Trying to start meter values on connector ID ${connectorID} with no transaction`); - // } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) { - // logger.debug(`${self._basicFormatLog()} Trying to start meter values on connector ID ${connectorID} with no transaction id`); - // } + if (!this._connectors[connectorID].transactionStarted) { + logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`); + } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) { + logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`); + } this._connectors[connectorID].transactionInterval = setInterval(async () => { const sendMeterValues = performance.timerify(this.sendMeterValues); this._performanceObserver.observe({ @@ -633,22 +736,13 @@ class ChargingStation { }, interval); } - async handleRemoteStopTransaction(commandPayload) { - for (const connector in this._connectors) { - if (this._connectors[connector].transactionId === commandPayload.transactionId) { - this.sendStopTransaction(commandPayload.transactionId, connector); - } - } - return Constants.OCPP_RESPONSE_ACCEPTED; - } - - isAuthorizationRequested() { - return this._authorizedKeys && this._authorizedKeys.length > 0; + hasAuthorizedTags() { + return Array.isArray(this._authorizedTags) && this._authorizedTags.length > 0; } getRandomTagId() { - const index = Math.round(Math.floor(Math.random() * this._authorizedKeys.length - 1)); - return this._authorizedKeys[index]; + const index = Math.round(Math.floor(Math.random() * this._authorizedTags.length - 1)); + return this._authorizedTags[index]; } _getConnector(number) {