Use generic for worker data type.
[e-mobility-charging-stations-simulator.git] / src / utils / Statistics.ts
index 67bbf49e337bd03ec357ce0f2bbb530a960c9b6f..2aa99b0d4c9f317c78d14a052c65da80f4cbac4c 100644 (file)
@@ -1,60 +1,54 @@
+import CommandStatistics, { CommandStatisticsData, PerfEntry } from '../types/CommandStatistics';
+import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/1.6/Requests';
+
+import CircularArray from './CircularArray';
 import Configuration from './Configuration';
-import Constants from './Constants';
+import { MessageType } from '../types/ocpp/MessageType';
+import { PerformanceEntry } from 'perf_hooks';
 import Utils from './Utils';
 import logger from './Logger';
 
 export default class Statistics {
-  private static instance: Statistics;
-  private _statistics;
-  private _objName: string;
-
-  private constructor() {
-    this._statistics = {};
-  }
-
-  set objName(objName: string) {
-    this._objName = objName;
-  }
+  private objId: string;
+  private commandsStatistics: CommandStatistics;
 
-  static getInstance(): Statistics {
-    if (!Statistics.instance) {
-      Statistics.instance = new Statistics();
-    }
-    return Statistics.instance;
+  public constructor(objName: string) {
+    this.objId = objName;
+    this.commandsStatistics = { id: this.objId ? this.objId : 'Object id not specified', commandsStatisticsData: {} };
   }
 
-  addMessage(command: string, messageType: number): void {
+  public addMessage(command: RequestCommand | IncomingRequestCommand, messageType: MessageType): void {
     switch (messageType) {
-      case Constants.OCPP_JSON_CALL_MESSAGE:
-        if (this._statistics[command] && this._statistics[command].count) {
-          this._statistics[command].countRequest++;
+      case MessageType.CALL_MESSAGE:
+        if (this.commandsStatistics.commandsStatisticsData[command] && this.commandsStatistics.commandsStatisticsData[command].countRequest) {
+          this.commandsStatistics.commandsStatisticsData[command].countRequest++;
         } else {
-          this._statistics[command] = {};
-          this._statistics[command].countRequest = 1;
+          this.commandsStatistics.commandsStatisticsData[command] = {} as CommandStatisticsData;
+          this.commandsStatistics.commandsStatisticsData[command].countRequest = 1;
         }
         break;
-      case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
-        if (this._statistics[command]) {
-          if (this._statistics[command].countResponse) {
-            this._statistics[command].countResponse++;
+      case MessageType.CALL_RESULT_MESSAGE:
+        if (this.commandsStatistics.commandsStatisticsData[command]) {
+          if (this.commandsStatistics.commandsStatisticsData[command].countResponse) {
+            this.commandsStatistics.commandsStatisticsData[command].countResponse++;
           } else {
-            this._statistics[command].countResponse = 1;
+            this.commandsStatistics.commandsStatisticsData[command].countResponse = 1;
           }
         } else {
-          this._statistics[command] = {};
-          this._statistics[command].countResponse = 1;
+          this.commandsStatistics.commandsStatisticsData[command] = {} as CommandStatisticsData;
+          this.commandsStatistics.commandsStatisticsData[command].countResponse = 1;
         }
         break;
-      case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
-        if (this._statistics[command]) {
-          if (this._statistics[command].countError) {
-            this._statistics[command].countError++;
+      case MessageType.CALL_ERROR_MESSAGE:
+        if (this.commandsStatistics.commandsStatisticsData[command]) {
+          if (this.commandsStatistics.commandsStatisticsData[command].countError) {
+            this.commandsStatistics.commandsStatisticsData[command].countError++;
           } else {
-            this._statistics[command].countError = 1;
+            this.commandsStatistics.commandsStatisticsData[command].countError = 1;
           }
         } else {
-          this._statistics[command] = {};
-          this._statistics[command].countError = 1;
+          this.commandsStatistics.commandsStatisticsData[command] = {} as CommandStatisticsData;
+          this.commandsStatistics.commandsStatisticsData[command].countError = 1;
         }
         break;
       default:
@@ -63,57 +57,71 @@ export default class Statistics {
     }
   }
 
-  addPerformanceTimer(command, duration) {
-    let currentStatistics;
-    // Map to proper command name
-    const MAPCOMMAND = {
-      sendMeterValues: 'MeterValues',
-      startTransaction: 'StartTransaction',
-      stopTransaction: 'StopTransaction',
-    };
-    // Get current command statistics
-    if (MAPCOMMAND[command]) {
-      currentStatistics = this._statistics[MAPCOMMAND[command]];
-    } else if (this._statistics[command]) {
-      currentStatistics = this._statistics[command];
-    } else {
-      this._statistics[command] = {};
-      currentStatistics = this._statistics[command];
-    }
-
-    if (currentStatistics) {
-      // Update current statistics timers
-      currentStatistics.countTime = currentStatistics.countTime ? currentStatistics.countTime + 1 : 1;
-      currentStatistics.minTime = currentStatistics.minTime ? (currentStatistics.minTime > duration ? duration : currentStatistics.minTime) : duration;
-      currentStatistics.maxTime = currentStatistics.maxTime ? (currentStatistics.maxTime < duration ? duration : currentStatistics.maxTime) : duration;
-      currentStatistics.totalTime = currentStatistics.totalTime ? currentStatistics.totalTime + duration : duration;
-      currentStatistics.avgTime = currentStatistics.totalTime / currentStatistics.countTime;
-    }
+  public logPerformance(entry: PerformanceEntry, className: string): void {
+    this.addPerformanceTimer(entry.name as RequestCommand | IncomingRequestCommand, entry.duration);
+    const perfEntry: PerfEntry = {} as PerfEntry;
+    perfEntry.name = entry.name;
+    perfEntry.entryType = entry.entryType;
+    perfEntry.startTime = entry.startTime;
+    perfEntry.duration = entry.duration;
+    logger.info(`${this._logPrefix()} object ${className} method(s) performance entry: %j`, perfEntry);
   }
 
-  logPerformance(entry, className: string): void {
-    this.addPerformanceTimer(entry.name, entry.duration);
-    logger.info(`${this._logPrefix()} class->${className}, method->${entry.name}, duration->${entry.duration}`);
+  public start(): void {
+    this._displayInterval();
   }
 
-  _display(): void {
-    logger.info(this._logPrefix() + ' %j', this._statistics);
+  private _display(): void {
+    logger.info(this._logPrefix() + ' %j', this.commandsStatistics);
   }
 
-  _displayInterval(): void {
+  private _displayInterval(): void {
     if (Configuration.getStatisticsDisplayInterval() > 0) {
       setInterval(() => {
         this._display();
       }, Configuration.getStatisticsDisplayInterval() * 1000);
-      logger.info(this._logPrefix() + ' displayed every ' + Configuration.getStatisticsDisplayInterval() + 's');
+      logger.info(this._logPrefix() + ' displayed every ' + Utils.secondsToHHMMSS(Configuration.getStatisticsDisplayInterval()));
     }
   }
 
-  start(): void {
-    this._displayInterval();
+  private median(dataSet: number[]): number {
+    if (Array.isArray(dataSet) && dataSet.length === 1) {
+      return dataSet[0];
+    }
+    const sortedDataSet = dataSet.slice().sort();
+    const middleIndex = Math.floor(sortedDataSet.length / 2);
+    if (sortedDataSet.length % 2) {
+      return sortedDataSet[middleIndex / 2];
+    }
+    return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2;
+  }
+
+  private addPerformanceTimer(command: RequestCommand | IncomingRequestCommand, duration: number): void {
+    // Map to proper command name
+    const MAPCOMMAND = {
+      sendMeterValues: 'MeterValues',
+      startTransaction: 'StartTransaction',
+      stopTransaction: 'StopTransaction',
+    };
+    if (MAPCOMMAND[command]) {
+      command = MAPCOMMAND[command] as RequestCommand | IncomingRequestCommand;
+    }
+    // Initialize command statistics
+    if (!this.commandsStatistics.commandsStatisticsData[command]) {
+      this.commandsStatistics.commandsStatisticsData[command] = {} as CommandStatisticsData;
+    }
+    // Update current statistics timers
+    this.commandsStatistics.commandsStatisticsData[command].countTimeMeasurement = this.commandsStatistics.commandsStatisticsData[command].countTimeMeasurement ? this.commandsStatistics.commandsStatisticsData[command].countTimeMeasurement + 1 : 1;
+    this.commandsStatistics.commandsStatisticsData[command].currentTimeMeasurement = duration;
+    this.commandsStatistics.commandsStatisticsData[command].minTimeMeasurement = this.commandsStatistics.commandsStatisticsData[command].minTimeMeasurement ? (this.commandsStatistics.commandsStatisticsData[command].minTimeMeasurement > duration ? duration : this.commandsStatistics.commandsStatisticsData[command].minTimeMeasurement) : duration;
+    this.commandsStatistics.commandsStatisticsData[command].maxTimeMeasurement = this.commandsStatistics.commandsStatisticsData[command].maxTimeMeasurement ? (this.commandsStatistics.commandsStatisticsData[command].maxTimeMeasurement < duration ? duration : this.commandsStatistics.commandsStatisticsData[command].maxTimeMeasurement) : duration;
+    this.commandsStatistics.commandsStatisticsData[command].totalTimeMeasurement = this.commandsStatistics.commandsStatisticsData[command].totalTimeMeasurement ? this.commandsStatistics.commandsStatisticsData[command].totalTimeMeasurement + duration : duration;
+    this.commandsStatistics.commandsStatisticsData[command].avgTimeMeasurement = this.commandsStatistics.commandsStatisticsData[command].totalTimeMeasurement / this.commandsStatistics.commandsStatisticsData[command].countTimeMeasurement;
+    Array.isArray(this.commandsStatistics.commandsStatisticsData[command].timeMeasurementSeries) ? this.commandsStatistics.commandsStatisticsData[command].timeMeasurementSeries.push(duration) : this.commandsStatistics.commandsStatisticsData[command].timeMeasurementSeries = [duration] as CircularArray<number>;
+    this.commandsStatistics.commandsStatisticsData[command].medTimeMeasurement = this.median(this.commandsStatistics.commandsStatisticsData[command].timeMeasurementSeries);
   }
 
   private _logPrefix(): string {
-    return Utils.logPrefix(` ${this._objName} Statistics:`);
+    return Utils.logPrefix(` ${this.objId} Statistics:`);
   }
 }