type ChargingStationOcppConfiguration,
type ChargingStationTemplate,
ConnectorPhaseRotation,
- ConnectorStatus,
+ type ConnectorStatus,
ConnectorStatusEnum,
CurrentType,
type ErrorCallback,
RegistrationStatusEnumType,
RequestCommand,
type Response,
- type ResponseCallback,
StandardParametersKey,
type StatusNotificationRequest,
type StatusNotificationResponse,
private ocppIncomingRequestService!: OCPPIncomingRequestService;
private readonly messageBuffer: Set<string>;
private configuredSupervisionUrl!: URL;
- private configuredSupervisionUrlIndex!: number;
private wsConnectionRestarted: boolean;
private autoReconnectRetryCount: number;
private templateFileWatcher!: fs.FSWatcher | undefined;
private get wsConnectionUrl(): URL {
return new URL(
`${
- this.getSupervisionUrlOcppConfiguration()
+ this.getSupervisionUrlOcppConfiguration() &&
+ Utils.isNotEmptyString(this.getSupervisionUrlOcppKey())
? ChargingStationConfigurationUtils.getConfigurationKey(
this,
this.getSupervisionUrlOcppKey()
return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
}
- public startHeartbeat(): void {
+ public getHeartbeatInterval(): number {
+ const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
+ this,
+ StandardParametersKey.HeartbeatInterval
+ );
+ if (HeartbeatInterval) {
+ return Utils.convertToInt(HeartbeatInterval.value) * 1000;
+ }
+ const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
+ this,
+ StandardParametersKey.HeartBeatInterval
+ );
+ if (HeartBeatInterval) {
+ return Utils.convertToInt(HeartBeatInterval.value) * 1000;
+ }
+ this.stationInfo?.autoRegister === false &&
+ logger.warn(
+ `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
+ Constants.DEFAULT_HEARTBEAT_INTERVAL
+ }`
+ );
+ return Constants.DEFAULT_HEARTBEAT_INTERVAL;
+ }
+
+ public setSupervisionUrl(url: string): void {
if (
- this.getHeartbeatInterval() &&
- this.getHeartbeatInterval() > 0 &&
- !this.heartbeatSetInterval
+ this.getSupervisionUrlOcppConfiguration() &&
+ Utils.isNotEmptyString(this.getSupervisionUrlOcppKey())
) {
+ ChargingStationConfigurationUtils.setConfigurationKeyValue(
+ this,
+ this.getSupervisionUrlOcppKey(),
+ url
+ );
+ } else {
+ this.stationInfo.supervisionUrls = url;
+ this.saveStationInfo();
+ this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
+ }
+ }
+
+ public startHeartbeat(): void {
+ if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
this.heartbeatSetInterval = setInterval(() => {
this.ocppRequestService
.requestHandler<HeartbeatRequest, HeartbeatResponse>(this, RequestCommand.HEARTBEAT)
);
} else {
logger.error(
- `${this.logPrefix()} Heartbeat interval set to ${
- this.getHeartbeatInterval()
- ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
- : this.getHeartbeatInterval()
- }, not starting the heartbeat`
+ `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
);
}
}
logger.error(
`${this.logPrefix()} Charging station ${
StandardParametersKey.MeterValueSampleInterval
- } configuration set to ${
- interval ? Utils.formatDurationMilliSeconds(interval) : interval
- }, not sending MeterValues`
+ } configuration set to ${interval}, not sending MeterValues`
);
}
}
this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
this.templateFileWatcher?.close();
this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
- this.bootNotificationResponse = undefined;
+ delete this.bootNotificationResponse;
this.started = false;
parentPort?.postMessage(MessageChannelUtils.buildStoppedMessage(this));
this.stopping = false;
if (params?.terminateOpened) {
this.terminateWSConnection();
}
- const ocppVersion = this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
- let protocol: string;
- switch (ocppVersion) {
- case OCPPVersion.VERSION_16:
- case OCPPVersion.VERSION_20:
- case OCPPVersion.VERSION_201:
- protocol = `ocpp${ocppVersion}`;
- break;
- default:
- this.handleUnsupportedVersion(ocppVersion);
- break;
- }
if (this.isWebSocketConnectionOpened() === true) {
logger.warn(
`${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
);
- this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
+ this.wsConnection = new WebSocket(
+ this.wsConnectionUrl,
+ `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
+ options
+ );
// Handle WebSocket message
this.wsConnection.on(
`${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
);
this.stationInfo = this.getStationInfo();
+ if (
+ this.stationInfo.firmwareStatus === FirmwareStatus.Installing &&
+ Utils.isNotEmptyString(this.stationInfo.firmwareVersion) &&
+ Utils.isNotEmptyString(this.stationInfo.firmwareVersionPattern)
+ ) {
+ const patternGroup: number | undefined =
+ this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
+ this.stationInfo.firmwareVersion?.split('.').length;
+ const match = this.stationInfo?.firmwareVersion
+ ?.match(new RegExp(this.stationInfo.firmwareVersionPattern))
+ ?.slice(1, patternGroup + 1);
+ const patchLevelIndex = match.length - 1;
+ match[patchLevelIndex] = (
+ Utils.convertToInt(match[patchLevelIndex]) +
+ this.stationInfo.firmwareUpgrade?.versionUpgrade?.step
+ ).toString();
+ this.stationInfo.firmwareVersion = match?.join('.');
+ }
this.saveStationInfo();
// Avoid duplication of connectors related information in RAM
- this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
+ delete this.stationInfo?.Connectors;
this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
if (this.getEnableStatistics() === true) {
this.performanceStatistics = PerformanceStatistics.getInstance(
// OCPP configuration
this.ocppConfiguration = this.getOcppConfiguration();
this.initializeOcppConfiguration();
+ this.initializeOcppServices();
+ if (this.stationInfo?.autoRegister === true) {
+ this.bootNotificationResponse = {
+ currentTime: new Date(),
+ interval: this.getHeartbeatInterval() / 1000,
+ status: RegistrationStatusEnumType.ACCEPTED,
+ };
+ }
+ }
+
+ private initializeOcppServices(): void {
const ocppVersion = this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
switch (ocppVersion) {
case OCPPVersion.VERSION_16:
this.handleUnsupportedVersion(ocppVersion);
break;
}
- if (this.stationInfo?.autoRegister === true) {
- this.bootNotificationResponse = {
- currentTime: new Date(),
- interval: this.getHeartbeatInterval() / 1000,
- status: RegistrationStatusEnumType.ACCEPTED,
- };
- }
- if (
- this.stationInfo.firmwareStatus === FirmwareStatus.Installing &&
- Utils.isNotEmptyString(this.stationInfo.firmwareVersion) &&
- Utils.isNotEmptyString(this.stationInfo.firmwareVersionPattern)
- ) {
- const patternGroup: number | undefined =
- this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
- this.stationInfo.firmwareVersion?.split('.').length;
- const match = this.stationInfo?.firmwareVersion
- ?.match(new RegExp(this.stationInfo.firmwareVersionPattern))
- ?.slice(1, patternGroup + 1);
- const patchLevelIndex = match.length - 1;
- match[patchLevelIndex] = (
- Utils.convertToInt(match[patchLevelIndex]) +
- this.stationInfo.firmwareUpgrade?.versionUpgrade?.step
- ).toString();
- this.stationInfo.firmwareVersion = match?.join('.');
- }
}
private initializeOcppConfiguration(): void {
}
if (
this.getSupervisionUrlOcppConfiguration() &&
+ Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
!ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
) {
ChargingStationConfigurationUtils.addConfigurationKey(
);
} else if (
!this.getSupervisionUrlOcppConfiguration() &&
+ Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
) {
ChargingStationConfigurationUtils.deleteConfigurationKey(
this.templateFile
} with connector ${connectorId} status configuration defined, undefine it`
);
- connectorStatus.status = undefined;
+ delete connectorStatus.status;
}
}
parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
}
+ private getCachedRequest(messageType: MessageType, messageId: string): CachedRequest | undefined {
+ const cachedRequest = this.requests.get(messageId);
+ if (Array.isArray(cachedRequest) === true) {
+ return cachedRequest;
+ }
+ throw new OCPPError(
+ ErrorType.PROTOCOL_ERROR,
+ `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
+ messageType
+ )} is not an array`,
+ undefined,
+ cachedRequest as JsonType
+ );
+ }
+
+ private async handleIncomingMessage(request: IncomingRequest): Promise<void> {
+ const [messageType, messageId, commandName, commandPayload] = request;
+ if (this.getEnableStatistics() === true) {
+ this.performanceStatistics?.addRequestStatistic(commandName, messageType);
+ }
+ logger.debug(
+ `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
+ request
+ )}`
+ );
+ // Process the message
+ await this.ocppIncomingRequestService.incomingRequestHandler(
+ this,
+ messageId,
+ commandName,
+ commandPayload
+ );
+ }
+
+ private handleResponseMessage(response: Response): void {
+ const [messageType, messageId, commandPayload] = response;
+ if (this.requests.has(messageId) === false) {
+ // Error
+ throw new OCPPError(
+ ErrorType.INTERNAL_ERROR,
+ `Response for unknown message id ${messageId}`,
+ undefined,
+ commandPayload
+ );
+ }
+ // Respond
+ const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest(
+ messageType,
+ messageId
+ );
+ logger.debug(
+ `${this.logPrefix()} << Command '${
+ requestCommandName ?? Constants.UNKNOWN_COMMAND
+ }' received response payload: ${JSON.stringify(response)}`
+ );
+ responseCallback(commandPayload, requestPayload);
+ }
+
+ private handleErrorMessage(errorResponse: ErrorResponse): void {
+ const [messageType, messageId, errorType, errorMessage, errorDetails] = errorResponse;
+ if (this.requests.has(messageId) === false) {
+ // Error
+ throw new OCPPError(
+ ErrorType.INTERNAL_ERROR,
+ `Error response for unknown message id ${messageId}`,
+ undefined,
+ { errorType, errorMessage, errorDetails }
+ );
+ }
+ const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId);
+ logger.debug(
+ `${this.logPrefix()} << Command '${
+ requestCommandName ?? Constants.UNKNOWN_COMMAND
+ }' received error response payload: ${JSON.stringify(errorResponse)}`
+ );
+ errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
+ }
+
private async onMessage(data: RawData): Promise<void> {
+ let request: IncomingRequest | Response | ErrorResponse;
let messageType: number;
- let messageId: string;
- let commandName: IncomingRequestCommand;
- let commandPayload: JsonType;
- let errorType: ErrorType;
- let errorMessage: string;
- let errorDetails: JsonType;
- let responseCallback: ResponseCallback;
- let errorCallback: ErrorCallback;
- let requestCommandName: RequestCommand | IncomingRequestCommand;
- let requestPayload: JsonType;
- let cachedRequest: CachedRequest;
let errMsg: string;
try {
- const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
+ request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
if (Array.isArray(request) === true) {
- [messageType, messageId] = request;
+ [messageType] = request;
// Check the type of message
switch (messageType) {
// Incoming Message
case MessageType.CALL_MESSAGE:
- [, , commandName, commandPayload] = request as IncomingRequest;
- if (this.getEnableStatistics() === true) {
- this.performanceStatistics?.addRequestStatistic(commandName, messageType);
- }
- logger.debug(
- `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
- request
- )}`
- );
- // Process the message
- await this.ocppIncomingRequestService.incomingRequestHandler(
- this,
- messageId,
- commandName,
- commandPayload
- );
+ await this.handleIncomingMessage(request as IncomingRequest);
break;
- // Outcome Message
+ // Response Message
case MessageType.CALL_RESULT_MESSAGE:
- [, , commandPayload] = request as Response;
- if (this.requests.has(messageId) === false) {
- // Error
- throw new OCPPError(
- ErrorType.INTERNAL_ERROR,
- `Response for unknown message id ${messageId}`,
- undefined,
- commandPayload
- );
- }
- // Respond
- cachedRequest = this.requests.get(messageId);
- if (Array.isArray(cachedRequest) === true) {
- [responseCallback, errorCallback, requestCommandName, requestPayload] = cachedRequest;
- } else {
- throw new OCPPError(
- ErrorType.PROTOCOL_ERROR,
- `Cached request for message id ${messageId} response is not an array`,
- undefined,
- cachedRequest as unknown as JsonType
- );
- }
- logger.debug(
- `${this.logPrefix()} << Command '${
- requestCommandName ?? Constants.UNKNOWN_COMMAND
- }' received response payload: ${JSON.stringify(request)}`
- );
- responseCallback(commandPayload, requestPayload);
+ this.handleResponseMessage(request as Response);
break;
// Error Message
case MessageType.CALL_ERROR_MESSAGE:
- [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
- if (this.requests.has(messageId) === false) {
- // Error
- throw new OCPPError(
- ErrorType.INTERNAL_ERROR,
- `Error response for unknown message id ${messageId}`,
- undefined,
- { errorType, errorMessage, errorDetails }
- );
- }
- cachedRequest = this.requests.get(messageId);
- if (Array.isArray(cachedRequest) === true) {
- [, errorCallback, requestCommandName] = cachedRequest;
- } else {
- throw new OCPPError(
- ErrorType.PROTOCOL_ERROR,
- `Cached request for message id ${messageId} error response is not an array`,
- undefined,
- cachedRequest as unknown as JsonType
- );
- }
- logger.debug(
- `${this.logPrefix()} << Command '${
- requestCommandName ?? Constants.UNKNOWN_COMMAND
- }' received error response payload: ${JSON.stringify(request)}`
- );
- errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
+ this.handleErrorMessage(request as ErrorResponse);
break;
- // Error
+ // Unknown Message
default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
errMsg = `Wrong message type ${messageType}`;
});
}
} catch (error) {
- // Log
- logger.error(
- `${this.logPrefix()} Incoming OCPP command '${
- commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
- }' message '${data.toString()}'${
- messageType !== MessageType.CALL_MESSAGE
- ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
- : ''
- } processing error:`,
- error
- );
- if (error instanceof OCPPError === false) {
- logger.warn(
- `${this.logPrefix()} Error thrown at incoming OCPP command '${
- commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
- }' message '${data.toString()}' handling is not an OCPPError:`,
- error
- );
- }
+ let commandName: IncomingRequestCommand;
+ let requestCommandName: RequestCommand | IncomingRequestCommand;
+ let errorCallback: ErrorCallback;
+ const [, messageId] = request;
switch (messageType) {
case MessageType.CALL_MESSAGE:
+ [, , commandName] = request as IncomingRequest;
// Send error
- await this.ocppRequestService.sendError(
- this,
- messageId,
- error as OCPPError,
- commandName ?? requestCommandName ?? null
- );
+ await this.ocppRequestService.sendError(this, messageId, error as OCPPError, commandName);
break;
case MessageType.CALL_RESULT_MESSAGE:
case MessageType.CALL_ERROR_MESSAGE:
- if (errorCallback) {
+ if (this.requests.has(messageId) === true) {
+ [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId);
// Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
errorCallback(error as OCPPError, false);
} else {
}
break;
}
+ if (error instanceof OCPPError === false) {
+ logger.warn(
+ `${this.logPrefix()} Error thrown at incoming OCPP command '${
+ commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
+ }' message '${data.toString()}' handling is not an OCPPError:`,
+ error
+ );
+ }
+ logger.error(
+ `${this.logPrefix()} Incoming OCPP command '${
+ commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
+ }' message '${data.toString()}'${
+ messageType !== MessageType.CALL_MESSAGE
+ ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
+ : ''
+ } processing error:`,
+ error
+ );
}
}
(this.isChargingStationAvailable() === false ||
this.isConnectorAvailable(connectorId) === false)
) {
- connectorStatus = ConnectorStatusEnum.UNAVAILABLE;
+ connectorStatus = ConnectorStatusEnum.Unavailable;
} else if (
!this.getConnectorStatus(connectorId)?.status &&
this.getConnectorStatus(connectorId)?.bootStatus
connectorStatus = this.getConnectorStatus(connectorId)?.status;
} else {
// Set default status
- connectorStatus = ConnectorStatusEnum.AVAILABLE;
+ connectorStatus = ConnectorStatusEnum.Available;
}
await this.ocppRequestService.requestHandler<
StatusNotificationRequest,
OCPPServiceUtils.buildStatusNotificationRequest(
this,
connectorId,
- ConnectorStatusEnum.UNAVAILABLE
+ ConnectorStatusEnum.Unavailable
)
);
- this.getConnectorStatus(connectorId).status = undefined;
+ delete this.getConnectorStatus(connectorId)?.status;
}
}
}
);
} else {
logger.error(
- `${this.logPrefix()} WebSocket ping interval set to ${
- webSocketPingInterval
- ? Utils.formatDurationSeconds(webSocketPingInterval)
- : webSocketPingInterval
- }, not starting the WebSocket ping`
+ `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
);
}
}
private stopWebSocketPing(): void {
if (this.webSocketPingSetInterval) {
clearInterval(this.webSocketPingSetInterval);
+ delete this.webSocketPingSetInterval;
}
}
private getConfiguredSupervisionUrl(): URL {
const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls();
if (Utils.isNotEmptyArray(supervisionUrls)) {
+ let configuredSupervisionUrlIndex: number;
switch (Configuration.getSupervisionUrlDistribution()) {
- case SupervisionUrlDistribution.ROUND_ROBIN:
- // FIXME
- this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
- break;
case SupervisionUrlDistribution.RANDOM:
- this.configuredSupervisionUrlIndex = Math.floor(
- Utils.secureRandom() * supervisionUrls.length
- );
+ configuredSupervisionUrlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
break;
+ case SupervisionUrlDistribution.ROUND_ROBIN:
case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY:
- this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
- break;
default:
- logger.error(
- `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
- SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
- }`
- );
- this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
+ Object.values(SupervisionUrlDistribution).includes(
+ Configuration.getSupervisionUrlDistribution()
+ ) === false &&
+ logger.error(
+ `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
+ SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
+ }`
+ );
+ configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
break;
}
- return new URL(supervisionUrls[this.configuredSupervisionUrlIndex]);
+ return new URL(supervisionUrls[configuredSupervisionUrlIndex]);
}
return new URL(supervisionUrls as string);
}
- private getHeartbeatInterval(): number {
- const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
- this,
- StandardParametersKey.HeartbeatInterval
- );
- if (HeartbeatInterval) {
- return Utils.convertToInt(HeartbeatInterval.value) * 1000;
- }
- const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
- this,
- StandardParametersKey.HeartBeatInterval
- );
- if (HeartBeatInterval) {
- return Utils.convertToInt(HeartBeatInterval.value) * 1000;
- }
- this.stationInfo?.autoRegister === false &&
- logger.warn(
- `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
- Constants.DEFAULT_HEARTBEAT_INTERVAL
- }`
- );
- return Constants.DEFAULT_HEARTBEAT_INTERVAL;
- }
-
private stopHeartbeat(): void {
if (this.heartbeatSetInterval) {
clearInterval(this.heartbeatSetInterval);
+ delete this.heartbeatSetInterval;
}
}
`${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
);
this.openWSConnection(
- { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout },
+ {
+ ...(this.stationInfo?.wsOptions ?? {}),
+ handshakeTimeout: reconnectTimeout,
+ },
{ closeOpened: true }
);
this.wsConnectionRestarted = true;