getMaxNumberOfEvses,
getNumberOfReservableConnectors,
getPhaseRotationValue,
- hasFeatureProfile,
hasReservationExpired,
initializeConnectorsMapStatus,
propagateSerialNumber,
- removeExpiredReservations,
stationTemplateToStationInfo,
warnTemplateKeysDeprecation,
} from './Helpers';
export class ChargingStation extends EventEmitter {
public readonly index: number;
public readonly templateFile: string;
+ public stationInfo!: ChargingStationInfo;
public started: boolean;
public starting: boolean;
public idTagsCache: IdTagsCache;
public bootNotificationRequest!: BootNotificationRequest;
public bootNotificationResponse!: BootNotificationResponse | undefined;
public powerDivider!: number;
- private internalStationInfo!: ChargingStationInfo;
private stopping: boolean;
private configurationFile!: string;
private configurationFileHash!: string;
private ocppIncomingRequestService!: OCPPIncomingRequestService;
private readonly messageBuffer: Set<string>;
private configuredSupervisionUrl!: URL;
- private wsConnectionRestarted: boolean;
private autoReconnectRetryCount: number;
private templateFileWatcher!: FSWatcher | undefined;
private templateFileHash!: string;
private readonly sharedLRUCache: SharedLRUCache;
private webSocketPingSetInterval?: NodeJS.Timeout;
private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel;
- private reservationExpirationSetInterval?: NodeJS.Timeout;
+ private flushMessageBufferSetInterval?: NodeJS.Timeout;
constructor(index: number, templateFile: string) {
super();
this.starting = false;
this.stopping = false;
this.wsConnection = null;
- this.wsConnectionRestarted = false;
this.autoReconnectRetryCount = 0;
this.index = index;
this.templateFile = templateFile;
return this.connectors.size === 0 && this.evses.size > 0;
}
- public get stationInfo(): ChargingStationInfo {
- return {
- ...{
- enableStatistics: false,
- remoteAuthorization: true,
- currentOutType: CurrentType.AC,
- mainVoltageMeterValues: true,
- phaseLineToLineVoltageMeterValues: false,
- customValueLimitationMeterValues: true,
- ocppStrictCompliance: true,
- outOfOrderEndMeterValues: false,
- beginEndMeterValues: false,
- meteringPerTransaction: true,
- transactionDataMeterValues: false,
- supervisionUrlOcppConfiguration: false,
- supervisionUrlOcppKey: VendorParametersKey.ConnectionUrl,
- ocppVersion: OCPPVersion.VERSION_16,
- ocppPersistentConfiguration: true,
- stationInfoPersistentConfiguration: true,
- automaticTransactionGeneratorPersistentConfiguration: true,
- autoReconnectMaxRetries: -1,
- registrationMaxRetries: -1,
- reconnectExponentialDelay: false,
- stopTransactionsOnStopped: true,
- },
- ...this.internalStationInfo,
- };
- }
-
private get wsConnectionUrl(): URL {
return new URL(
`${
- this.stationInfo?.supervisionUrlOcppConfiguration &&
+ this.stationInfo?.supervisionUrlOcppConfiguration === true &&
isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) &&
isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value)
? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value
}
public logPrefix = (): string => {
- return logPrefix(
- ` ${
- (isNotEmptyString(this?.stationInfo?.chargingStationId)
- ? this?.stationInfo?.chargingStationId
- : getChargingStationId(this.index, this.getTemplateFromFile()!)) ??
- 'Error at building log prefix'
- } |`,
- );
+ if (isNotEmptyString(this?.stationInfo?.chargingStationId)) {
+ return logPrefix(` ${this?.stationInfo?.chargingStationId} |`);
+ }
+ let stationTemplate: ChargingStationTemplate | undefined;
+ try {
+ stationTemplate = JSON.parse(
+ readFileSync(this.templateFile, 'utf8'),
+ ) as ChargingStationTemplate;
+ } catch {
+ stationTemplate = undefined;
+ }
+ return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`);
};
public hasIdTags(): boolean {
const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
switch (this.getCurrentOutType(stationInfo)) {
case CurrentType.AC:
- return !isUndefined(localStationInfo.numberOfPhases) ? localStationInfo.numberOfPhases! : 3;
+ return localStationInfo.numberOfPhases ?? 3;
case CurrentType.DC:
return 0;
}
return this?.wsConnection?.readyState === WebSocket.OPEN;
}
- public getRegistrationStatus(): RegistrationStatusEnumType | undefined {
- return this?.bootNotificationResponse?.status;
- }
-
public inUnknownState(): boolean {
return isNullOrUndefined(this?.bootNotificationResponse?.status);
}
this,
StandardParametersKey.AuthorizeRemoteTxRequests,
);
- return authorizeRemoteTxRequests ? convertToBoolean(authorizeRemoteTxRequests.value) : false;
+ return authorizeRemoteTxRequests !== undefined
+ ? convertToBoolean(authorizeRemoteTxRequests.value)
+ : false;
}
public getLocalAuthListEnabled(): boolean {
this,
StandardParametersKey.LocalAuthListEnabled,
);
- return localAuthListEnabled ? convertToBoolean(localAuthListEnabled.value) : false;
+ return localAuthListEnabled !== undefined
+ ? convertToBoolean(localAuthListEnabled.value)
+ : false;
}
public getHeartbeatInterval(): number {
const HeartbeatInterval = getConfigurationKey(this, StandardParametersKey.HeartbeatInterval);
- if (HeartbeatInterval) {
+ if (HeartbeatInterval !== undefined) {
return secondsToMilliseconds(convertToInt(HeartbeatInterval.value));
}
const HeartBeatInterval = getConfigurationKey(this, StandardParametersKey.HeartBeatInterval);
- if (HeartBeatInterval) {
+ if (HeartBeatInterval !== undefined) {
return secondsToMilliseconds(convertToInt(HeartBeatInterval.value));
}
this.stationInfo?.autoRegister === false &&
if (this.stationInfo?.enableStatistics === true) {
this.performanceStatistics?.start();
}
- if (hasFeatureProfile(this, SupportedFeatureProfiles.Reservation)) {
- this.startReservationExpirationSetInterval();
- }
this.openWSConnection();
// Monitor charging station template file
this.templateFileWatcher = watchJsonFile(
if (this.stationInfo?.enableStatistics === true) {
this.performanceStatistics?.stop();
}
- if (hasFeatureProfile(this, SupportedFeatureProfiles.Reservation)) {
- this.stopReservationExpirationSetInterval();
- }
this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
this.templateFileWatcher?.close();
this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash);
public bufferMessage(message: string): void {
this.messageBuffer.add(message);
+ if (this.flushMessageBufferSetInterval === undefined) {
+ this.flushMessageBufferSetInterval = setInterval(() => {
+ if (this.isWebSocketConnectionOpened() === true && this.inAcceptedState() === true) {
+ this.flushMessageBuffer();
+ }
+ if (this.flushMessageBufferSetInterval !== undefined && this.messageBuffer.size === 0) {
+ clearInterval(this.flushMessageBufferSetInterval);
+ delete this.flushMessageBufferSetInterval;
+ }
+ }, Constants.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL);
+ }
}
public openWSConnection(
public async addReservation(reservation: Reservation): Promise<void> {
const reservationFound = this.getReservationBy('reservationId', reservation.reservationId);
- if (!isUndefined(reservationFound)) {
- await this.removeReservation(
- reservationFound!,
- ReservationTerminationReason.REPLACE_EXISTING,
- );
+ if (reservationFound !== undefined) {
+ await this.removeReservation(reservationFound, ReservationTerminationReason.REPLACE_EXISTING);
}
this.getConnectorStatus(reservation.connectorId)!.reservation = reservation;
await OCPPServiceUtils.sendAndSetConnectorStatus(
return false;
}
- private startReservationExpirationSetInterval(customInterval?: number): void {
- const interval = customInterval ?? Constants.DEFAULT_RESERVATION_EXPIRATION_INTERVAL;
- if (interval > 0) {
- logger.info(
- `${this.logPrefix()} Reservation expiration date checks started every ${formatDurationMilliSeconds(
- interval,
- )}`,
- );
- this.reservationExpirationSetInterval = setInterval((): void => {
- removeExpiredReservations(this).catch(Constants.EMPTY_FUNCTION);
- }, interval);
- }
- }
-
- private stopReservationExpirationSetInterval(): void {
- if (!isNullOrUndefined(this.reservationExpirationSetInterval)) {
- clearInterval(this.reservationExpirationSetInterval);
- }
- }
-
- // private restartReservationExpiryDateSetInterval(): void {
- // this.stopReservationExpirationSetInterval();
- // this.startReservationExpirationSetInterval();
- // }
-
private getNumberOfReservableConnectors(): number {
let numberOfReservableConnectors = 0;
if (this.hasEvses) {
return stationInfo;
}
- private getStationInfoFromFile(): ChargingStationInfo | undefined {
+ private getStationInfoFromFile(
+ stationInfoPersistentConfiguration = true,
+ ): ChargingStationInfo | undefined {
let stationInfo: ChargingStationInfo | undefined;
- if (this.stationInfo?.stationInfoPersistentConfiguration === true) {
+ if (stationInfoPersistentConfiguration === true) {
stationInfo = this.getConfigurationFromFile()?.stationInfo;
if (stationInfo) {
delete stationInfo?.infoHash;
}
private getStationInfo(): ChargingStationInfo {
+ const defaultStationInfo: Partial<ChargingStationInfo> = {
+ enableStatistics: false,
+ remoteAuthorization: true,
+ currentOutType: CurrentType.AC,
+ mainVoltageMeterValues: true,
+ phaseLineToLineVoltageMeterValues: false,
+ customValueLimitationMeterValues: true,
+ ocppStrictCompliance: true,
+ outOfOrderEndMeterValues: false,
+ beginEndMeterValues: false,
+ meteringPerTransaction: true,
+ transactionDataMeterValues: false,
+ supervisionUrlOcppConfiguration: false,
+ supervisionUrlOcppKey: VendorParametersKey.ConnectionUrl,
+ ocppVersion: OCPPVersion.VERSION_16,
+ ocppPersistentConfiguration: true,
+ stationInfoPersistentConfiguration: true,
+ automaticTransactionGeneratorPersistentConfiguration: true,
+ autoReconnectMaxRetries: -1,
+ registrationMaxRetries: -1,
+ reconnectExponentialDelay: false,
+ stopTransactionsOnStopped: true,
+ };
const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
- const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile();
+ const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile(
+ stationInfoFromTemplate?.stationInfoPersistentConfiguration,
+ );
// Priority:
// 1. charging station info from template
// 2. charging station info from configuration file
if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
- return stationInfoFromFile!;
+ return { ...defaultStationInfo, ...stationInfoFromFile! };
}
stationInfoFromFile &&
propagateSerialNumber(
stationInfoFromFile,
stationInfoFromTemplate,
);
- return stationInfoFromTemplate;
+ return { ...defaultStationInfo, ...stationInfoFromTemplate };
}
private saveStationInfo(): void {
} else {
this.initializeConnectorsOrEvsesFromTemplate(stationTemplate);
}
- this.internalStationInfo = this.getStationInfo();
+ this.stationInfo = this.getStationInfo();
if (
this.stationInfo.firmwareStatus === FirmwareStatus.Installing &&
isNotEmptyString(this.stationInfo.firmwareVersion) &&
}
private initializeOcppConfiguration(): void {
- if (!getConfigurationKey(this, StandardParametersKey.HeartbeatInterval)) {
+ if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.HeartbeatInterval))) {
addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0');
}
- if (!getConfigurationKey(this, StandardParametersKey.HeartBeatInterval)) {
+ if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.HeartBeatInterval))) {
addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false });
}
if (
- this.stationInfo?.supervisionUrlOcppConfiguration &&
+ this.stationInfo?.supervisionUrlOcppConfiguration === true &&
isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) &&
- !getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)
+ isNullOrUndefined(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!))
) {
addConfigurationKey(
this,
{ reboot: true },
);
} else if (
- !this.stationInfo?.supervisionUrlOcppConfiguration &&
+ this.stationInfo?.supervisionUrlOcppConfiguration === false &&
isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) &&
- getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)
+ !isNullOrUndefined(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!))
) {
deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!, { save: false });
}
if (
isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
- !getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)
+ isNullOrUndefined(getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!))
) {
addConfigurationKey(
this,
).toString(),
);
}
- if (!getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)) {
+ if (
+ isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles))
+ ) {
addConfigurationKey(
this,
StandardParametersKey.SupportedFeatureProfiles,
{ readonly: true },
{ overwrite: true },
);
- if (!getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData)) {
+ if (
+ isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData))
+ ) {
addConfigurationKey(
this,
StandardParametersKey.MeterValuesSampledData,
MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
);
}
- if (!getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation)) {
+ if (
+ isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation))
+ ) {
const connectorsPhaseRotation: string[] = [];
if (this.hasEvses) {
for (const evseStatus of this.evses.values()) {
connectorsPhaseRotation.toString(),
);
}
- if (!getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests)) {
+ if (
+ isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests))
+ ) {
addConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
}
if (
- !getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled) &&
+ isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled)) &&
getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)?.value?.includes(
SupportedFeatureProfiles.LocalAuthListManagement,
)
) {
addConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled, 'false');
}
- if (!getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) {
+ if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut))) {
addConfigurationKey(
this,
StandardParametersKey.ConnectionTimeOut,
}
if (
this.stationInfo?.ocppPersistentConfiguration === true &&
- this.ocppConfiguration?.configurationKey
+ Array.isArray(this.ocppConfiguration?.configurationKey)
) {
- configurationData.configurationKey = this.ocppConfiguration.configurationKey;
+ configurationData.configurationKey = this.ocppConfiguration?.configurationKey;
} else {
delete configurationData.configurationKey;
}
private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined {
const configurationKey = this.getConfigurationFromFile()?.configurationKey;
- if (this.stationInfo?.ocppPersistentConfiguration === true && configurationKey) {
+ if (this.stationInfo?.ocppPersistentConfiguration === true && Array.isArray(configurationKey)) {
return { configurationKey };
}
return undefined;
.stationInfo?.registrationMaxRetries})`,
);
}
- this.wsConnectionRestarted = false;
this.autoReconnectRetryCount = 0;
this.emit(ChargingStationEvents.updated);
} else {
commandName,
commandPayload,
);
+ this.emit(ChargingStationEvents.updated);
}
private handleResponseMessage(response: Response): void {
logger.error(`${this.logPrefix()} ${errorMsg}`);
throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg);
}
- this.emit(ChargingStationEvents.updated);
} else {
throw new OCPPError(
ErrorType.PROTOCOL_ERROR,
// 0 for disabling
private getConnectionTimeout(): number {
- if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) {
- return (
- parseInt(getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)!.value!) ??
- Constants.DEFAULT_CONNECTION_TIMEOUT
+ if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut) !== undefined) {
+ return convertToInt(
+ getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)!.value! ??
+ Constants.DEFAULT_CONNECTION_TIMEOUT,
);
}
return Constants.DEFAULT_CONNECTION_TIMEOUT;
return powerDivider;
}
- private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
- const maximumPower = this.getMaximumPower(stationInfo);
+ private getMaximumAmperage(stationInfo?: ChargingStationInfo): number | undefined {
+ const maximumPower = (stationInfo ?? this.stationInfo).maximumPower!;
switch (this.getCurrentOutType(stationInfo)) {
case CurrentType.AC:
return ACElectricUtils.amperagePerPhaseFromPower(
}
}
- private getMaximumPower(stationInfo?: ChargingStationInfo): number {
- return (stationInfo ?? this.stationInfo).maximumPower!;
- }
-
private getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType {
return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC;
}
private getAmperageLimitation(): number | undefined {
if (
isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
- getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)
+ getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) !== undefined
) {
return (
convertToInt(
}
}
}
- if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) {
+ if (this.stationInfo.firmwareStatus === FirmwareStatus.Installing) {
await this.ocppRequestService.requestHandler<
FirmwareStatusNotificationRequest,
FirmwareStatusNotificationResponse
if (this.getAutomaticTransactionGeneratorConfiguration().enable === true) {
this.startAutomaticTransactionGenerator();
}
- this.wsConnectionRestarted === true && this.flushMessageBuffer();
+ this.flushMessageBuffer();
}
private async stopMessageSequence(
}
private startWebSocketPing(): void {
- const webSocketPingInterval: number = getConfigurationKey(
- this,
- StandardParametersKey.WebSocketPingInterval,
- )
- ? convertToInt(getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value)
- : 0;
- if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
+ const webSocketPingInterval: number =
+ getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval) !== undefined
+ ? convertToInt(
+ getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value,
+ )
+ : 0;
+ if (webSocketPingInterval > 0 && this.webSocketPingSetInterval === undefined) {
this.webSocketPingSetInterval = setInterval(() => {
if (this.isWebSocketConnectionOpened() === true) {
this.wsConnection?.ping();
webSocketPingInterval,
)}`,
);
- } else if (this.webSocketPingSetInterval) {
+ } else if (this.webSocketPingSetInterval !== undefined) {
logger.info(
`${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
webSocketPingInterval,
}
private stopWebSocketPing(): void {
- if (this.webSocketPingSetInterval) {
+ if (this.webSocketPingSetInterval !== undefined) {
clearInterval(this.webSocketPingSetInterval);
delete this.webSocketPingSetInterval;
}
},
{ closeOpened: true },
);
- this.wsConnectionRestarted = true;
} else if (this.stationInfo?.autoReconnectMaxRetries !== -1) {
logger.error(
`${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${