IncomingRequestCommand,
RequestCommand,
} from '../types/ocpp/Requests';
-import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
+import {
+ BootNotificationResponse,
+ HeartbeatResponse,
+ MeterValuesResponse,
+ RegistrationStatus,
+ StatusNotificationResponse,
+} from '../types/ocpp/Responses';
import ChargingStationConfiguration, {
ConfigurationKey,
} from '../types/ChargingStationConfiguration';
VendorDefaultParametersKey,
} from '../types/ocpp/Configuration';
import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
+import { StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction';
import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
import WebSocket, { ClientOptions, Data, OPEN, RawData } from 'ws';
import { OCPPVersion } from '../types/ocpp/OCPPVersion';
import PerformanceStatistics from '../performance/PerformanceStatistics';
import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
-import { StopTransactionReason } from '../types/ocpp/Transaction';
import { SupervisionUrlDistribution } from '../types/ConfigurationData';
import { URL } from 'url';
import Utils from '../utils/Utils';
import path from 'path';
export default class ChargingStation {
- public readonly id: string;
+ public hashId!: string;
public readonly stationTemplateFile: string;
public authorizedTags: string[];
public stationInfo!: ChargingStationInfo;
public performanceStatistics!: PerformanceStatistics;
public heartbeatSetInterval!: NodeJS.Timeout;
public ocppRequestService!: OCPPRequestService;
+ public bootNotificationResponse!: BootNotificationResponse | null;
private readonly index: number;
private configurationFile!: string;
private bootNotificationRequest!: BootNotificationRequest;
- private bootNotificationResponse!: BootNotificationResponse | null;
private connectorsConfigurationHash!: string;
private ocppIncomingRequestService!: OCPPIncomingRequestService;
private readonly messageBuffer: Set<string>;
private webSocketPingSetInterval!: NodeJS.Timeout;
constructor(index: number, stationTemplateFile: string) {
- this.id = Utils.generateUUID();
this.index = index;
this.stationTemplateFile = stationTemplateFile;
this.stopped = false;
this.authorizedTags = this.getAuthorizedTags();
}
- get wsConnectionUrl(): URL {
+ private get wsConnectionUrl(): URL {
return this.getSupervisionUrlOcppConfiguration()
? new URL(
this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value +
) {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
- await this.ocppRequestService.sendMessageHandler(RequestCommand.HEARTBEAT);
+ await this.ocppRequestService.sendMessageHandler<HeartbeatResponse>(
+ RequestCommand.HEARTBEAT
+ );
}, this.getHeartbeatInterval());
logger.info(
this.logPrefix() +
this.getConnectorStatus(connectorId).transactionId,
interval
);
- await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, {
- connectorId,
- transactionId: this.getConnectorStatus(connectorId).transactionId,
- meterValue: [meterValue],
- });
+ await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
+ RequestCommand.METER_VALUES,
+ {
+ connectorId,
+ transactionId: this.getConnectorStatus(connectorId).transactionId,
+ meterValue: [meterValue],
+ }
+ );
},
interval
);
}
}
);
- FileUtils.watchJsonFile<ChargingStationConfiguration>(
- this.logPrefix(),
- FileType.ChargingStationConfiguration,
- this.configurationFile,
- this.configuration
- );
// Handle WebSocket message
this.wsConnection.on(
'message',
await this.stopMessageSequence(reason);
for (const connectorId of this.connectors.keys()) {
if (connectorId > 0) {
- await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
- connectorId,
- status: ChargePointStatus.UNAVAILABLE,
- errorCode: ChargePointErrorCode.NO_ERROR,
- });
+ await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+ RequestCommand.STATUS_NOTIFICATION,
+ {
+ connectorId,
+ status: ChargePointStatus.UNAVAILABLE,
+ errorCode: ChargePointErrorCode.NO_ERROR,
+ }
+ );
this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
}
}
reboot: false,
};
}
- const readonly = options.readonly;
- const visible = options.visible;
- const reboot = options.reboot;
+ const readonly = options.readonly ?? false;
+ const visible = options.visible ?? true;
+ const reboot = options.reboot ?? false;
let keyFound = this.getConfigurationKey(key);
if (keyFound && params?.overwrite) {
- this.configuration.configurationKey.splice(
- this.configuration.configurationKey.indexOf(keyFound),
- 1
- );
+ this.deleteConfigurationKey(keyFound.key, { save: false });
keyFound = undefined;
}
if (!keyFound) {
}
}
+ public deleteConfigurationKey(
+ key: string | StandardParametersKey,
+ params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false }
+ ): ConfigurationKey[] {
+ const keyFound = this.getConfigurationKey(key, params?.caseInsensitive);
+ if (keyFound) {
+ const deletedConfigurationKey = this.configuration.configurationKey.splice(
+ this.configuration.configurationKey.indexOf(keyFound),
+ 1
+ );
+ params?.save && this.saveConfiguration();
+ return deletedConfigurationKey;
+ }
+ }
+
public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
let cpReplaced = false;
if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
}
}
- private getSupervisionUrlOcppKey(): string {
- return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
- }
-
private getSupervisionUrlOcppConfiguration(): boolean {
return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
}
+ private getSupervisionUrlOcppKey(): string {
+ return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
+ }
+
private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
// In case of multiple instances: add instance index to charging station id
const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
idSuffix;
}
+ private getRandomSerialNumberSuffix(params?: {
+ randomBytesLength?: number;
+ upperCase?: boolean;
+ }): string {
+ const randomSerialNumberSuffix = crypto
+ .randomBytes(params?.randomBytesLength ?? 16)
+ .toString('hex');
+ if (params?.upperCase) {
+ return randomSerialNumberSuffix.toUpperCase();
+ }
+ return randomSerialNumberSuffix;
+ }
+
private buildStationInfo(): ChargingStationInfo {
let stationTemplateFromFile: ChargingStationTemplate;
try {
);
this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? ({} as ChargingStationInfo);
+ stationInfo.chargePointSerialNumber = stationTemplateFromFile?.chargePointSerialNumberPrefix;
+ delete stationInfo.chargePointSerialNumberPrefix;
+ stationInfo.chargeBoxSerialNumber = stationTemplateFromFile?.chargeBoxSerialNumberPrefix;
+ delete stationInfo.chargeBoxSerialNumberPrefix;
stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
}
+ private getOcppPersistentConfiguration(): boolean {
+ return this.stationInfo.ocppPersistentConfiguration ?? true;
+ }
+
private handleUnsupportedVersion(version: OCPPVersion) {
const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
this.stationTemplateFile
private initialize(): void {
this.stationInfo = this.buildStationInfo();
- this.configurationFile = path.join(
- path.resolve(__dirname, '../'),
- 'assets',
- 'configurations',
- this.stationInfo.chargingStationId + '.json'
- );
- this.configuration = this.getConfiguration();
- delete this.stationInfo.Configuration;
this.bootNotificationRequest = {
chargePointModel: this.stationInfo.chargePointModel,
chargePointVendor: this.stationInfo.chargePointVendor,
- ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && {
- chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix,
+ ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumber) && {
+ chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumber,
+ }),
+ ...(!Utils.isUndefined(this.stationInfo.chargePointSerialNumber) && {
+ chargePointSerialNumber: this.stationInfo.chargePointSerialNumber,
}),
...(!Utils.isUndefined(this.stationInfo.firmwareVersion) && {
firmwareVersion: this.stationInfo.firmwareVersion,
}),
+ ...(!Utils.isUndefined(this.stationInfo.iccid) && { iccid: this.stationInfo.iccid }),
+ ...(!Utils.isUndefined(this.stationInfo.imsi) && { imsi: this.stationInfo.imsi }),
+ ...(!Utils.isUndefined(this.stationInfo.meterSerialNumber) && {
+ meterSerialNumber: this.stationInfo.meterSerialNumber,
+ }),
+ ...(!Utils.isUndefined(this.stationInfo.meterType) && {
+ meterType: this.stationInfo.meterType,
+ }),
};
+
+ this.hashId = crypto
+ .createHash(Constants.DEFAULT_HASH_ALGORITHM)
+ .update(JSON.stringify(this.bootNotificationRequest) + this.stationInfo.chargingStationId)
+ .digest('hex');
+ logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
+ this.configurationFile = path.join(
+ path.resolve(__dirname, '../'),
+ 'assets',
+ 'configurations',
+ this.hashId + '.json'
+ );
+ this.configuration = this.getConfiguration();
+ delete this.stationInfo.Configuration;
// Build connectors if needed
const maxConnectors = this.getMaxNumberOfConnectors();
if (maxConnectors <= 0) {
this.stationInfo.randomConnectors = true;
}
const connectorsConfigHash = crypto
- .createHash('sha256')
+ .createHash(Constants.DEFAULT_HASH_ALGORITHM)
.update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
.digest('hex');
const connectorsConfigChanged =
this.wsConfiguredConnectionUrl = new URL(
this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
);
+ // OCPP parameters
+ this.initOcppParameters();
switch (this.getOcppVersion()) {
case OCPPVersion.VERSION_16:
this.ocppIncomingRequestService =
this.handleUnsupportedVersion(this.getOcppVersion());
break;
}
- // OCPP parameters
- this.initOcppParameters();
if (this.stationInfo.autoRegister) {
this.bootNotificationResponse = {
currentTime: new Date().toISOString(),
this.stationInfo.powerDivider = this.getPowerDivider();
if (this.getEnableStatistics()) {
this.performanceStatistics = PerformanceStatistics.getInstance(
- this.id,
+ this.hashId,
this.stationInfo.chargingStationId,
this.wsConnectionUrl
);
this.getConfiguredSupervisionUrl().href,
{ reboot: true }
);
+ } else if (
+ !this.getSupervisionUrlOcppConfiguration() &&
+ this.getConfigurationKey(this.getSupervisionUrlOcppKey())
+ ) {
+ this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
}
if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
this.addConfigurationKey(
private getConfigurationFromFile(): ChargingStationConfiguration | null {
let configuration: ChargingStationConfiguration = null;
- if (this.configurationFile && fs.existsSync(this.configurationFile)) {
+ if (
+ this.getOcppPersistentConfiguration() &&
+ this.configurationFile &&
+ fs.existsSync(this.configurationFile)
+ ) {
try {
configuration = JSON.parse(
fs.readFileSync(this.configurationFile, 'utf8')
}
private saveConfiguration(): void {
- if (this.configurationFile) {
- try {
- if (!fs.existsSync(path.dirname(this.configurationFile))) {
- fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
+ if (this.getOcppPersistentConfiguration()) {
+ if (this.configurationFile) {
+ try {
+ if (!fs.existsSync(path.dirname(this.configurationFile))) {
+ fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
+ }
+ const fileDescriptor = fs.openSync(this.configurationFile, 'w');
+ fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2));
+ fs.closeSync(fileDescriptor);
+ } catch (error) {
+ FileUtils.handleFileException(
+ this.logPrefix(),
+ FileType.ChargingStationConfiguration,
+ this.configurationFile,
+ error as NodeJS.ErrnoException
+ );
}
- const fileDescriptor = fs.openSync(this.configurationFile, 'w');
- fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2));
- fs.closeSync(fileDescriptor);
- } catch (error) {
- FileUtils.handleFileException(
- this.logPrefix(),
- FileType.ChargingStationConfiguration,
- this.configurationFile,
- error as NodeJS.ErrnoException
+ } else {
+ logger.error(
+ `${this.logPrefix()} Trying to save charging station configuration to undefined file`
);
}
- } else {
- logger.error(
- `${this.logPrefix()} Trying to save charging station configuration to undefined file`
- );
}
}
// Send BootNotification
let registrationRetryCount = 0;
do {
- this.bootNotificationResponse = (await this.ocppRequestService.sendMessageHandler(
- RequestCommand.BOOT_NOTIFICATION,
- {
- chargePointModel: this.bootNotificationRequest.chargePointModel,
- chargePointVendor: this.bootNotificationRequest.chargePointVendor,
- chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
- firmwareVersion: this.bootNotificationRequest.firmwareVersion,
- chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
- iccid: this.bootNotificationRequest.iccid,
- imsi: this.bootNotificationRequest.imsi,
- meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
- meterType: this.bootNotificationRequest.meterType,
- },
- { skipBufferingOnError: true }
- )) as BootNotificationResponse;
+ this.bootNotificationResponse =
+ await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
+ RequestCommand.BOOT_NOTIFICATION,
+ {
+ chargePointModel: this.bootNotificationRequest.chargePointModel,
+ chargePointVendor: this.bootNotificationRequest.chargePointVendor,
+ chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
+ firmwareVersion: this.bootNotificationRequest.firmwareVersion,
+ chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
+ iccid: this.bootNotificationRequest.iccid,
+ imsi: this.bootNotificationRequest.imsi,
+ meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
+ meterType: this.bootNotificationRequest.meterType,
+ },
+ { skipBufferingOnError: true }
+ );
if (!this.isInAcceptedState()) {
this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
await Utils.sleep(
private async startMessageSequence(): Promise<void> {
if (this.stationInfo.autoRegister) {
- await this.ocppRequestService.sendMessageHandler(
+ await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
RequestCommand.BOOT_NOTIFICATION,
{
chargePointModel: this.bootNotificationRequest.chargePointModel,
this.getConnectorStatus(connectorId)?.bootStatus
) {
// Send status in template at startup
- await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
- connectorId,
- status: this.getConnectorStatus(connectorId).bootStatus,
- errorCode: ChargePointErrorCode.NO_ERROR,
- });
+ await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+ RequestCommand.STATUS_NOTIFICATION,
+ {
+ connectorId,
+ status: this.getConnectorStatus(connectorId).bootStatus,
+ errorCode: ChargePointErrorCode.NO_ERROR,
+ }
+ );
this.getConnectorStatus(connectorId).status =
this.getConnectorStatus(connectorId).bootStatus;
} else if (
this.getConnectorStatus(connectorId)?.bootStatus
) {
// Send status in template after reset
- await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
- connectorId,
- status: this.getConnectorStatus(connectorId).bootStatus,
- errorCode: ChargePointErrorCode.NO_ERROR,
- });
+ await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+ RequestCommand.STATUS_NOTIFICATION,
+ {
+ connectorId,
+ status: this.getConnectorStatus(connectorId).bootStatus,
+ errorCode: ChargePointErrorCode.NO_ERROR,
+ }
+ );
this.getConnectorStatus(connectorId).status =
this.getConnectorStatus(connectorId).bootStatus;
} else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
// Send previous status at template reload
- await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
- connectorId,
- status: this.getConnectorStatus(connectorId).status,
- errorCode: ChargePointErrorCode.NO_ERROR,
- });
+ await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+ RequestCommand.STATUS_NOTIFICATION,
+ {
+ connectorId,
+ status: this.getConnectorStatus(connectorId).status,
+ errorCode: ChargePointErrorCode.NO_ERROR,
+ }
+ );
} else {
// Send default status
- await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
- connectorId,
- status: ChargePointStatus.AVAILABLE,
- errorCode: ChargePointErrorCode.NO_ERROR,
- });
+ await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+ RequestCommand.STATUS_NOTIFICATION,
+ {
+ connectorId,
+ status: ChargePointStatus.AVAILABLE,
+ errorCode: ChargePointErrorCode.NO_ERROR,
+ }
+ );
this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
}
}
connectorId,
this.getEnergyActiveImportRegisterByTransactionId(transactionId)
);
- await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, {
- connectorId,
- transactionId,
- meterValue: transactionEndMeterValue,
- });
+ await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
+ RequestCommand.METER_VALUES,
+ {
+ connectorId,
+ transactionId,
+ meterValue: transactionEndMeterValue,
+ }
+ );
}
- await this.ocppRequestService.sendMessageHandler(RequestCommand.STOP_TRANSACTION, {
- transactionId,
- meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
- idTag: this.getTransactionIdTag(transactionId),
- reason,
- });
+ await this.ocppRequestService.sendMessageHandler<StopTransactionResponse>(
+ RequestCommand.STOP_TRANSACTION,
+ {
+ transactionId,
+ meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
+ idTag: this.getTransactionIdTag(transactionId),
+ reason,
+ }
+ );
}
}
}