X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.js;h=be4f161380c6fad845520e4cb2b5139fe79fd621;hb=d20c21a0906551f6d22f07688ca2cd9b10bbd84b;hp=f68607863c1a1a9882d2f3be5cddf068d3a190fe;hpb=4a56deef7aeca58425c92ec27388bbe34543ad4f;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.js b/src/charging-station/ChargingStation.js index f6860786..be4f1613 100644 --- a/src/charging-station/ChargingStation.js +++ b/src/charging-station/ChargingStation.js @@ -121,12 +121,12 @@ class ChargingStation { } _getAuthorizeRemoteTxRequests() { - const authorizeRemoteTxRequests = this._configuration.configurationKey.find((configElement) => configElement.key === 'AuthorizeRemoteTxRequests'); + const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests'); return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; } _getLocalAuthListEnabled() { - const localAuthListEnabled = this._configuration.configurationKey.find((configElement) => configElement.key === 'LocalAuthListEnabled'); + const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled'); return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; } @@ -235,7 +235,6 @@ class ChargingStation { // Incoming Message case Constants.OCPP_JSON_CALL_MESSAGE: // Process the call - this._statistics.addMessage(commandName); await this.handleRequest(messageId, commandName, commandPayload); break; // Outcome Message @@ -253,7 +252,6 @@ class ChargingStation { throw new Error(`Response for unknown message id ${messageId}`); } delete this._requests[messageId]; - // this._statistics.addMessage(commandName) responseCallback(commandName, requestPayload); break; // Error Message @@ -305,7 +303,7 @@ class ChargingStation { _reconnect(error) { logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error); - // Stop heartbeat interval + // Stop heartbeat if (this._heartbeatSetInterval) { clearInterval(this._heartbeatSetInterval); this._heartbeatSetInterval = null; @@ -330,11 +328,6 @@ class ChargingStation { } } - send(command, messageType = Constants.OCPP_JSON_CALL_MESSAGE) { - // Send Message - 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); @@ -376,13 +369,14 @@ class ChargingStation { break; // Response case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: + this._statistics.addMessage(commandName); // Build response messageToSend = JSON.stringify([messageType, messageId, command]); break; // Error Message case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: // Build Message - this._statistics.addMessage(`Error ${command.code}`); + this._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`); messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]); break; } @@ -411,7 +405,7 @@ class ChargingStation { if (typeof self[responseCallbackFn] === 'function') { self[responseCallbackFn](payload, requestPayload, self); } else { - logger.debug(self._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn); + logger.debug(self._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn); } // Send the response resolve(payload); @@ -419,6 +413,7 @@ class ChargingStation { // Function that will receive the request's rejection function rejectCallback(reason) { + self._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true); // Build Exception // eslint-disable-next-line no-empty-function self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request @@ -430,27 +425,30 @@ class ChargingStation { } async _basicStartMessageSequence() { + // Start heartbeat this._startHeartbeat(this); - // build connectors + // Build connectors if (!this._connectors) { this._connectors = {}; const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors); - // determine number of customized connectors + // Determine number of customized connectors let lastConnector; for (lastConnector in connectorsConfig) { - // add connector 0, OCPP specification violation that for example KEBA have - if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0)) { + // Add connector 0, OCPP specification violation that for example KEBA have + if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) && + connectorsConfig[lastConnector]) { this._connectors[lastConnector] = connectorsConfig[lastConnector]; } } let maxConnectors = 0; if (Array.isArray(this._stationInfo.numberOfConnectors)) { - // generate some connectors + // Generate some connectors maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length]; } else { maxConnectors = this._stationInfo.numberOfConnectors; } - // generate all connectors + this._addConfigurationKey('NumberOfConnectors', maxConnectors, true); + // Generate all connectors for (let index = 1; index <= maxConnectors; index++) { const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index; this._connectors[index] = connectorsConfig[randConnectorID]; @@ -483,16 +481,19 @@ class ChargingStation { _resetTransactionOnConnector(connectorID) { this._connectors[connectorID].transactionStarted = false; this._connectors[connectorID].transactionId = null; + this._connectors[connectorID].idTag = null; this._connectors[connectorID].lastConsumptionValue = -1; this._connectors[connectorID].lastSoC = -1; - if (this._connectors[connectorID].transactionInterval) { - clearInterval(this._connectors[connectorID].transactionInterval); + if (this._connectors[connectorID].transactionSetInterval) { + clearInterval(this._connectors[connectorID].transactionSetInterval); } } handleResponseBootNotification(payload) { if (payload.status === 'Accepted') { this._heartbeatInterval = payload.interval * 1000; + this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval)); + this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false); this._basicStartMessageSequence(); } else { logger.info(this._basicFormatLog() + ' Boot Notification rejected'); @@ -500,41 +501,57 @@ class ChargingStation { } handleResponseStartTransaction(payload, requestPayload) { - // 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 (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 + ' for idTag ' + requestPayload.idTag); - this.sendStatusNotification(requestPayload.connectorId, 'Charging'); - const configuredMeterValueSampleInterval = this._configuration.configurationKey.find((value) => value.key === 'MeterValueSampleInterval'); - this.startMeterValues(requestPayload.connectorId, - configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000, - this); - } + if (this._connectors[requestPayload.connectorId].transactionStarted) { + logger.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ' by transaction ' + this._connectors[requestPayload.connectorId].transactionId); + } + + let transactionConnectorId; + for (const connector in this._connectors) { + if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { + transactionConnectorId = connector; + break; } + } + if (!transactionConnectorId) { + logger.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId); + return; + } + if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') { + this._connectors[transactionConnectorId].transactionStarted = true; + this._connectors[transactionConnectorId].transactionId = payload.transactionId; + this._connectors[transactionConnectorId].idTag = requestPayload.idTag; + this._connectors[transactionConnectorId].lastConsumptionValue = 0; + this._connectors[transactionConnectorId].lastSoC = 0; + this.sendStatusNotification(requestPayload.connectorId, 'Charging'); + logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[transactionConnectorId].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag); + const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval'); + this.startMeterValues(requestPayload.connectorId, + configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000); } 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 (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { - this._resetTransactionOnConnector(connector); - } - } + this._resetTransactionOnConnector(transactionConnectorId); this.sendStatusNotification(requestPayload.connectorId, 'Available'); } } handleResponseStopTransaction(payload, requestPayload) { - if (payload.idTagInfo && payload.idTagInfo.status) { - logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: ' + payload.idTagInfo.status); + let transactionConnectorId; + for (const connector in this._connectors) { + if (this._connectors[connector].transactionId === requestPayload.transactionId) { + transactionConnectorId = connector; + break; + } + } + if (!transactionConnectorId) { + logger.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload.transactionId); + return; + } + if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') { + this.sendStatusNotification(transactionConnectorId, 'Available'); + logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[transactionConnectorId].transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId); + this._resetTransactionOnConnector(transactionConnectorId); } else { - logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: Unknown'); + logger.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors[transactionConnectorId].transactionId + ' REJECTED with status ' + payload.idTagInfo.status); } } @@ -573,23 +590,71 @@ class ChargingStation { await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE); } + _getConfigurationKey(key) { + return this._configuration.configurationKey.find((configElement) => configElement.key === key); + } + + _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) { + const keyFound = this._getConfigurationKey(key); + if (!keyFound) { + this._configuration.configurationKey.push({ + key, + readonly, + value, + visible, + reboot, + }); + } + } + + _setConfigurationKeyValue(key, value) { + const keyFound = this._getConfigurationKey(key); + if (keyFound) { + const keyIndex = this._configuration.configurationKey.indexOf(keyFound); + this._configuration.configurationKey[keyIndex].value = value; + } + } + 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 (Utils.isEmptyArray(commandPayload.key)) { + 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, + }); } - if (!configuration.visible) { - continue; + } else { + for (const configurationKey of commandPayload.key) { + const keyFound = this._getConfigurationKey(configurationKey); + if (keyFound) { + if (Utils.isUndefined(keyFound.visible)) { + keyFound.visible = true; + } else { + keyFound.visible = Utils.convertToBoolean(configurationKey.visible); + } + if (!keyFound.visible) { + continue; + } + configurationKey.push({ + key: keyFound.key, + readonly: keyFound.readonly, + value: keyFound.value, + }); + } else { + unknownKey.push(configurationKey); + } } - configurationKey.push({ - key: configuration.key, - readonly: configuration.readonly, - value: configuration.value, - }); } return { configurationKey, @@ -598,13 +663,38 @@ class ChargingStation { } async handleChangeConfiguration(commandPayload) { - const keyToChange = this._configuration.configurationKey.find((element) => element.key === commandPayload.key); - if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) { + const keyToChange = this._getConfigurationKey(commandPayload.key); + if (!keyToChange) { + return {status: Constants.OCPP_ERROR_NOT_SUPPORTED}; + } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) { + return Constants.OCPP_RESPONSE_REJECTED; + } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) { const keyIndex = this._configuration.configurationKey.indexOf(keyToChange); this._configuration.configurationKey[keyIndex].value = commandPayload.value; + let triggerHeartbeatRestart = false; + if (keyToChange.key === 'HeartBeatInterval') { + this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value); + triggerHeartbeatRestart = true; + } + if (keyToChange.key === 'HeartbeatInterval') { + this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value); + triggerHeartbeatRestart = true; + } + if (triggerHeartbeatRestart) { + this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000; + // Stop heartbeat + if (this._heartbeatSetInterval) { + clearInterval(this._heartbeatSetInterval); + this._heartbeatSetInterval = null; + } + // Start heartbeat + this._startHeartbeat(this); + } + if (Utils.convertToBoolean(keyToChange.reboot)) { + return Constants.OCPP_RESPONSE_REBOOT_REQUIRED; + } return Constants.OCPP_RESPONSE_ACCEPTED; } - return Constants.OCPP_RESPONSE_REJECTED; } async handleRemoteStartTransaction(commandPayload) { @@ -613,7 +703,7 @@ class ChargingStation { // Check if authorized if (this._authorizedTags.find((value) => value === commandPayload.idTag)) { // Authorization successful start transaction - setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT); + this.sendStartTransactionWithTimeout(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; } @@ -621,7 +711,7 @@ class ChargingStation { return Constants.OCPP_RESPONSE_REJECTED; } // No local authorization check required => start transaction - setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT); + this.sendStartTransactionWithTimeout(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; } @@ -629,10 +719,12 @@ class ChargingStation { async handleRemoteStopTransaction(commandPayload) { for (const connector in this._connectors) { if (this._connectors[connector].transactionId === commandPayload.transactionId) { - this.sendStopTransaction(commandPayload.transactionId, connector); + this.sendStopTransaction(commandPayload.transactionId); + return Constants.OCPP_RESPONSE_ACCEPTED; } } - return Constants.OCPP_RESPONSE_ACCEPTED; + logger.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId); + return Constants.OCPP_RESPONSE_REJECTED; } async sendStartTransaction(connectorID, idTag) { @@ -646,12 +738,14 @@ class ChargingStation { 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); throw error; } } + async sendStartTransactionWithTimeout(connectorID, idTag, timeout) { + setTimeout(() => this.sendStartTransaction(connectorID, idTag), timeout); + } - async sendStopTransaction(transactionId, connectorID) { + async sendStopTransaction(transactionId) { try { const payload = { transactionId, @@ -659,18 +753,14 @@ class ChargingStation { timestamp: new Date().toISOString(), }; 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) { logger.error(this._basicFormatLog() + ' Send stop transaction error: ' + error); throw error; - } finally { - this._resetTransactionOnConnector(connectorID); } } // eslint-disable-next-line class-methods-use-this - async sendMeterValues(connectorID, interval, self) { + async sendMeterValues(connectorID, interval, self, debug = false) { try { const sampledValueLcl = { timestamp: new Date().toISOString(), @@ -682,30 +772,25 @@ class ChargingStation { sampledValueLcl.sampledValue = [meterValuesClone]; } for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) { + const connector = self._connectors[connectorID]; 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() + ' MeterValues measurand: ' + - sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' + - ', value: ' + sampledValueLcl.sampledValue[index].value); + sampledValueLcl.sampledValue[index].value = Utils.getRandomInt(100); + if (sampledValueLcl.sampledValue[index].value > 100 || debug) { + logger.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, 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, 4); + const consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval); if (connector && connector.lastConsumptionValue >= 0) { connector.lastConsumptionValue += consumption; } else { connector.lastConsumptionValue = 0; } - consumption = Math.round(connector.lastConsumptionValue * 3600 / interval); - logger.info(self._basicFormatLog() + ' MeterValues: connectorID ' + connectorID + ', transaction ' + connector.transactionId + ', value ' + connector.lastConsumptionValue); + const maxConsumption = self._stationInfo.maxPower * 3600 / interval; + logger.info(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: 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() + ' MeterValues measurand: ' + - sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' + - ', value: ' + sampledValueLcl.sampledValue[index].value + '/' + (self._stationInfo.maxPower * 3600 / interval)); + if (sampledValueLcl.sampledValue[index].value > maxConsumption || debug) { + logger.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}/${maxConsumption}`); } } } @@ -721,18 +806,20 @@ class ChargingStation { } } - async startMeterValues(connectorID, interval, self) { + async startMeterValues(connectorID, interval) { if (!this._connectors[connectorID].transactionStarted) { - logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`); + logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`); + return; } 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`); + logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`); + return; } - this._connectors[connectorID].transactionInterval = setInterval(async () => { + this._connectors[connectorID].transactionSetInterval = setInterval(async () => { const sendMeterValues = performance.timerify(this.sendMeterValues); this._performanceObserver.observe({ entryTypes: ['function'], }); - await sendMeterValues(connectorID, interval, self); + await sendMeterValues(connectorID, interval, this); }, interval); } @@ -741,7 +828,7 @@ class ChargingStation { } getRandomTagId() { - const index = Math.round(Math.floor(Math.random() * this._authorizedTags.length - 1)); + const index = Math.floor(Math.random() * this._authorizedTags.length); return this._authorizedTags[index]; }