+ const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
+ if (Array.isArray(request) === true) {
+ [messageType, messageId] = 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
+ );
+ break;
+ // Outcome 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}`,
+ null,
+ 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`,
+ null,
+ cachedRequest as unknown as JsonType
+ );
+ }
+ logger.debug(
+ `${this.logPrefix()} << Command '${
+ requestCommandName ?? Constants.UNKNOWN_COMMAND
+ }' received response payload: ${JSON.stringify(request)}`
+ );
+ responseCallback(commandPayload, requestPayload);
+ 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}`,
+ null,
+ { 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`,
+ null,
+ 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));
+ break;
+ // Error
+ default:
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
+ errMsg = `Wrong message type ${messageType}`;
+ logger.error(`${this.logPrefix()} ${errMsg}`);
+ throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
+ }
+ parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));