Implementing the TempToMargin feature

Wrapping the input name std::string in a new structure SensorInput, so
that the TempToMargin information can be cleanly carried along with
it, all the way down to the PID input processing layer where it is
needed. This allows the conversion to be done just-in-time before the
temperature reading is interpreted, minimizing the blast radius of
this change. Nonetheless, because of the type change, there was a
somewhat large blast radius to implement this feature.

The design, and the documentation, is already here:
https://github.com/openbmc/phosphor-pid-control/issues/23

Tested: Added unit tests for JSON parsing and for proper execution
of the TempToMargin feature. They pass. Ran it locally, on our
appropriately-configured system, and it seems to work for me.

Change-Id: I598ba485195aaa70c26e91a1da3ab88fff8c3a4c
Signed-off-by: Josh Lehan <krellan@google.com>
diff --git a/pid/builder.cpp b/pid/builder.cpp
index 8525073..bae0e81 100644
--- a/pid/builder.cpp
+++ b/pid/builder.cpp
@@ -23,6 +23,7 @@
 #include "pid/thermalcontroller.hpp"
 #include "pid/zone.hpp"
 #include "pid/zone_interface.hpp"
+#include "util.hpp"
 
 #include <sdbusplus/bus.hpp>
 
@@ -82,7 +83,7 @@
         // For each PID create a Controller and a Sensor.
         for (const auto& [name, info] : pidConfig)
         {
-            std::vector<std::string> inputs;
+            std::vector<pid_control::conf::SensorInput> inputs;
             std::cerr << "PID name: " << name << "\n";
 
             /*
@@ -94,11 +95,11 @@
                 for (const auto& i : info.inputs)
                 {
                     inputs.push_back(i);
-                    zone->addFanInput(i);
+                    zone->addFanInput(i.name);
                 }
 
-                auto pid = FanController::createFanPid(zone.get(), name, inputs,
-                                                       info.pidInfo);
+                auto pid = FanController::createFanPid(
+                    zone.get(), name, splitNames(inputs), info.pidInfo);
                 zone->addFanPID(std::move(pid));
                 zone->addPidFailSafePercent(name, info.failSafePercent);
             }
@@ -107,7 +108,7 @@
                 for (const auto& i : info.inputs)
                 {
                     inputs.push_back(i);
-                    zone->addThermalInput(i);
+                    zone->addThermalInput(i.name);
                 }
 
                 auto pid = ThermalController::createThermalPid(
@@ -125,10 +126,10 @@
                 for (const auto& i : info.inputs)
                 {
                     inputs.push_back(i);
-                    zone->addThermalInput(i);
+                    zone->addThermalInput(i.name);
                 }
                 auto stepwise = StepwiseController::createStepwiseController(
-                    zone.get(), name, inputs, info.stepwiseInfo);
+                    zone.get(), name, splitNames(inputs), info.stepwiseInfo);
                 zone->addThermalPID(std::move(stepwise));
                 zone->addPidControlProcess(
                     name, info.type, info.setpoint, modeControlBus,
@@ -139,7 +140,12 @@
             std::cerr << "inputs: ";
             for (const auto& i : inputs)
             {
-                std::cerr << i << ", ";
+                std::cerr << i.name;
+                if (i.convertTempToMargin)
+                {
+                    std::cerr << "[" << i.convertMarginZero << "]";
+                }
+                std::cerr << ", ";
             }
             std::cerr << "\n";
         }
diff --git a/pid/buildjson.cpp b/pid/buildjson.cpp
index 57ea943..8396338 100644
--- a/pid/buildjson.cpp
+++ b/pid/buildjson.cpp
@@ -17,10 +17,12 @@
 #include "pid/buildjson.hpp"
 
 #include "conf.hpp"
+#include "util.hpp"
 
 #include <nlohmann/json.hpp>
 
 #include <iostream>
+#include <limits>
 #include <map>
 #include <tuple>
 
@@ -31,12 +33,25 @@
 
 namespace conf
 {
+
 void from_json(const json& j, conf::ControllerInfo& c)
 {
+    std::vector<std::string> inputNames;
+
     j.at("type").get_to(c.type);
-    j.at("inputs").get_to(c.inputs);
+    j.at("inputs").get_to(inputNames);
     j.at("setpoint").get_to(c.setpoint);
 
+    std::vector<double> inputTempToMargin;
+
+    auto findTempToMargin = j.find("tempToMargin");
+    if (findTempToMargin != j.end())
+    {
+        findTempToMargin->get_to(inputTempToMargin);
+    }
+
+    c.inputs = spliceInputs(inputNames, inputTempToMargin);
+
     /* TODO: We need to handle parsing other PID controller configurations.
      * We can do that by checking for different keys and making the decision
      * accordingly.
@@ -135,6 +150,7 @@
         c.stepwiseInfo.negativeHysteresis = negativeHysteresisValue;
     }
 }
+
 } // namespace conf
 
 inline void getCycleTimeSetting(const auto& zone, const int id,
diff --git a/pid/ec/pid.hpp b/pid/ec/pid.hpp
index 378f93c..9dac6a4 100644
--- a/pid/ec/pid.hpp
+++ b/pid/ec/pid.hpp
@@ -15,14 +15,14 @@
 } limits_t;
 
 /* Note: If you update these structs you need to update the copy code in
- * pid/util.cpp.
+ * pid/util.cpp and the initialization code in pid/buildjson.hpp files.
  */
 typedef struct
 {
     bool initialized;         // has pid been initialized
 
     double ts;                // sample time in seconds
-    double integral;          // intergal of error
+    double integral;          // integral of error
     double lastOutput;        // value of last output
     double lastError;         // value of last error
 
diff --git a/pid/pidcontroller.hpp b/pid/pidcontroller.hpp
index c3e9999..05cbd71 100644
--- a/pid/pidcontroller.hpp
+++ b/pid/pidcontroller.hpp
@@ -29,6 +29,7 @@
         _pid_info.lastOutput = static_cast<double>(0.0);
         _pid_info.proportionalCoeff = static_cast<double>(0.0);
         _pid_info.integralCoeff = static_cast<double>(0.0);
+        _pid_info.derivativeCoeff = static_cast<double>(0.0);
         _pid_info.feedFwdOffset = static_cast<double>(0.0);
         _pid_info.feedFwdGain = static_cast<double>(0.0);
         _pid_info.integralLimit.min = static_cast<double>(0.0);
diff --git a/pid/thermalcontroller.cpp b/pid/thermalcontroller.cpp
index 357437b..ddb5893 100644
--- a/pid/thermalcontroller.cpp
+++ b/pid/thermalcontroller.cpp
@@ -55,7 +55,7 @@
 
 std::unique_ptr<PIDController> ThermalController::createThermalPid(
     ZoneInterface* owner, const std::string& id,
-    const std::vector<std::string>& inputs, double setpoint,
+    const std::vector<pid_control::conf::SensorInput>& inputs, double setpoint,
     const ec::pidinfo& initial, const ThermalType& type)
 {
     // ThermalController requires at least 1 input
@@ -101,12 +101,12 @@
         throw ControllerBuildException("Unrecognized ThermalType");
     }
 
-    std::string leaderName = *(_inputs.begin());
+    std::string leaderName = _inputs.begin()->name;
 
     bool acceptable = false;
     for (const auto& in : _inputs)
     {
-        double cachedValue = _owner->getCachedValue(in);
+        double cachedValue = _owner->getCachedValue(in.name);
 
         // Less than 0 is perfectly OK for temperature, but must not be NAN
         if (!(std::isfinite(cachedValue)))
@@ -114,6 +114,30 @@
             continue;
         }
 
+        // Perform TempToMargin conversion before further processing
+        if (type == ThermalType::margin)
+        {
+            if (in.convertTempToMargin)
+            {
+                if (!(std::isfinite(in.convertMarginZero)))
+                {
+                    throw ControllerBuildException("Unrecognized TempToMargin");
+                }
+
+                double marginValue = in.convertMarginZero - cachedValue;
+
+                if (debugEnabled)
+                {
+                    std::cerr << "Converting temp to margin: temp "
+                              << cachedValue << ", Tjmax "
+                              << in.convertMarginZero << ", margin "
+                              << marginValue << "\n";
+                }
+
+                cachedValue = marginValue;
+            }
+        }
+
         double oldValue = value;
 
         if (doSummation)
@@ -127,7 +151,7 @@
 
         if (oldValue != value)
         {
-            leaderName = in;
+            leaderName = in.name;
             _owner->updateThermalPowerDebugInterface(_id, leaderName, value, 0);
         }
 
@@ -136,8 +160,11 @@
 
     if (!acceptable)
     {
-        // While not optimal, zero is better than garbage
-        value = 0;
+        // If none of the inputs were acceptable, use the setpoint as
+        // the input value. This will continue to run the PID loop, but
+        // make it a no-op, as the error will be zero. This provides safe
+        // behavior until the inputs become acceptable.
+        value = setptProc();
     }
 
     if (debugEnabled)
diff --git a/pid/thermalcontroller.hpp b/pid/thermalcontroller.hpp
index 752c105..ac551d2 100644
--- a/pid/thermalcontroller.hpp
+++ b/pid/thermalcontroller.hpp
@@ -1,5 +1,6 @@
 #pragma once
 
+#include "conf.hpp"
 #include "ec/pid.hpp"
 #include "pidcontroller.hpp"
 
@@ -44,14 +45,13 @@
 class ThermalController : public PIDController
 {
   public:
-    static std::unique_ptr<PIDController>
-        createThermalPid(ZoneInterface* owner, const std::string& id,
-                         const std::vector<std::string>& inputs,
-                         double setpoint, const ec::pidinfo& initial,
-                         const ThermalType& type);
+    static std::unique_ptr<PIDController> createThermalPid(
+        ZoneInterface* owner, const std::string& id,
+        const std::vector<pid_control::conf::SensorInput>& inputs,
+        double setpoint, const ec::pidinfo& initial, const ThermalType& type);
 
     ThermalController(const std::string& id,
-                      const std::vector<std::string>& inputs,
+                      const std::vector<pid_control::conf::SensorInput>& inputs,
                       const ThermalType& type, ZoneInterface* owner) :
         PIDController(id, owner),
         _inputs(inputs), type(type)
@@ -62,7 +62,7 @@
     void outputProc(double value) override;
 
   private:
-    std::vector<std::string> _inputs;
+    std::vector<pid_control::conf::SensorInput> _inputs;
     ThermalType type;
 };