-import { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand, Request } from '../types/ocpp/Requests';
+import { AvailabilityType, BootNotificationRequest, CachedRequest, IncomingRequest, IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
import ChargingStationTemplate, { CurrentType, PowerUnits, Voltage } from '../types/ChargingStationTemplate';
import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles } from '../types/ocpp/Configuration';
import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
import ChargingStationTemplate, { CurrentType, PowerUnits, Voltage } from '../types/ChargingStationTemplate';
import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles } from '../types/ocpp/Configuration';
import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
-import WebSocket, { ClientOptions, Data } from 'ws';
+import WebSocket, { ClientOptions, Data, OPEN } from 'ws';
import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
private bootNotificationRequest!: BootNotificationRequest;
private bootNotificationResponse!: BootNotificationResponse | null;
private connectorsConfigurationHash!: string;
private bootNotificationRequest!: BootNotificationRequest;
private bootNotificationResponse!: BootNotificationResponse | null;
private connectorsConfigurationHash!: string;
private webSocketPingSetInterval!: NodeJS.Timeout;
constructor(index: number, stationTemplateFile: string) {
this.index = index;
this.stationTemplateFile = stationTemplateFile;
private webSocketPingSetInterval!: NodeJS.Timeout;
constructor(index: number, stationTemplateFile: string) {
this.index = index;
this.stationTemplateFile = stationTemplateFile;
- public getRandomTagId(): string {
- const index = Math.floor(Math.random() * this.authorizedTags.length);
+ public getRandomIdTag(): string {
+ const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
- public getConnector(id: number): Connector {
- return this.connectors[id];
+ public getNumberOfConnectors(): number {
+ return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
+ }
+
+ public getConnectorStatus(id: number): ConnectorStatus {
+ return this.connectors.get(id);
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
- return this.getConnector(Utils.convertToInt(connector)).transactionIdTag;
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
+ return this.getConnectorStatus(connectorId).transactionIdTag;
public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
if (this.getMeteringPerTransaction()) {
public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
if (this.getMeteringPerTransaction()) {
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
- return this.getConnector(Utils.convertToInt(connector)).transactionEnergyActiveImportRegisterValue;
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
+ return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
- return this.getConnector(Utils.convertToInt(connector)).energyActiveImportRegisterValue;
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
+ return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
}
}
}
public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
if (this.getMeteringPerTransaction()) {
}
}
}
public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
if (this.getMeteringPerTransaction()) {
public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
phase?: MeterValuePhase): SampledValueTemplate | undefined {
if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
phase?: MeterValuePhase): SampledValueTemplate | undefined {
if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) {
for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) {
return sampledValueTemplates[index];
} else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
return sampledValueTemplates[index];
} else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
return sampledValueTemplates[index];
} else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
return sampledValueTemplates[index];
} else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
return sampledValueTemplates[index];
}
}
if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
return sampledValueTemplates[index];
}
}
if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
await this.ocppRequestService.sendHeartbeat();
}, this.getHeartbeatInterval());
this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
await this.ocppRequestService.sendHeartbeat();
}, this.getHeartbeatInterval());
- logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
+ logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
return;
}
if (interval > 0) {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
return;
}
if (interval > 0) {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
- this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
- await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval);
+ this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
+ await this.ocppRequestService.sendMeterValues(connectorId, this.getConnectorStatus(connectorId).transactionId, interval);
- logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
+ logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
this.startAuthorizationFileMonitoring();
// Monitor station template file
this.startStationTemplateFileMonitoring();
this.startAuthorizationFileMonitoring();
// Monitor station template file
this.startStationTemplateFileMonitoring();
this.wsConnection.on('pong', this.onPong.bind(this));
}
public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
// Stop message sequence
await this.stopMessageSequence(reason);
this.wsConnection.on('pong', this.onPong.bind(this));
}
public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
// Stop message sequence
await this.stopMessageSequence(reason);
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0) {
- await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
- this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0) {
+ await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.UNAVAILABLE);
+ this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
- if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
- this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
+ if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
+ this.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
- || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
- this.getConnector(connectorId).chargingProfiles[index] = cp;
+ || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
+ this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
- this.getConnector(connectorId).authorized = false;
- this.getConnector(connectorId).transactionStarted = false;
- delete this.getConnector(connectorId).authorizeIdTag;
- delete this.getConnector(connectorId).transactionId;
- delete this.getConnector(connectorId).transactionIdTag;
- this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
- delete this.getConnector(connectorId).transactionBeginMeterValue;
+ this.getConnectorStatus(connectorId).authorized = false;
+ this.getConnectorStatus(connectorId).transactionStarted = false;
+ delete this.getConnectorStatus(connectorId).authorizeIdTag;
+ delete this.getConnectorStatus(connectorId).transactionId;
+ delete this.getConnectorStatus(connectorId).transactionIdTag;
+ this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
+ delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
// In case of multiple instances: add instance index to charging station id
private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
// In case of multiple instances: add instance index to charging station id
const idSuffix = stationTemplate.nameSuffix ?? '';
return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
}
const idSuffix = stationTemplate.nameSuffix ?? '';
return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
}
const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
: stationTemplateFromFile.power[powerArrayRandomIndex];
stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
: stationTemplateFromFile.power[powerArrayRandomIndex];
this.stationInfo.randomConnectors = true;
}
const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
this.stationInfo.randomConnectors = true;
}
const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
- // FIXME: Handle shrinking the number of connectors
- if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
+ const connectorsConfigChanged = this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
+ if (this.connectors?.size === 0 || connectorsConfigChanged) {
+ connectorsConfigChanged && (this.connectors.clear());
this.connectorsConfigurationHash = connectorsConfigHash;
// Add connector Id 0
let lastConnector = '0';
for (lastConnector in this.stationInfo.Connectors) {
this.connectorsConfigurationHash = connectorsConfigHash;
// Add connector Id 0
let lastConnector = '0';
for (lastConnector in this.stationInfo.Connectors) {
- if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
- this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
- this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
- if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
- this.connectors[lastConnector].chargingProfiles = [];
+ const lastConnectorId = Utils.convertToInt(lastConnector);
+ if (lastConnectorId === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
+ this.connectors.set(lastConnectorId, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector]));
+ this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
+ if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
+ this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
}
}
}
// Generate all connectors
if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
for (let index = 1; index <= maxConnectors; index++) {
}
}
}
// Generate all connectors
if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
for (let index = 1; index <= maxConnectors; index++) {
- const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
- this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]);
- this.connectors[index].availability = AvailabilityType.OPERATIVE;
- if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
- this.connectors[index].chargingProfiles = [];
+ const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) : index;
+ this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId]));
+ this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
+ if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
+ this.getConnectorStatus(index).chargingProfiles = [];
// Avoid duplication of connectors related information
delete this.stationInfo.Connectors;
// Initialize transaction attributes on connectors
// Avoid duplication of connectors related information
delete this.stationInfo.Connectors;
// Initialize transaction attributes on connectors
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
- this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
+ this.initTransactionAttributesOnConnector(connectorId);
}
if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
const connectorPhaseRotation = [];
}
if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
const connectorPhaseRotation = [];
- if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) {
- connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`);
- } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) {
- connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
+ if (connectorId === 0 && this.getNumberOfPhases() === 0) {
+ connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
+ } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
+ connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
- } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) {
- connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
- } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) {
- connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`);
+ } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
+ connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
+ } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
+ connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
}
if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
}
if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
}
if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
}
if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
- this.hasStopped && (this.hasStopped = false);
- if (this.hasSocketRestarted && this.isWebSocketConnectionOpened()) {
+ this.stopped && (this.stopped = false);
+ if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
this.flushMessageQueue();
}
} else {
logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
}
this.autoReconnectRetryCount = 0;
this.flushMessageQueue();
}
} else {
logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
}
this.autoReconnectRetryCount = 0;
private async onMessage(data: Data): Promise<void> {
let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
private async onMessage(data: Data): Promise<void> {
let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
- [responseCallback, , requestPayload] = cachedRequest;
+ [responseCallback, , , requestPayload] = cachedRequest;
- throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Response request for message id ${messageId} is not iterable`, commandName);
+ throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} response is not iterable`, commandName);
- throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response request for unknown message id ${messageId}`, commandName);
+ throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response for unknown message id ${messageId}`, commandName);
responseCallback(commandName, requestPayload);
break;
// Error Message
case MessageType.CALL_ERROR_MESSAGE:
cachedRequest = this.requests.get(messageId);
responseCallback(commandName, requestPayload);
break;
// Error Message
case MessageType.CALL_ERROR_MESSAGE:
cachedRequest = this.requests.get(messageId);
- this.requests.delete(messageId);
- rejectCallback(new OCPPError(commandName, commandPayload.toString(), null, errorDetails));
+ if (!rejectCallback) {
+ // Error
+ throw new OCPPError(ErrorType.INTERNAL_ERROR, `Error response for unknown message id ${messageId}`, requestCommandName);
+ }
+ rejectCallback(new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails));
- logger.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), data, error, this.requests.get(messageId));
+ logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data, this.requests.get(messageId), error);
- messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
+ messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
private async startMessageSequence(): Promise<void> {
// Start WebSocket ping
this.startWebSocketPing();
// Start heartbeat
this.startHeartbeat();
// Initialize connectors status
private async startMessageSequence(): Promise<void> {
// Start WebSocket ping
this.startWebSocketPing();
// Start heartbeat
this.startHeartbeat();
// Initialize connectors status
- await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
- this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
- } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
+ await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
+ this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
+ } else if (this.stopped && this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
- await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
- this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
- } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
+ await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
+ this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
+ } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
- await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
- this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
+ await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
+ this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
private startAutomaticTransactionGenerator() {
if (this.stationInfo.AutomaticTransactionGenerator.enable) {
private startAutomaticTransactionGenerator() {
if (this.stationInfo.AutomaticTransactionGenerator.enable) {
- if (!this.automaticTransactionGeneration) {
- this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
+ if (!this.automaticTransactionGenerator) {
+ this.automaticTransactionGenerator = new AutomaticTransactionGenerator(this);
- if (this.automaticTransactionGeneration.timeToStop) {
- // The ATG might sleep
- this.automaticTransactionGeneration.start().catch(() => { });
+ if (!this.automaticTransactionGenerator.started) {
+ this.automaticTransactionGenerator.start();
- this.automaticTransactionGeneration &&
- !this.automaticTransactionGeneration.timeToStop) {
- await this.automaticTransactionGeneration.stop(reason);
+ this.automaticTransactionGenerator &&
+ this.automaticTransactionGenerator.started) {
+ this.automaticTransactionGenerator.stop();
- for (const connector in this.connectors) {
- if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
- const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
+ for (const connectorId of this.connectors.keys()) {
+ if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
+ const transactionId = this.getConnectorStatus(connectorId).transactionId;
await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
this.getTransactionIdTag(transactionId), reason);
}
await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
this.getTransactionIdTag(transactionId), reason);
}
if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
this.webSocketPingSetInterval = setInterval(() => {
if (this.isWebSocketConnectionOpened()) {
if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
this.webSocketPingSetInterval = setInterval(() => {
if (this.isWebSocketConnectionOpened()) {
- logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
+ logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
- if (this.getConnector(connectorId)?.transactionSetInterval) {
- clearInterval(this.getConnector(connectorId).transactionSetInterval);
+ if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
+ clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
if (filename && event === 'change') {
try {
logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
if (filename && event === 'change') {
try {
logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
// Stop the ATG if needed
if (this.stationInfo.AutomaticTransactionGenerator.enable &&
this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
// Stop the ATG if needed
if (this.stationInfo.AutomaticTransactionGenerator.enable &&
this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
- this.automaticTransactionGeneration &&
- !this.automaticTransactionGeneration.timeToStop) {
- await this.automaticTransactionGeneration.stop();
+ this.automaticTransactionGenerator &&
+ this.automaticTransactionGenerator.started) {
+ this.automaticTransactionGenerator.stop();
}
if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
this.autoReconnectRetryCount++;
const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
}
if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
this.autoReconnectRetryCount++;
const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
- logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
+ const reconnectTimeout = reconnectDelay - 100;
+ logger.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
- logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
- this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
- this.hasSocketRestarted = true;
+ logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
+ this.openWSConnection({ handshakeTimeout: reconnectTimeout }, true);
+ this.wsConnectionRestarted = true;
- this.getConnector(connectorId).authorized = false;
- this.getConnector(connectorId).transactionStarted = false;
- this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
- this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
+ this.getConnectorStatus(connectorId).authorized = false;
+ this.getConnectorStatus(connectorId).transactionStarted = false;
+ this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
+ this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;