Cleanups to message queue handling code.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
index efedd1016fa57127ccf5d2ba71147fc975e7082a..0c39613beefea49afdb1a3701457daba98fa12ee 100644 (file)
@@ -223,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`);
     }
   }
 
@@ -319,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;
@@ -460,16 +485,12 @@ export default class ChargingStation {
           await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
         }
       } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
-    } else if (this.isRegistered()) {
+    }
+    if (this.isRegistered()) {
       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()})`);