// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
+import { EventEmitter } from 'node:events';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { type Worker, isMainThread } from 'node:worker_threads';
noChargingStationTemplates = 2,
}
-export class Bootstrap {
+export class Bootstrap extends EventEmitter {
private static instance: Bootstrap | null = null;
public numberOfChargingStations!: number;
public numberOfChargingStationTemplates!: number;
private readonly workerScript: string;
private constructor() {
+ super();
for (const signal of ['SIGINT', 'SIGQUIT', 'SIGTERM']) {
- process.on(signal, () => {
- this.gracefulShutdown().catch(Constants.EMPTY_FUNCTION);
- });
+ process.on(signal, this.gracefulShutdown);
}
// Enable unconditionally for now
ErrorUtils.handleUnhandledRejection();
public async stop(): Promise<void> {
if (isMainThread && this.started === true) {
await this.uiServer?.sendBroadcastChannelRequest(
- Utils.generateUUID(),
- ProcedureName.STOP_CHARGING_STATION,
- Constants.EMPTY_FREEZED_OBJECT
+ this.uiServer.buildProtocolRequest(
+ Utils.generateUUID(),
+ ProcedureName.STOP_CHARGING_STATION,
+ Constants.EMPTY_FREEZED_OBJECT
+ )
);
+ await this.waitForChargingStationsStopped();
await this.workerImplementation?.stop();
this.workerImplementation = null;
this.uiServer?.stop();
switch (msg.id) {
case ChargingStationWorkerMessageEvents.started:
this.workerEventStarted(msg.data as ChargingStationData);
+ this.emit(ChargingStationWorkerMessageEvents.started, msg.data as ChargingStationData);
break;
case ChargingStationWorkerMessageEvents.stopped:
this.workerEventStopped(msg.data as ChargingStationData);
+ this.emit(ChargingStationWorkerMessageEvents.stopped, msg.data as ChargingStationData);
break;
case ChargingStationWorkerMessageEvents.updated:
this.workerEventUpdated(msg.data as ChargingStationData);
+ this.emit(ChargingStationWorkerMessageEvents.updated, msg.data as ChargingStationData);
break;
case ChargingStationWorkerMessageEvents.performanceStatistics:
this.workerEventPerformanceStatistics(msg.data as Statistics);
+ this.emit(
+ ChargingStationWorkerMessageEvents.performanceStatistics,
+ msg.data as Statistics
+ );
break;
default:
throw new BaseError(
});
}
- private gracefulShutdown = async (): Promise<void> => {
+ private gracefulShutdown = (): void => {
console.info(`${chalk.green('Graceful shutdown')}`);
- try {
- await this.stop();
- process.exit(0);
- } catch (error) {
- process.exit(1);
- }
+ this.stop()
+ .then(() => {
+ process.exit(0);
+ })
+ .catch((error) => {
+ console.error(chalk.red('Error while stopping charging stations simulator:'), error);
+ process.exit(1);
+ });
+ };
+
+ private waitForChargingStationsStopped = async (): Promise<void> => {
+ return new Promise((resolve) => {
+ let stoppedEvents = 0;
+ this.on(ChargingStationWorkerMessageEvents.stopped, () => {
+ ++stoppedEvents;
+ if (stoppedEvents === this.numberOfChargingStations) {
+ resolve();
+ }
+ });
+ });
};
private logPrefix = (): string => {
type ProcedureName,
type ProtocolRequest,
type ProtocolResponse,
- type ProtocolVersion,
+ ProtocolVersion,
type RequestPayload,
type ResponsePayload,
type UIServerConfiguration,
this.chargingStations.clear();
}
- public async sendBroadcastChannelRequest(
- id: string,
- procedureName: ProcedureName,
- requestPayload: RequestPayload
- ): Promise<void> {
- for (const uiService of this.uiServices.values()) {
- await uiService.requestHandler(this.buildProtocolRequest(id, procedureName, requestPayload));
- }
+ public async sendBroadcastChannelRequest(request: ProtocolRequest): Promise<ProtocolResponse> {
+ const protocolVersion = ProtocolVersion['0.0.1'];
+ this.registerProtocolVersionUIService(protocolVersion);
+ return this.uiServices.get(protocolVersion)?.requestHandler(request);
}
protected startHttpServer(): void {
ProcedureName,
type ProtocolRequest,
type ProtocolRequestHandler,
+ type ProtocolResponse,
type ProtocolVersion,
type RequestPayload,
type ResponsePayload,
this.broadcastChannelRequests = new Map<string, number>();
}
- public async requestHandler(request: ProtocolRequest): Promise<void> {
+ public async requestHandler(request: ProtocolRequest): Promise<ProtocolResponse | undefined> {
let messageId: string;
let command: ProcedureName;
let requestPayload: RequestPayload | undefined;
- let responsePayload: ResponsePayload;
+ let responsePayload: ResponsePayload | undefined;
try {
[messageId, command, requestPayload] = request;
errorStack: (error as Error).stack,
errorDetails: (error as OCPPError).details,
};
- } finally {
- // Send response for payload not forwarded to broadcast channel
- if (!Utils.isNullOrUndefined(responsePayload)) {
- this.sendResponse(messageId, responsePayload);
- }
+ }
+ // Send response
+ if (!Utils.isNullOrUndefined(responsePayload)) {
+ this.sendResponse(messageId, responsePayload);
+ return this.uiServer.buildProtocolResponse(messageId, responsePayload);
}
}