From 71b6807f116c2b9f3aec006733118c29ff69d39c Mon Sep 17 00:00:00 2001
From: "Wang.Bin" <Bin-B.Wang@luxshare-ict.com>
Date: Wed, 6 Nov 2024 19:45:16 +0800
Subject: [PATCH] Add function of sumIgnoreNaN

---
 exprtkTools.hpp   | 25 +++++++++++++++++++++++++
 virtualSensor.cpp |  6 ++++++
 virtualSensor.hpp |  2 ++
 3 files changed, 33 insertions(+)

diff --git a/exprtkTools.hpp b/exprtkTools.hpp
index 18a4af7..fad5bcf 100644
--- a/exprtkTools.hpp
+++ b/exprtkTools.hpp
@@ -37,3 +37,28 @@
 
 /* include main exprtk header library */
 #include <exprtk.hpp>
+
+#include <cmath>
+#include <limits>
+#include <numeric>
+
+template <typename T>
+struct FuncSumIgnoreNaN : public exprtk::ivararg_function<T>
+{
+    inline T operator()(const std::vector<T>& argList)
+    {
+        return std::reduce(std::begin(argList), std::end(argList),
+                           std::numeric_limits<double>::quiet_NaN(),
+                           [](auto a, auto b) {
+            if (std::isnan(b))
+            {
+                return a;
+            }
+            if (std::isnan(a))
+            {
+                return b;
+            }
+            return a + b;
+        });
+    }
+};
\ No newline at end of file
diff --git a/virtualSensor.cpp b/virtualSensor.cpp
index a61527e..65f9a43 100644
--- a/virtualSensor.cpp
+++ b/virtualSensor.cpp
@@ -4,6 +4,8 @@
 
 #include <fstream>
 
+#include <iostream>
+
 static constexpr bool DEBUG = false;
 static constexpr auto busName = "xyz.openbmc_project.VirtualSensor";
 static constexpr auto sensorDbusPath = "/xyz/openbmc_project/sensors/";
@@ -45,6 +47,8 @@ namespace phosphor
 namespace virtualSensor
 {
 
+FuncSumIgnoreNaN<double> VirtualSensor::funcSumIgnoreNaN;
+
 void printParams(const VirtualSensor::ParamMap& paramMap)
 {
     for (const auto& p : paramMap)
@@ -308,6 +312,7 @@ void VirtualSensor::initVirtualSensor(const Json& sensorConfig,
         else if (ref.is_string())
         {
             exprStr = std::string{ref};
+
         }
     }
 
@@ -365,6 +370,7 @@ void VirtualSensor::initVirtualSensor(const Json& sensorConfig,
 
     symbols.add_constants();
     symbols.add_package(vecopsPackage);
+    symbols.add_function("sumIgnoreNaN", funcSumIgnoreNaN);
     expression.register_symbol_table(symbols);
 
     /* parser from exprtk */
diff --git a/virtualSensor.hpp b/virtualSensor.hpp
index 8f17395..c08f208 100644
--- a/virtualSensor.hpp
+++ b/virtualSensor.hpp
@@ -169,6 +169,8 @@ class VirtualSensor : public ValueObject
     /** @brief The association interface object */
     std::unique_ptr<AssociationObject> associationIface;
 
+    static FuncSumIgnoreNaN<double> funcSumIgnoreNaN;
+    
     /** @brief Read config from json object and initialize sensor data
      * for each virtual sensor
      */
-- 
2.25.1

