- public async stop(): Promise<void> {
- if (!isMainThread) {
- throw new Error('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;
+ public async stop (stopChargingStations = true): Promise<void> {
+ if (this.started) {
+ if (!this.stopping) {
+ this.stopping = true
+ if (stopChargingStations) {
+ await this.uiServer?.sendInternalRequest(
+ this.uiServer.buildProtocolRequest(
+ generateUUID(),
+ ProcedureName.STOP_CHARGING_STATION,
+ Constants.EMPTY_FROZEN_OBJECT
+ )
+ )
+ try {
+ await this.waitChargingStationsStopped()
+ } catch (error) {
+ console.error(chalk.red('Error while waiting for charging stations to stop: '), error)
+ }
+ }
+ await this.workerImplementation?.stop()
+ delete this.workerImplementation
+ this.removeAllListeners()
+ await this.storage?.close()
+ delete this.storage
+ this.resetCounters()
+ this.initializedCounters = false
+ this.started = false
+ this.stopping = false