import Connectors, { Connector } from '../types/Connectors';
import { MeterValue, MeterValueLocation, MeterValueMeasurand, MeterValuePhase, MeterValueUnit, MeterValuesRequest, MeterValuesResponse, SampledValue } from '../types/ocpp/1.6/MeterValues';
import { PerformanceObserver, performance } from 'perf_hooks';
-import Requests, { BootNotificationRequest, ChangeConfigurationRequest, GetConfigurationRequest, HeartbeatRequest, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests';
+import Requests, { BootNotificationRequest, ChangeConfigurationRequest, GetConfigurationRequest, HeartbeatRequest, IncomingRequest, IncomingRequestCommand, RemoteStartTransactionRequest, RemoteStopTransactionRequest, Request, RequestCommand, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests';
import WebSocket, { MessageEvent } from 'ws';
import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
import Configuration from '../utils/Configuration';
import Constants from '../utils/Constants';
import ElectricUtils from '../utils/ElectricUtils';
+import { ErrorType } from '../types/ocpp/ErrorType';
import MeasurandValues from '../types/MeasurandValues';
+import { MessageType } from '../types/ocpp/MessageType';
import OCPPError from './OcppError';
import Statistics from '../utils/Statistics';
import Utils from '../utils/Utils';
this._openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
this._hasSocketRestarted = true;
} else if (this._getAutoReconnectMaxRetries() !== -1) {
- logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`);
+ logger.error(`${this._logPrefix()} Socket reconnect failure: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`);
}
}
}
}
} else {
- logger.error(`${this._logPrefix()} Registration: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`);
+ logger.error(`${this._logPrefix()} Registration failure: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`);
}
this._autoReconnectRetryCount = 0;
this._hasSocketRestarted = false;
}
async onMessage(messageEvent: MessageEvent): Promise<void> {
- let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
+ let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, '', ''];
+ let responseCallback: (payload?, requestPayload?) => void;
+ let rejectCallback: (error: OCPPError) => void;
+ let requestPayload: Record<string, unknown>;
+ let errMsg: string;
try {
// Parse the message
- [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString());
+ [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
// Check the Type of message
switch (messageType) {
// Incoming Message
- case Constants.OCPP_JSON_CALL_MESSAGE:
+ case MessageType.CALL_MESSAGE:
if (this.getEnableStatistics()) {
this._statistics.addMessage(commandName, messageType);
}
await this.handleRequest(messageId, commandName, commandPayload);
break;
// Outcome Message
- case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
+ case MessageType.CALL_RESULT_MESSAGE:
// Respond
- // eslint-disable-next-line no-case-declarations
- let responseCallback; let requestPayload;
if (Utils.isIterable(this._requests[messageId])) {
[responseCallback, , requestPayload] = this._requests[messageId];
} else {
responseCallback(commandName, requestPayload);
break;
// Error Message
- case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
+ case MessageType.CALL_ERROR_MESSAGE:
if (!this._requests[messageId]) {
// Error
throw new Error(`Error request for unknown message id ${messageId}`);
}
- // eslint-disable-next-line no-case-declarations
- let rejectCallback;
if (Utils.isIterable(this._requests[messageId])) {
[, rejectCallback] = this._requests[messageId];
} else {
break;
// Error
default:
- // eslint-disable-next-line no-case-declarations
- const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
+ errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
logger.error(errMsg);
throw new Error(errMsg);
}
} catch (error) {
// Log
- logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent, error, this._requests[messageId]);
+ logger.error('%s Incoming message %j processing error %j on request content type %j', this._logPrefix(), messageEvent, error, this._requests[messageId]);
// Send error
- messageType !== Constants.OCPP_JSON_CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName);
+ messageType !== MessageType.CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName);
}
}
async sendHeartbeat(): Promise<void> {
try {
const payload: HeartbeatRequest = {};
- await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
+ await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.HEARTBEAT);
} catch (error) {
- logger.error(this._logPrefix() + ' Send Heartbeat error: %j', error);
- throw error;
+ this.handleRequestError(RequestCommand.HEARTBEAT, error);
}
}
async sendBootNotification(): Promise<BootNotificationResponse> {
try {
- return await this.sendMessage(Utils.generateUUID(), this._bootNotificationRequest, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification') as BootNotificationResponse;
+ return await this.sendMessage(Utils.generateUUID(), this._bootNotificationRequest, MessageType.CALL_MESSAGE, RequestCommand.BOOT_NOTIFICATION) as BootNotificationResponse;
} catch (error) {
- logger.error(this._logPrefix() + ' Send BootNotification error: %j', error);
- throw error;
+ this.handleRequestError(RequestCommand.BOOT_NOTIFICATION, error);
}
}
errorCode,
status,
};
- await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
+ await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.STATUS_NOTIFICATION);
} catch (error) {
- logger.error(this._logPrefix() + ' Send StatusNotification error: %j', error);
- throw error;
+ this.handleRequestError(RequestCommand.STATUS_NOTIFICATION, error);
}
}
meterStart: 0,
timestamp: new Date().toISOString(),
};
- return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction') as StartTransactionResponse;
+ return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.START_TRANSACTION) as StartTransactionResponse;
} catch (error) {
- logger.error(this._logPrefix() + ' Send StartTransaction error: %j', error);
- throw error;
+ this.handleRequestError(RequestCommand.START_TRANSACTION, error);
}
}
timestamp: new Date().toISOString(),
...reason && { reason },
};
- return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction') as StartTransactionResponse;
+ return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.STOP_TRANSACTION) as StartTransactionResponse;
} catch (error) {
- logger.error(this._logPrefix() + ' Send StopTransaction error: %j', error);
- throw error;
+ this.handleRequestError(RequestCommand.STOP_TRANSACTION, error);
}
}
transactionId: self.getConnector(connectorId).transactionId,
meterValue: meterValue,
};
- await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
+ await self.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.METERVALUES);
} catch (error) {
- logger.error(self._logPrefix() + ' Send MeterValues error: %j', error);
- throw error;
+ this.handleRequestError(RequestCommand.METERVALUES, error);
}
}
- async sendError(messageId: string, err: Error | OCPPError, commandName: string): Promise<unknown> {
+ async sendError(messageId: string, err: Error | OCPPError, commandName: RequestCommand | IncomingRequestCommand): Promise<unknown> {
// Check exception type: only OCPP error are accepted
- const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack);
+ const error = err instanceof OCPPError ? err : new OCPPError(ErrorType.INTERNAL_ERROR, err.message, err.stack && err.stack);
// Send error
- return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName);
+ return this.sendMessage(messageId, error, MessageType.CALL_ERROR_MESSAGE, commandName);
}
- async sendMessage(messageId: string, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string): Promise<any> {
+ async sendMessage(messageId: string, commandParams, messageType = MessageType.CALL_RESULT_MESSAGE, commandName: RequestCommand | IncomingRequestCommand): Promise<any> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
// Send a message through wsConnection
return new Promise((resolve: (value?: any | PromiseLike<any>) => void, reject: (reason?: any) => void) => {
- let messageToSend;
+ let messageToSend: string;
// Type of message
switch (messageType) {
// Request
- case Constants.OCPP_JSON_CALL_MESSAGE:
+ case MessageType.CALL_MESSAGE:
// Build request
- this._requests[messageId] = [responseCallback, rejectCallback, commandParams];
+ this._requests[messageId] = [responseCallback, rejectCallback, commandParams] as Request;
messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
break;
// Response
- case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
+ case MessageType.CALL_RESULT_MESSAGE:
// Build response
messageToSend = JSON.stringify([messageType, messageId, commandParams]);
break;
// Error Message
- case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
+ case MessageType.CALL_ERROR_MESSAGE:
// Build Error Message
- messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
+ messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
break;
}
// Check if wsConnection opened and charging station registered
- if (this._isWebSocketOpen() && (this._isRegistered() || commandName === 'BootNotification')) {
+ if (this._isWebSocketOpen() && (this._isRegistered() || commandName === RequestCommand.BOOT_NOTIFICATION)) {
if (this.getEnableStatistics()) {
this._statistics.addMessage(commandName, messageType);
}
// Handle dups in buffer
for (const message of this._messageQueue) {
// Same message
- if (JSON.stringify(messageToSend) === JSON.stringify(message)) {
+ if (messageToSend === message) {
dups = true;
break;
}
this._messageQueue.push(messageToSend);
}
// Reject it
- return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
+ return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
}
// Response?
- if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) {
+ if (messageType === MessageType.CALL_RESULT_MESSAGE) {
// Yes: send Ok
resolve();
- } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) {
+ } else if (messageType === MessageType.CALL_ERROR_MESSAGE) {
// Send timeout
- setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_SOCKET_TIMEOUT);
+ setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_ERROR_TIMEOUT);
}
// Function that will receive the request's response
self._statistics.addMessage(commandName, messageType);
}
// Send the response
- await self.handleResponse(commandName, payload, requestPayload);
+ await self.handleResponse(commandName as RequestCommand, payload, requestPayload);
resolve(payload);
}
});
}
- async handleResponse(commandName: string, payload, requestPayload): Promise<void> {
+ async handleResponse(commandName: RequestCommand, payload, requestPayload): Promise<void> {
const responseCallbackFn = 'handleResponse' + commandName;
if (typeof this[responseCallbackFn] === 'function') {
await this[responseCallbackFn](payload, requestPayload);
logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
}
- async handleRequest(messageId: string, commandName: string, commandPayload): Promise<void> {
+ async handleRequest(messageId: string, commandName: IncomingRequestCommand, commandPayload): Promise<void> {
let response;
// Call
if (typeof this['handleRequest' + commandName] === 'function') {
}
} else {
// Throw exception
- await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName);
+ await this.sendError(messageId, new OCPPError(ErrorType.NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName);
throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
}
// Send response
- await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName);
+ await this.sendMessage(messageId, response, MessageType.CALL_RESULT_MESSAGE, commandName);
}
// Simulate charging station restart
logger.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
return Constants.OCPP_RESPONSE_REJECTED;
}
+
+ private handleRequestError(commandName: RequestCommand, error: Error) {
+ logger.error(this._logPrefix() + ' Send ' + commandName + ' error: %j', error);
+ throw error;
+ }
}