Refactor WebSocket handling for migration to uWebSocket
MODIFY
src/client/ocpp/json/JsonChargingStationClient.ts
src/client/ocpp/json/JsonChargingStationClient.ts
@@ -31,67 +31,67 @@ export default class JsonChargingStationClient extends ChargingStationClient {
}
public async remoteStartTransaction(params: OCPPRemoteStartTransactionCommandParam): Promise<OCPPRemoteStartTransactionCommandResult> {
- return this.sendMessage(params, Command.REMOTE_START_TRANSACTION);
+ return this.sendMessage(Command.REMOTE_START_TRANSACTION, params);
}
public async reset(params: OCPPResetCommandParam): Promise<OCPPResetCommandResult> {
- return this.sendMessage(params, Command.RESET);
+ return this.sendMessage(Command.RESET, params);
}
public async clearCache(): Promise<OCPPClearCacheCommandResult> {
- return this.sendMessage({}, Command.CLEAR_CACHE);
+ return this.sendMessage(Command.CLEAR_CACHE, {});
}
public async getConfiguration(params: OCPPGetConfigurationCommandParam = {}): Promise<OCPPGetConfigurationCommandResult> {
- return this.sendMessage(params, Command.GET_CONFIGURATION);
+ return this.sendMessage(Command.GET_CONFIGURATION, params);
}
public async changeConfiguration(params: OCPPChangeConfigurationCommandParam): Promise<OCPPChangeConfigurationCommandResult> {
- return this.sendMessage(params, Command.CHANGE_CONFIGURATION);
+ return this.sendMessage(Command.CHANGE_CONFIGURATION, params);
}
public async remoteStopTransaction(params: OCPPRemoteStopTransactionCommandParam): Promise<OCPPRemoteStopTransactionCommandResult> {
- return this.sendMessage(params, Command.REMOTE_STOP_TRANSACTION);
+ return this.sendMessage(Command.REMOTE_STOP_TRANSACTION, params);
}
public async unlockConnector(params: OCPPUnlockConnectorCommandParam): Promise<OCPPUnlockConnectorCommandResult> {
- return this.sendMessage(params, Command.UNLOCK_CONNECTOR);
+ return this.sendMessage(Command.UNLOCK_CONNECTOR, params);
}
public async setChargingProfile(params: OCPPSetChargingProfileCommandParam): Promise<OCPPSetChargingProfileCommandResult> {
- return this.sendMessage(params, Command.SET_CHARGING_PROFILE);
+ return this.sendMessage(Command.SET_CHARGING_PROFILE, params);
}
public async getCompositeSchedule(params: OCPPGetCompositeScheduleCommandParam): Promise<OCPPGetCompositeScheduleCommandResult> {
- return this.sendMessage(params, Command.GET_COMPOSITE_SCHEDULE);
+ return this.sendMessage(Command.GET_COMPOSITE_SCHEDULE, params);
}
public async clearChargingProfile(params: OCPPClearChargingProfileCommandParam): Promise<OCPPClearChargingProfileCommandResult> {
- return this.sendMessage(params, Command.CLEAR_CHARGING_PROFILE);
+ return this.sendMessage(Command.CLEAR_CHARGING_PROFILE, params);
}
public async changeAvailability(params: OCPPChangeAvailabilityCommandParam): Promise<OCPPChangeAvailabilityCommandResult> {
- return this.sendMessage(params, Command.CHANGE_AVAILABILITY);
+ return this.sendMessage(Command.CHANGE_AVAILABILITY, params);
}
public async getDiagnostics(params: OCPPGetDiagnosticsCommandParam): Promise<OCPPGetDiagnosticsCommandResult> {
- return this.sendMessage(params, Command.GET_DIAGNOSTICS);
+ return this.sendMessage(Command.GET_DIAGNOSTICS, params);
}
public async updateFirmware(params: OCPPUpdateFirmwareCommandParam): Promise<void> {
- return this.sendMessage(params, Command.UPDATE_FIRMWARE);
+ return this.sendMessage(Command.UPDATE_FIRMWARE, params);
}
public async dataTransfer(params: OCPPDataTransferCommandParam): Promise<OCPPDataTransferCommandResult> {
- return this.sendMessage(params, Command.DATA_TRANSFER);
+ return this.sendMessage(Command.DATA_TRANSFER, params);
}
public async reserveNow(params: OCPPReserveNowCommandParam): Promise<OCPPReserveNowCommandResult> {
- return this.sendMessage(params, Command.RESERVE_NOW);
+ return this.sendMessage(Command.RESERVE_NOW, params);
}
public async cancelReservation(params: OCPPCancelReservationCommandParam): Promise<OCPPCancelReservationCommandResult> {
- return this.sendMessage(params, Command.CANCEL_RESERVATION);
+ return this.sendMessage(Command.CANCEL_RESERVATION, params);
}
public setChargingStationDetails(chargingStation: ChargingStation): void {
@@ -100,13 +100,13 @@ export default class JsonChargingStationClient extends ChargingStationClient {
this.companyID = chargingStation?.companyID;
}
- private async sendMessage(params: any, command: Command): Promise<any> {
+ private async sendMessage(command: Command, params: any): Promise<any> {
// Trace
const performanceTracingData = await Logging.traceOcppMessageRequest(MODULE_NAME, this.tenant, this.chargingStationID,
`ChargingStation${command}` as ServerAction, params, '<<',
{ siteAreaID: this.siteAreaID, siteID: this.siteID, companyID: this.companyID });
// Execute
- const result = await this.wsConnection.sendMessage(Utils.generateUUID(), params, OCPPMessageType.CALL_MESSAGE, command);
+ const result = await this.wsConnection.sendMessage(Utils.generateUUID(), OCPPMessageType.CALL_MESSAGE, command, params);
// Trace
await Logging.traceOcppMessageResponse(MODULE_NAME, this.tenant, this.chargingStationID,
`ChargingStation${command}` as ServerAction, params, result, '>>',

MODIFY
src/server/ocpp/json/JsonRestWSConnection.ts
src/server/ocpp/json/JsonRestWSConnection.ts
-import WebSocket, { CloseEvent, ErrorEvent } from 'ws';
-
import BackendError from '../../../exception/BackendError';
import ChargingStationClient from '../../../client/ocpp/ChargingStationClient';
import ChargingStationStorage from '../../../storage/mongodb/ChargingStationStorage';
@@ -11,6 +9,7 @@ import OCPPUtils from '../utils/OCPPUtils';
import { ServerAction } from '../../../types/Server';
import Utils from '../../../utils/Utils';
import WSConnection from './WSConnection';
+import WebSocket from 'ws';
import global from '../../../types/GlobalType';
import http from 'http';
@@ -41,7 +40,7 @@ export default class JsonRestWSConnection extends WSConnection {
}
}
- public onError(errorEvent: ErrorEvent): void {
+ public onError(error: Error): void {
void Logging.logError({
tenantID: this.getTenantID(),
siteID: this.getSiteID(),
@@ -50,12 +49,12 @@ export default class JsonRestWSConnection extends WSConnection {
chargingStationID: this.getChargingStationID(),
module: MODULE_NAME, method: 'onError',
action: ServerAction.WS_REST_CONNECTION_ERROR,
- message: `Error ${errorEvent?.error} ${errorEvent?.message}`,
- detailedMessages: { errorEvent: errorEvent }
+ message: `Error: ${error?.message}`,
+ detailedMessages: { error: error?.stack }
});
}
- public onClose(closeEvent: CloseEvent): void {
+ public onClose(code: number, reason: Buffer): void {
// Remove the connection
this.wsServer.removeRestConnection(this);
void Logging.logInfo({
@@ -66,8 +65,8 @@ export default class JsonRestWSConnection extends WSConnection {
chargingStationID: this.getChargingStationID(),
module: MODULE_NAME, method: 'onClose',
action: ServerAction.WS_REST_CONNECTION_CLOSED,
- message: `Connection has been closed, Reason: '${closeEvent.reason ? closeEvent.reason : 'No reason given'}', Message: '${Utils.getWebSocketCloseEventStatusString(Utils.convertToInt(closeEvent))}', Code: '${closeEvent.toString()}'`,
- detailedMessages: { closeEvent }
+ message: `Connection has been closed, Reason: '${reason.toString()}', Message: '${Utils.getWebSocketCloseEventStatusString(Utils.convertToInt(code))}', Code: '${code}'`,
+ detailedMessages: { code, reason }
});
}
@@ -111,7 +110,7 @@ export default class JsonRestWSConnection extends WSConnection {
// Call the method
const result = await chargingStationClient[actionMethod](commandPayload);
// Send Response
- await this.sendMessage(messageId, result, OCPPMessageType.CALL_RESULT_MESSAGE, command);
+ await this.sendMessage(messageId, OCPPMessageType.CALL_RESULT_MESSAGE, command, result);
} else {
// Error
throw new BackendError({

MODIFY
src/server/ocpp/json/JsonWSConnection.ts
src/server/ocpp/json/JsonWSConnection.ts
@@ -2,7 +2,6 @@ import ChargingStation, { Command } from '../../../types/ChargingStation';
import { OCPPErrorType, OCPPMessageType } from '../../../types/ocpp/OCPPCommon';
import { OCPPProtocol, OCPPVersion } from '../../../types/ocpp/OCPPServer';
import { ServerAction, WSServerProtocol } from '../../../types/Server';
-import WebSocket, { CloseEvent, ErrorEvent } from 'ws';
import BackendError from '../../../exception/BackendError';
import ChargingStationClient from '../../../client/ocpp/ChargingStationClient';
@@ -19,6 +18,7 @@ import { OCPPHeader } from '../../../types/ocpp/OCPPHeader';
import OCPPUtils from '../utils/OCPPUtils';
import Utils from '../../../utils/Utils';
import WSConnection from './WSConnection';
+import WebSocket from 'ws';
import http from 'http';
const MODULE_NAME = 'JsonWSConnection';
@@ -98,7 +98,7 @@ export default class JsonWSConnection extends WSConnection {
}
}
- public onError(errorEvent: ErrorEvent): void {
+ public onError(error: Error): void {
void Logging.logError({
tenantID: this.getTenantID(),
siteID: this.getSiteID(),
@@ -107,12 +107,12 @@ export default class JsonWSConnection extends WSConnection {
chargingStationID: this.getChargingStationID(),
action: ServerAction.WS_JSON_CONNECTION_ERROR,
module: MODULE_NAME, method: 'onError',
- message: `Error occurred: ${errorEvent?.message}`,
- detailedMessages: { errorEvent }
+ message: `Error occurred: ${error?.message}`,
+ detailedMessages: { error: error.stack }
});
}
- public onClose(closeEvent: CloseEvent): void {
+ public onClose(code: number, reason: Buffer): void {
// Remove the connection
this.wsServer.removeJsonConnection(this);
void Logging.logInfo({
@@ -123,8 +123,8 @@ export default class JsonWSConnection extends WSConnection {
chargingStationID: this.getChargingStationID(),
action: ServerAction.WS_JSON_CONNECTION_CLOSED,
module: MODULE_NAME, method: 'onClose',
- message: `Connection has been closed, Reason: '${closeEvent.reason ? closeEvent.reason : 'No reason given'}', Message: '${Utils.getWebSocketCloseEventStatusString(Utils.convertToInt(closeEvent))}', Code: '${closeEvent.toString()}'`,
- detailedMessages: { closeEvent }
+ message: `Connection has been closed, Reason: '${reason?.toString()}', Message: '${Utils.getWebSocketCloseEventStatusString(Utils.convertToInt(code))}', Code: '${code}'`,
+ detailedMessages: { code, reason }
});
}
@@ -166,7 +166,7 @@ export default class JsonWSConnection extends WSConnection {
// Call it
result = await this.chargingStationService[methodName](this.headers, commandPayload);
// Send Response
- await this.sendMessage(messageId, result, OCPPMessageType.CALL_RESULT_MESSAGE, command);
+ await this.sendMessage(messageId, OCPPMessageType.CALL_RESULT_MESSAGE, command, result);
} finally {
// Clean the header
delete this.headers.chargingStation;

MODIFY
src/server/ocpp/json/WSConnection.ts
src/server/ocpp/json/WSConnection.ts
import ChargingStation, { Command } from '../../../types/ChargingStation';
-import { OCPPErrorType, OCPPIncomingRequest, OCPPMessageType, OCPPRequest } from '../../../types/ocpp/OCPPCommon';
-import WebSocket, { CLOSED, CLOSING, CONNECTING, CloseEvent, ErrorEvent, MessageEvent, OPEN } from 'ws';
+import { FctOCPPReject, FctOCPPResponse, OCPPErrorType, OCPPIncomingRequest, OCPPIncomingResponse, OCPPMessageType, OCPPRequest } from '../../../types/ocpp/OCPPCommon';
+import WebSocket, { CLOSED, CLOSING, CONNECTING, OPEN } from 'ws';
import BackendError from '../../../exception/BackendError';
import Constants from '../../../utils/Constants';
@@ -29,7 +29,7 @@ export default abstract class WSConnection {
private url: string;
private clientIP: string | string[];
private wsConnection: WebSocket;
- private requests: { [id: string]: OCPPRequest } = {};
+ private ocppRequests: Record<string, OCPPRequest> = {};
constructor(wsConnection: WebSocket, req: http.IncomingMessage, wsServer: JsonCentralSystemServer) {
// Init
@@ -67,117 +67,79 @@ export default abstract class WSConnection {
}
}
- public async onMessage(messageEvent: MessageEvent): Promise<void> {
- let [messageType, messageId, command, commandPayload, errorDetails]: OCPPIncomingRequest = [0, '', '' as Command, '', {}];
- let responseCallback: (payload?: Record<string, unknown> | string) => void;
- let rejectCallback: (reason?: OCPPError) => void;
+ public async onMessage(wsData: WebSocket.RawData, isBinary: boolean): Promise<void> {
+ let responseCallback: FctOCPPResponse;
+ let rejectCallback: FctOCPPReject;
+ let command: Command, commandPayload: Record<string, any>, errorDetails: Record<string, any>;
+ const ocppMessage: OCPPIncomingRequest|OCPPIncomingResponse = JSON.parse(wsData.toString());
+ // Parse the data
+ const [messageType, messageID] = ocppMessage;
try {
- // Parse the message
- [messageType, messageId, command, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as OCPPIncomingRequest;
// Wait for init
await this.waitForInitialization();
// Check the Type of message
switch (messageType) {
// Incoming Message
case OCPPMessageType.CALL_MESSAGE:
+ // Get the data
+ [,,command,commandPayload] = ocppMessage as OCPPIncomingRequest;
// Process the call
- await this.handleRequest(messageId, command, commandPayload);
+ await this.handleRequest(messageID, command, commandPayload);
break;
// Outcome Message
case OCPPMessageType.CALL_RESULT_MESSAGE:
+ // Get the data
+ [,,commandPayload] = ocppMessage as OCPPIncomingResponse;
// Respond
- if (Utils.isIterable(this.requests[messageId])) {
- [responseCallback] = this.requests[messageId];
- } else {
- throw new BackendError({
- chargingStationID: this.getChargingStationID(),
- siteID: this.getSiteID(),
- siteAreaID: this.getSiteAreaID(),
- companyID: this.getCompanyID(),
- module: MODULE_NAME,
- method: 'onMessage',
- message: `Response request for message id ${messageId} is not iterable`,
- action: OCPPUtils.buildServerActionFromOcppCommand(command)
- });
- }
+ [responseCallback,,command] = this.ocppRequests[messageID];
if (!responseCallback) {
- // Error
throw new BackendError({
chargingStationID: this.getChargingStationID(),
siteID: this.getSiteID(),
siteAreaID: this.getSiteAreaID(),
companyID: this.getCompanyID(),
- module: MODULE_NAME,
- method: 'onMessage',
- message: `Response request for unknown message id ${messageId}`,
- action: OCPPUtils.buildServerActionFromOcppCommand(command)
+ module: MODULE_NAME, method: 'onMessage',
+ message: `Unknwon OCPP Request for '${wsData.toString()}'`,
});
}
- delete this.requests[messageId];
- responseCallback(command);
+ delete this.ocppRequests[messageID];
+ responseCallback(commandPayload);
break;
// Error Message
case OCPPMessageType.CALL_ERROR_MESSAGE:
- // Log
- await Logging.logError({
- tenantID: this.getTenantID(),
- module: MODULE_NAME,
- method: 'onMessage',
- action: OCPPUtils.buildServerActionFromOcppCommand(command),
- message: `Error occurred '${command}' with message content '${JSON.stringify(commandPayload)}'`,
- detailedMessages: { messageType, messageId, command, commandPayload, errorDetails }
- });
- if (!this.requests[messageId]) {
- // Error
+ [,,commandPayload,errorDetails] = ocppMessage as OCPPIncomingResponse;
+ [,rejectCallback,command] = this.ocppRequests[messageID];
+ if (!rejectCallback) {
throw new BackendError({
chargingStationID: this.getChargingStationID(),
siteID: this.getSiteID(),
siteAreaID: this.getSiteAreaID(),
companyID: this.getCompanyID(),
- module: MODULE_NAME,
- method: 'onMessage',
- message: `Error request for unknown message id ${messageId}`,
- action: OCPPUtils.buildServerActionFromOcppCommand(command)
- });
- }
- if (Utils.isIterable(this.requests[messageId])) {
- [, rejectCallback] = this.requests[messageId];
- } else {
- throw new BackendError({
- chargingStationID: this.getChargingStationID(),
- siteID: this.getSiteID(),
- siteAreaID: this.getSiteAreaID(),
- companyID: this.getCompanyID(),
- module: MODULE_NAME,
- method: 'onMessage',
- message: `Error request for message id ${messageId} is not iterable`,
- action: OCPPUtils.buildServerActionFromOcppCommand(command)
+ module: MODULE_NAME, method: 'onMessage',
+ message: `Unknwon OCPP Request for '${wsData.toString()}'`,
+ detailedMessages: { messageType, messageID, commandPayload, errorDetails }
});
}
- delete this.requests[messageId];
+ delete this.ocppRequests[messageID];
rejectCallback(new OCPPError({
chargingStationID: this.getChargingStationID(),
siteID: this.getSiteID(),
siteAreaID: this.getSiteAreaID(),
companyID: this.getCompanyID(),
- module: MODULE_NAME,
- method: 'onMessage',
+ module: MODULE_NAME, method: 'onMessage',
code: command,
- message: commandPayload.toString(),
- details: { errorDetails }
+ message: wsData.toString(),
}));
break;
- // Error
default:
throw new BackendError({
chargingStationID: this.getChargingStationID(),
siteID: this.getSiteID(),
siteAreaID: this.getSiteAreaID(),
companyID: this.getCompanyID(),
- module: MODULE_NAME,
- method: 'onMessage',
- message: `Wrong message type ${messageType}`,
- action: OCPPUtils.buildServerActionFromOcppCommand(command)
+ action: OCPPUtils.buildServerActionFromOcppCommand(command),
+ module: MODULE_NAME, method: 'onMessage',
+ message: `Wrong OCPP Message Type '${messageType as string}' for '${wsData.toString()}'`,
});
}
} catch (error) {
@@ -190,9 +152,9 @@ export default abstract class WSConnection {
action: OCPPUtils.buildServerActionFromOcppCommand(command),
message: `${error.message as string}`,
module: MODULE_NAME, method: 'onMessage',
- detailedMessages: { messageEvent, error: error.stack }
+ detailedMessages: { data: wsData, error: error.stack }
});
- await this.sendError(messageId, error);
+ await this.sendError(messageID, error);
}
}
@@ -209,47 +171,42 @@ export default abstract class WSConnection {
}
public async sendError(messageId: string, error: OCPPError): Promise<unknown> {
- // Send error
- return this.sendMessage(messageId, error, OCPPMessageType.CALL_ERROR_MESSAGE);
+ return this.sendMessage(messageId, OCPPMessageType.CALL_ERROR_MESSAGE, null, null, error);
}
- public async sendMessage(messageId: string, commandParams: Record<string, unknown> | OCPPError, messageType: OCPPMessageType,
- command?: Command): Promise<unknown> {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const self = this;
+ public async sendMessage(messageID: string, messageType: OCPPMessageType, command: Command, commandParams: Record<string, unknown>, error?: OCPPError): Promise<unknown> {
// Create a promise
- return await new Promise((resolve, reject) => {
+ return new Promise((resolve, reject) => {
let messageToSend: string;
// Function that will receive the request's response
- function responseCallback(payload: Record<string, unknown> | string): void {
+ const responseCallback = (payload: Record<string, unknown> | string): void => {
// Send the response
resolve(payload);
- }
+ };
// Function that will receive the request's rejection
- function rejectCallback(reason: string | OCPPError): void {
+ const rejectCallback = (reason: string | OCPPError): void => {
// Build Exception
- self.requests[messageId] = [() => { }, () => { }];
- const error = reason instanceof OCPPError ? reason : new Error(reason);
+ const ocppError = reason instanceof OCPPError ? reason : new Error(reason);
// Send error
- reject(error);
- }
+ reject(ocppError);
+ };
// Type of message
switch (messageType) {
// Request
case OCPPMessageType.CALL_MESSAGE:
// Build request
- this.requests[messageId] = [responseCallback, rejectCallback];
- messageToSend = JSON.stringify([messageType, messageId, command, commandParams]);
+ this.ocppRequests[messageID] = [responseCallback, rejectCallback, command];
+ messageToSend = JSON.stringify([messageType, messageID, command, commandParams]);
break;
// Response
case OCPPMessageType.CALL_RESULT_MESSAGE:
// Build response
- messageToSend = JSON.stringify([messageType, messageId, commandParams]);
+ messageToSend = JSON.stringify([messageType, messageID, commandParams]);
break;
// Error Message
case OCPPMessageType.CALL_ERROR_MESSAGE:
// Build Error Message
- messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : OCPPErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
+ messageToSend = JSON.stringify([messageType, messageID, error.code ? error.code : OCPPErrorType.GENERIC_ERROR, error.message ? error.message : '', error.details ? error.details : {}]);
break;
}
// Check if wsConnection is ready
@@ -258,7 +215,7 @@ export default abstract class WSConnection {
this.wsConnection.send(messageToSend);
} else {
// Reject it
- return rejectCallback(`WebSocket closed for Message ID '${messageId}' with content '${messageToSend}' (${this.tenantSubdomain})`);
+ return rejectCallback(`WebSocket closed for Message ID '${messageID}' with content '${messageToSend}' (${this.tenantSubdomain})`);
}
// Response?
if (messageType !== OCPPMessageType.CALL_MESSAGE) {
@@ -266,7 +223,7 @@ export default abstract class WSConnection {
resolve();
} else {
// Send timeout
- setTimeout(() => rejectCallback(`Timeout for Message ID '${messageId}' with content '${messageToSend} (${this.tenantSubdomain})`), Constants.OCPP_SOCKET_TIMEOUT);
+ setTimeout(() => rejectCallback(`Timeout for Message ID '${messageID}' with content '${messageToSend} (${this.tenantSubdomain})`), Constants.OCPP_SOCKET_TIMEOUT);
}
});
}
@@ -436,7 +393,7 @@ export default abstract class WSConnection {
public abstract handleRequest(messageId: string, command: Command, commandPayload: Record<string, unknown> | string): Promise<void>;
- public abstract onError(errorEvent: ErrorEvent): void;
+ public abstract onError(error: Error): void;
- public abstract onClose(closeEvent: CloseEvent): void;
+ public abstract onClose(code: number, reason: Buffer): void;
}

MODIFY
src/server/rest/v1/service/RegistrationTokenService.ts
src/server/rest/v1/service/RegistrationTokenService.ts
@@ -79,9 +79,6 @@ export default class RegistrationTokenService {
// Save
registrationToken.id = await RegistrationTokenStorage.saveRegistrationToken(req.tenant, registrationToken);
// Build OCPP URLs
- registrationToken.ocpp15SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16JSONUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
registrationToken.ocpp15SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16JSONSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
@@ -135,9 +132,6 @@ export default class RegistrationTokenService {
// Save
registrationToken.id = await RegistrationTokenStorage.saveRegistrationToken(req.tenant, registrationToken);
// Build OCPP URLs
- registrationToken.ocpp15SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16JSONUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
registrationToken.ocpp15SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16JSONSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
@@ -259,9 +253,6 @@ export default class RegistrationTokenService {
);
// Build OCPP URLs
for (const registrationToken of registrationTokens.result) {
- registrationToken.ocpp15SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16JSONUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
registrationToken.ocpp15SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16JSONSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
@@ -299,9 +290,6 @@ export default class RegistrationTokenService {
});
}
// Build OCPP URLs
- registrationToken.ocpp15SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16SOAPUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
- registrationToken.ocpp16JSONUrl = Utils.buildOCPPServerURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);
registrationToken.ocpp15SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_15, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16SOAPSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.SOAP, registrationToken.id);
registrationToken.ocpp16JSONSecureUrl = Utils.buildOCPPServerSecureURL(req.user.tenantID, OCPPVersion.VERSION_16, OCPPProtocol.JSON, registrationToken.id);

MODIFY
src/types/ocpp/OCPPCommon.ts
src/types/ocpp/OCPPCommon.ts
import { Command } from '../ChargingStation';
import OCPPError from '../../exception/OcppError';
-export type OCPPRequest = [(payload?: Record<string, unknown> | string) => void, (reason?: OCPPError) => void];
+export type FctOCPPResponse = (payload?: Record<string, unknown> | string) => void;
+export type FctOCPPReject = (reason?: OCPPError) => void;
-export type OCPPIncomingRequest = [OCPPMessageType, string, Command, Record<string, unknown> | string, Record<string, unknown>];
+export type OCPPRequest = [FctOCPPResponse, FctOCPPReject, Command];
+
+export type OCPPIncomingRequest = [OCPPMessageType, string, Command, Record<string, unknown>, Record<string, unknown>];
+export type OCPPIncomingResponse = [OCPPMessageType, string, Record<string, unknown>, Record<string, unknown>];
export type OCPPOutgoingRequest = [OCPPMessageType, string, Command, Record<string, unknown>];

MODIFY
src/utils/Logging.ts
src/utils/Logging.ts
@@ -48,7 +48,7 @@ export default class Logging {
const sizeOfResponseDataKB = Utils.truncTo(Utils.createDecimal(
sizeof(response)).div(1024).toNumber(), 2);
const numberOfRecords = Array.isArray(response) ? response.length : 0;
- const message = `${module}.${method} - ${executionDurationMillis.toString()} ms - Req ${(sizeOfRequestDataKB > 0) ? sizeOfRequestDataKB : '?'} KB - Res ${(sizeOfResponseDataKB > 0) ? sizeOfResponseDataKB : '?'} KB - ${numberOfRecords.toString()} rec(s)`;
+ const message = `${module}.${method} - ${executionDurationMillis.toString()} ms - Req ${sizeOfRequestDataKB} KB - Res ${(sizeOfResponseDataKB > 0) ? sizeOfResponseDataKB : '?'} KB - ${numberOfRecords.toString()} rec(s)`;
Utils.isDevelopmentEnv() && console.debug(chalk.green(message));
if (sizeOfResponseDataKB > Constants.PERF_MAX_DATA_VOLUME_KB) {
const error = new Error(`Data must be < ${Constants.PERF_MAX_DATA_VOLUME_KB}KB, got ${sizeOfResponseDataKB}KB`);
@@ -593,7 +593,7 @@ export default class Logging {
// Compute size
const sizeOfRequestDataKB = Utils.truncTo(Utils.createDecimal(
sizeof(request)).div(1024).toNumber(), 2);
- const message = `${direction} OCPP Request '${action}' - Req ${(sizeOfRequestDataKB > 0) ? sizeOfRequestDataKB : '?'} KB - ${direction === '>>' ? 'Received' : 'Sent'}`;
+ const message = `${direction} OCPP Request '${action}' - Req ${sizeOfRequestDataKB} KB - ${direction === '>>' ? 'Received' : 'Sent'}`;
Utils.isDevelopmentEnv() && console.debug(chalk.green(message));
await Logging.logDebug({
tenantID: tenant.id,

Refactor WebSocket handling for migration to uWebSocket