- if (isMainThread && this.started === true) {
- await this.workerImplementation.stop();
- this.workerImplementation = null;
- this.uiServer?.stop();
- await this.storage?.close();
- this.started = false;
+ if (!isMainThread) {
+ throw new BaseError('Cannot stop charging stations simulator from worker thread');
+ }
+ if (this.started === true) {
+ if (this.stopping === false) {
+ this.stopping = true;
+ await this.uiServer?.sendInternalRequest(
+ this.uiServer.buildProtocolRequest(
+ generateUUID(),
+ ProcedureName.STOP_CHARGING_STATION,
+ Constants.EMPTY_FREEZED_OBJECT,
+ ),
+ );
+ await Promise.race([
+ waitChargingStationEvents(
+ this,
+ ChargingStationWorkerMessageEvents.stopped,
+ this.numberOfChargingStations,
+ ),
+ new Promise<string>((resolve) => {
+ setTimeout(() => {
+ const message = `Timeout reached ${formatDurationMilliSeconds(
+ Constants.STOP_SIMULATOR_TIMEOUT,
+ )} at stopping charging stations simulator`;
+ console.warn(chalk.yellow(message));
+ resolve(message);
+ }, Constants.STOP_SIMULATOR_TIMEOUT);
+ }),
+ ]);
+ await this.workerImplementation?.stop();
+ this.workerImplementation = null;
+ this.uiServer?.stop();
+ await this.storage?.close();
+ this.resetCounters();
+ this.initializedCounters = false;
+ this.started = false;
+ this.stopping = false;
+ } else {
+ console.error(chalk.red('Cannot stop an already stopping charging stations simulator'));
+ }