this._messageQueue = [];
this._isSocketRestart = false;
+
+ this._authorizedTags = this._loadAndGetAuthorizedTags();
}
_initialize() {
this._bootNotificationMessage = {
chargePointModel: this._stationInfo.chargePointModel,
chargePointVendor: this._stationInfo.chargePointVendor,
+ chargePointSerialNumber: this._stationInfo.chargePointSerialNumberPrefix ? this._stationInfo.chargePointSerialNumberPrefix : '',
+ firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '',
};
this._configuration = this._getConfiguration();
- this._authorizedTags = this._getAuthorizedTags();
this._supervisionUrl = this._getSupervisionURL();
this._statistics = new Statistics(this._stationInfo.name);
this._performanceObserver = new PerformanceObserver((list) => {
return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : '';
}
- _getAuthorizedTags() {
+ _loadAndGetAuthorizedTags() {
let authorizedTags = [];
const authorizationFile = this._getAuthorizationFile();
if (authorizationFile) {
try {
logger.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
// Initialize _authorizedTags
- this._authorizedTags = this._getAuthorizedTags();
+ this._authorizedTags = this._loadAndGetAuthorizedTags();
} catch (error) {
logger.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error);
}
}
_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;
}
}
async start() {
+ this._url = this._supervisionUrl + '/' + this._stationInfo.name;
+ this._wsConnection = new WebSocket(this._url, 'ocpp1.6');
logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl);
// Monitor authorization file
this._startAuthorizationFileMonitoring();
// Monitor station template file
this._startStationTemplateFileMonitoring();
- this._url = this._supervisionUrl + '/' + this._stationInfo.name;
- this._wsConnection = new WebSocket(this._url, 'ocpp1.6');
// Handle Socket incoming messages
this._wsConnection.on('message', this.onMessage.bind(this));
// Handle Socket error
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();
if (this._messageQueue.length > 0) {
}
});
}
- } else {
- // At first start, 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);
- }
}
this._autoReconnectRetryCount = 0;
this._isSocketRestart = false;
// 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 = {
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');
}
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 &&
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);
}
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);
async _basicStartMessageSequence() {
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 && 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 = this._stationInfo.randomConnectors ? Utils.getRandomInt(maxConnectors, 1) : index;
+ const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index;
this._connectors[index] = connectorsConfig[randConnectorID];
}
}
}
}
- 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();
}
handleResponseBootNotification(payload) {
if (payload.status === 'Accepted') {
this._heartbeatInterval = payload.interval * 1000;
+ this._addConfigurationKey('HeartBeatInterval', this._heartbeatInterval / 1000);
+ this._addConfigurationKey('HeartbeatInterval', this._heartbeatInterval / 1000, false, false);
this._basicStartMessageSequence();
} else {
logger.info(this._basicFormatLog() + ' Boot Notification rejected');
}
handleResponseStartTransaction(payload, requestPayload) {
- // Reset connector transaction related attributes
+ // Set connector transaction related attributes
this._connectors[requestPayload.connectorId].transactionStarted = false;
this._connectors[requestPayload.connectorId].idTag = requestPayload.idTag;
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');
+ const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
this.startMeterValues(requestPayload.connectorId,
- (configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000),
- this);
+ configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000,
+ this);
}
}
} else {
}
}
- handleResponseStatusNotification(payload) {
- logger.debug(this._basicFormatLog() + ' Status notification response received: %j', payload);
+ 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');
+ }
+ }
+
+ handleResponseStatusNotification(payload, requestPayload) {
+ logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload);
}
- handleResponseMeterValues(payload) {
- logger.debug(this._basicFormatLog() + ' MeterValues response received: %j', payload);
+ handleResponseMeterValues(payload, requestPayload) {
+ logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
}
- handleResponseHeartbeat(payload) {
- logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j', payload);
+ handleResponseHeartbeat(payload, requestPayload) {
+ logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
}
async handleRequest(messageId, commandName, commandPayload) {
} 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 {
await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE);
}
- async handleGetConfiguration() {
- return this._configuration;
+ _getConfigurationKey(key) {
+ return this._configuration.configurationKey.find((configElement) => configElement.key === key);
+ }
+
+ _addConfigurationKey(key, value, readonly = false, visible = true) {
+ const keyFound = this._getConfigurationKey(key);
+ if (!keyFound) {
+ this._configuration.configurationKey.push({
+ key,
+ readonly,
+ value,
+ visible,
+ });
+ }
+ }
+
+ _setConfigurationKeyValue(key, value) {
+ const keyFound = this._getConfigurationKey(key);
+ if (keyFound) {
+ this._configuration.configurationKey.key = value;
+ }
+ }
+
+ async handleGetConfiguration(commandPayload) {
+ const configurationKey = [];
+ const unknownKey = [];
+ 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,
+ });
+ }
+ } else {
+ for (const configuration of commandPayload.key) {
+ const keyFound = this._getConfigurationKey(configuration);
+ if (keyFound) {
+ if (Utils.isUndefined(keyFound.visible)) {
+ keyFound.visible = true;
+ } else {
+ keyFound.visible = Utils.convertToBoolean(configuration.visible);
+ }
+ if (!keyFound.visible) {
+ continue;
+ }
+ configurationKey.push({
+ key: keyFound.key,
+ readonly: keyFound.readonly,
+ value: keyFound.value,
+ });
+ } else {
+ unknownKey.push(configuration);
+ }
+ }
+ }
+ return {
+ configurationKey,
+ unknownKey,
+ };
}
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;
+ if (Utils.convertToBoolean(keyToChange.reboot)) {
+ return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
+ }
return Constants.OCPP_RESPONSE_ACCEPTED;
}
- return Constants.OCPP_RESPONSE_REJECTED;
}
async handleRemoteStartTransaction(commandPayload) {
- const transactionConnectorID = (commandPayload.connectorId ? commandPayload.connectorId : '1');
+ const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
// 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;
}
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;
}
throw error;
}
}
+ async sendStartTransactionWithTimeout(connectorID, idTag, timeout) {
+ setTimeout(() => this.sendStartTransaction(connectorID, idTag), timeout);
+ }
async sendStopTransaction(transactionId, connectorID) {
try {
}
for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) {
if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') {
- sampledValueLcl.sampledValue[index].value = Math.floor(Math.random() * 100) + 1;
+ sampledValueLcl.sampledValue[index].value = Utils.getRandomInt(100);
if (sampledValueLcl.sampledValue[index].value > 100) {
- logger.info(self._basicFormatLog() + ' Meter type: ' +
- (sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'default') +
+ 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, 4);
+ 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() + ' 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') +
+ 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));
}
}
};
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 started`);
+ 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 meter values on connector ID ${connectorID} with no transaction id`);
+ 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);
}
hasAuthorizedTags() {
- return Array.isArray(this._authorizedTags) && this._authorizedTags.length > 0;
+ return !Utils.isEmptyArray(this._authorizedTags);
}
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];
}