Cleanups to message queue handling code.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
index c532eea01dc72b2a008862a61d98164ebfdbda43..0c39613beefea49afdb1a3701457daba98fa12ee 100644 (file)
@@ -1,4 +1,4 @@
-import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/RequestResponses';
+import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
 import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
 import ChargingStationTemplate, { PowerOutType, VoltageOut } from '../types/ChargingStationTemplate';
 import Connectors, { Connector } from '../types/Connectors';
@@ -174,7 +174,8 @@ export default class ChargingStation {
 
   public startHeartbeat(): void {
     if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
-      this.heartbeatSetInterval = setInterval(async () => {
+      // eslint-disable-next-line @typescript-eslint/no-misused-promises
+      this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
         await this.ocppRequestService.sendHeartbeat();
       }, this.getHeartbeatInterval());
       logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
@@ -209,7 +210,8 @@ export default class ChargingStation {
       return;
     }
     if (interval > 0) {
-      this.getConnector(connectorId).transactionSetInterval = setInterval(async () => {
+      // eslint-disable-next-line @typescript-eslint/no-misused-promises
+      this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
         if (this.getEnableStatistics()) {
           const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
           this.performanceObserver.observe({
@@ -221,7 +223,7 @@ export default class ChargingStation {
         }
       }, interval);
     } else {
-      logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
+      logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
     }
   }
 
@@ -317,6 +319,31 @@ export default class ChargingStation {
     }
   }
 
+  public addToMessageQueue(message: string): void {
+    let dups = false;
+    // Handle dups in buffer
+    for (const bufferedMessage of this.messageQueue) {
+      // Same message
+      if (message === bufferedMessage) {
+        dups = true;
+        break;
+      }
+    }
+    if (!dups) {
+      // Buffer message
+      this.messageQueue.push(message);
+    }
+  }
+
+  private flushMessageQueue() {
+    if (!Utils.isEmptyArray(this.messageQueue)) {
+      this.messageQueue.forEach((message, index) => {
+        this.messageQueue.splice(index, 1);
+        this.wsConnection.send(message);
+      });
+    }
+  }
+
   private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
     // In case of multiple instances: add instance index to charging station id
     let instanceIndex = process.env.CF_INSTANCE_INDEX ? process.env.CF_INSTANCE_INDEX : 0;
@@ -463,12 +490,7 @@ export default class ChargingStation {
       await this.startMessageSequence();
       this.hasStopped && (this.hasStopped = false);
       if (this.hasSocketRestarted && this.isWebSocketOpen()) {
-        if (!Utils.isEmptyArray(this.messageQueue)) {
-          this.messageQueue.forEach((message, index) => {
-            this.messageQueue.splice(index, 1);
-            this.wsConnection.send(message);
-          });
-        }
+        this.flushMessageQueue();
       }
     } else {
       logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
@@ -824,6 +846,7 @@ export default class ChargingStation {
   }
 
   private startStationTemplateFileMonitoring(): void {
+    // eslint-disable-next-line @typescript-eslint/no-misused-promises
     fs.watch(this.stationTemplateFile).on('change', async (e): Promise<void> => {
       try {
         logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');