Cleanup
[e-mobility-charging-stations-simulator.git] / src / utils / Statistics.ts
index a2e0d030f009221fe5bf69cef6a8aee51353c75e..3fa4c78321ddafe219ba750aa11b78c971f83b63 100644 (file)
@@ -1,14 +1,18 @@
+import CommandStatistics, { CommandStatisticsData, PerfEntry } from '../types/CommandStatistics';
+
 import Configuration from './Configuration';
+import Constants from './Constants';
+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 _commandsStatistics: CommandStatistics;
 
   private constructor() {
-    this._statistics = {};
+    this._commandsStatistics = {} as CommandStatistics;
   }
 
   set objName(objName: string) {
@@ -22,61 +26,58 @@ export default class Statistics {
     return Statistics.instance;
   }
 
-  addMessage(command, response = false) {
-    if (response) {
-      if (this._statistics[command]) {
-        if (this._statistics[command].countResponse) {
-          this._statistics[command].countResponse++;
+  addMessage(command: string, messageType: number): void {
+    switch (messageType) {
+      case Constants.OCPP_JSON_CALL_MESSAGE:
+        if (this._commandsStatistics[command] && this._commandsStatistics[command].countRequest) {
+          this._commandsStatistics[command].countRequest++;
         } else {
-          this._statistics[command].countResponse = 1;
+          this._commandsStatistics[command] = {} as CommandStatisticsData;
+          this._commandsStatistics[command].countRequest = 1;
         }
-      } else {
-        this._statistics[command] = {};
-        this._statistics[command].countResponse = 1;
-      }
-    } else if (this._statistics[command] && this._statistics[command].count) {
-      this._statistics[command].count++;
-    } else {
-      this._statistics[command] = {};
-      this._statistics[command].count = 1;
-    }
-  }
-
-  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;
+        break;
+      case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
+        if (this._commandsStatistics[command]) {
+          if (this._commandsStatistics[command].countResponse) {
+            this._commandsStatistics[command].countResponse++;
+          } else {
+            this._commandsStatistics[command].countResponse = 1;
+          }
+        } else {
+          this._commandsStatistics[command] = {} as CommandStatisticsData;
+          this._commandsStatistics[command].countResponse = 1;
+        }
+        break;
+      case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
+        if (this._commandsStatistics[command]) {
+          if (this._commandsStatistics[command].countError) {
+            this._commandsStatistics[command].countError++;
+          } else {
+            this._commandsStatistics[command].countError = 1;
+          }
+        } else {
+          this._commandsStatistics[command] = {} as CommandStatisticsData;
+          this._commandsStatistics[command].countError = 1;
+        }
+        break;
+      default:
+        logger.error(`${this._logPrefix()} Wrong message type ${messageType}`);
+        break;
     }
   }
 
-  logPerformance(entry, className: string): void {
+  logPerformance(entry: PerformanceEntry, className: string): void {
     this.addPerformanceTimer(entry.name, entry.duration);
-    logger.info(`${this._logPrefix()} class->${className}, method->${entry.name}, duration->${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 performance entry: %j`, perfEntry);
   }
 
   _display(): void {
-    logger.info(this._logPrefix() + ' %j', this._statistics);
+    logger.info(this._logPrefix() + ' %j', this._commandsStatistics);
   }
 
   _displayInterval(): void {
@@ -84,7 +85,7 @@ export default class Statistics {
       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()));
     }
   }
 
@@ -92,6 +93,43 @@ export default class Statistics {
     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: string, duration: number): void {
+    // Map to proper command name
+    const MAPCOMMAND = {
+      sendMeterValues: 'MeterValues',
+      startTransaction: 'StartTransaction',
+      stopTransaction: 'StopTransaction',
+    };
+    if (MAPCOMMAND[command]) {
+      command = MAPCOMMAND[command] as string;
+    }
+    // Initialize command statistics
+    if (!this._commandsStatistics[command]) {
+      this._commandsStatistics[command] = {} as CommandStatisticsData;
+    }
+    // Update current statistics timers
+    this._commandsStatistics[command].countTimeMeasurement = this._commandsStatistics[command].countTimeMeasurement ? this._commandsStatistics[command].countTimeMeasurement + 1 : 1;
+    this._commandsStatistics[command].currentTimeMeasurement = duration;
+    this._commandsStatistics[command].minTimeMeasurement = this._commandsStatistics[command].minTimeMeasurement ? (this._commandsStatistics[command].minTimeMeasurement > duration ? duration : this._commandsStatistics[command].minTimeMeasurement) : duration;
+    this._commandsStatistics[command].maxTimeMeasurement = this._commandsStatistics[command].maxTimeMeasurement ? (this._commandsStatistics[command].maxTimeMeasurement < duration ? duration : this._commandsStatistics[command].maxTimeMeasurement) : duration;
+    this._commandsStatistics[command].totalTimeMeasurement = this._commandsStatistics[command].totalTimeMeasurement ? this._commandsStatistics[command].totalTimeMeasurement + duration : duration;
+    this._commandsStatistics[command].avgTimeMeasurement = this._commandsStatistics[command].totalTimeMeasurement / this._commandsStatistics[command].countTimeMeasurement;
+    Array.isArray(this._commandsStatistics[command].timeMeasurementSeries) ? this._commandsStatistics[command].timeMeasurementSeries.push(duration) : this._commandsStatistics[command].timeMeasurementSeries = [duration];
+    this._commandsStatistics[command].medTimeMeasurement = this.median(this._commandsStatistics[command].timeMeasurementSeries);
+  }
+
   private _logPrefix(): string {
     return Utils.logPrefix(` ${this._objName} Statistics:`);
   }