Add PowerWatts for EnvironmentMetrics

The EnvironmentMetrics schema[1] provides for efficient retrieval of
environmental metrics by separating them from performance metrics.
EnvironmentMetrics is a property of the Chassis schema since v1_15_0[2].
EnvironmentMetrics was added to Redfish release 2021.2 [3] to be used
instead of the deprecated Power schema.[4]

This commit adds PowerWatts property of the EnvironmentMetrics schema.
PowerWatts has been part of the EnvironmentMetrics schema since v1_1_0.
PowerWatts is a SensorPowerExcerpt[5].

Implementation notes: The new D-Bus interface
"xyz.openbmc_project.Sensor.Purpose" is used to find the sensor with the
"TotalPower" purpose.[6][7] The new utility function
sensor_utils::getSensorsByPurpose() returns a subset of an incoming list
of sensors which implement a specified purpose.

Multiple D-Bus calls are needed to find the sensor providing the
totalPower:
1. Retrieve list of power sensors associated with specified chassis
   which implement the Sensor.Purpose interface using existing
   getAllSensorObjects() function.
2. For each of those power sensors retrieve the actual purpose of the
   sensor to find the sensor implementing totalPower purpose. Expect no
   more than one sensor to implement this purpose. New utility function
   getSensorsByPurpose() is used.
3. If a totalPower sensor is found then retrieve its properties to fill
   in PowerWatts in the response using existing
   sensor_utils::objectExcerptToJson() utility function.

If no sensor has the "TotalPower" purpose then PowerWatts is
not added to EnvironmentMetrics and no error is returned.

[1] https://redfish.dmtf.org/schemas/v1/EnvironmentMetrics.v1_3_2.json
[2] https://redfish.dmtf.org/schemas/v1/Chassis.v1_25_2.json
[3] http://redfish.dmtf.org/schemas/Redfish_Release_History.pdf
[4] https://redfish.dmtf.org/schemas/v1/Power.v1_7_3.json
[5] http://redfish.dmtf.org/schemas/v1/Sensor.v1_9_1.json#/definitions/SensorPowerExcerpt
[6] https://gerrit.openbmc.org/c/openbmc/phosphor-dbus-interfaces/+/75943
[7] https://gerrit.openbmc.org/c/openbmc/openpower-occ-control/+/77408

Tested:
 - Updated unit tests for new environmentMetricsNode enum
 - Redfish Service Validator passes (confirmed PowerWatts tested)
```
VERBOSE1 - ServiceRoot -> Chassis -> Members#4 -> EnvironmentMetrics, EnvironmentMetrics.v1_3_0, EnvironmentMetrics
VERBOSE1 - @odata.id                                               PASS
VERBOSE1 - @odata.type                                             PASS
VERBOSE1 - Id                                                      PASS
VERBOSE1 - Name                                                    PASS
VERBOSE1 - PowerWatts                                              PASS
```
 - No "TotalPower" sensor exists (system never powered on).
   PowerWatts is not shown and no error is returned.
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/EnvironmentMetrics
{
  "@odata.id": "/redfish/v1/Chassis/chassis/EnvironmentMetrics",
  "@odata.type": "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics",
  "Id": "EnvironmentMetrics",
  "Name": "Chassis Environment Metrics"
}
```

 - "TotalPower" sensor exists (system powered on)
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Systems/system | grep PowerState
  "PowerState": "On",

curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/EnvironmentMetrics
{
  "@odata.id": "/redfish/v1/Chassis/chassis/EnvironmentMetrics",
  "@odata.type": "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics",
  "Id": "EnvironmentMetrics",
  "Name": "Chassis Environment Metrics",
  "PowerWatts": {
    "DataSourceUri": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
    "Reading": 191.0
  }
}
```
   DataSourceUri is a valid sensor:
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/Sensors/power_total_power
{
  "@odata.id": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
  "@odata.type": "#Sensor.v1_2_0.Sensor",
  "Id": "power_total_power",
  "Name": "total power",
  "Reading": 191.0,
  "ReadingType": "Power",
  "ReadingUnits": "W",
  "Status": {
    "Health": "OK",
    "State": "Enabled"
  }
}
```

 - "TotalPower" sensor exists but null value (system powered off)
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Systems/system | grep PowerState
  "PowerState": "Off",

curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/EnvironmentMetrics
{
  "@odata.id": "/redfish/v1/Chassis/chassis/EnvironmentMetrics",
  "@odata.type": "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics",
  "Id": "EnvironmentMetrics",
  "Name": "Chassis Environment Metrics",
  "PowerWatts": {
    "DataSourceUri": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
    "Reading": null
  }
}
```

And again the DataSourceUri points to a valid sensor:
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/Sensors/power_total_power
{
  "@odata.id": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
  "@odata.type": "#Sensor.v1_2_0.Sensor",
  "Id": "power_total_power",
  "Name": "total power",
  "Reading": null,
  "ReadingType": "Power",
  "ReadingUnits": "W",
  "Status": {
    "Health": "OK",
    "State": "Enabled"
  }
}
```

 - Invalid chassis id ("TotalPower" sensor exists)
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassisBAD/EnvironmentMetrics
{
  "error": {
    "@Message.ExtendedInfo": [
      {
        "@odata.type": "#Message.v1_1_1.Message",
        "Message": "The requested resource of type Chassis named 'chassisBAD' was not found.",
        "MessageArgs": [
          "Chassis",
          "chassisBAD"
        ],
        "MessageId": "Base.1.19.ResourceNotFound",
        "MessageSeverity": "Critical",
        "Resolution": "Provide a valid resource identifier and resubmit the request."
      }
    ],
    "code": "Base.1.19.ResourceNotFound",
    "message": "The requested resource of type Chassis named 'chassisBAD' was not found."
  }
}
```

Signed-off-by: George Liu <liuxiwei@inspur.com>
Signed-off-by: Janet Adkins <janeta@us.ibm.com>
Change-Id: Ibe84a5e7fe0d2b232f925e457a094c021ca85d36
diff --git a/redfish-core/lib/environment_metrics.hpp b/redfish-core/lib/environment_metrics.hpp
index 9d92fd4..ec5a3ef 100644
--- a/redfish-core/lib/environment_metrics.hpp
+++ b/redfish-core/lib/environment_metrics.hpp
@@ -4,25 +4,174 @@
 
 #include "app.hpp"
 #include "async_resp.hpp"
+#include "dbus_singleton.hpp"
+#include "dbus_utility.hpp"
 #include "error_messages.hpp"
 #include "http_request.hpp"
+#include "logging.hpp"
 #include "query.hpp"
 #include "registries/privilege_registry.hpp"
 #include "utils/chassis_utils.hpp"
+#include "utils/sensor_utils.hpp"
 
 #include <boost/beast/http/field.hpp>
 #include <boost/beast/http/verb.hpp>
 #include <boost/url/format.hpp>
+#include <nlohmann/json.hpp>
+#include <sdbusplus/asio/property.hpp>
 
+#include <array>
 #include <functional>
 #include <memory>
 #include <optional>
 #include <string>
+#include <string_view>
 #include <utility>
 
 namespace redfish
 {
 
+inline void afterGetPowerWatts(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId, const std::string& path,
+    const boost::system::error_code& ec,
+    const dbus::utility::DBusPropertiesMap& valuesDict)
+{
+    if (ec)
+    {
+        if (ec != boost::system::errc::io_error)
+        {
+            BMCWEB_LOG_ERROR("DBUS response error for PowerWatts {}", ec);
+            messages::internalError(asyncResp->res);
+        }
+        return;
+    }
+
+    nlohmann::json item = nlohmann::json::object();
+
+    /* Don't return an error for a failure to fill in properties from the
+     * single sensor. Just skip adding it.
+     */
+    if (sensor_utils::objectExcerptToJson(
+            path, chassisId,
+            sensor_utils::ChassisSubNode::environmentMetricsNode, "power",
+            valuesDict, item))
+    {
+        asyncResp->res.jsonValue["PowerWatts"] = std::move(item);
+    }
+}
+
+inline void handleTotalPowerList(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId, const boost::system::error_code& ec,
+    const std::shared_ptr<sensor_utils::SensorServicePathList>& sensorList)
+{
+    BMCWEB_LOG_DEBUG("handleTotalPowerList: {}", sensorList->size());
+
+    if (ec)
+    {
+        if (ec != boost::system::errc::io_error)
+        {
+            BMCWEB_LOG_ERROR("D-Bus response error {}", ec);
+            messages::internalError(asyncResp->res);
+        }
+        return;
+    }
+
+    // TotalPower cannot be supplied by multiple sensors
+    if (sensorList->size() != 1)
+    {
+        if (sensorList->empty())
+        {
+            // None found, not an error
+            return;
+        }
+        BMCWEB_LOG_ERROR("Too many total power sensors found {}. Expected 1.",
+                         sensorList->size());
+        messages::internalError(asyncResp->res);
+        return;
+    }
+
+    const std::string& serviceName = (*sensorList)[0].first;
+    const std::string& sensorPath = (*sensorList)[0].second;
+    sdbusplus::asio::getAllProperties(
+        *crow::connections::systemBus, serviceName, sensorPath,
+        "xyz.openbmc_project.Sensor.Value",
+        [asyncResp, chassisId,
+         sensorPath](const boost::system::error_code& ec1,
+                     const dbus::utility::DBusPropertiesMap& propertiesList) {
+            afterGetPowerWatts(asyncResp, chassisId, sensorPath, ec1,
+                               propertiesList);
+        });
+}
+
+inline void getTotalPowerSensor(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId, const boost::system::error_code& ec,
+    const sensor_utils::SensorServicePathList& sensorsServiceAndPath)
+{
+    BMCWEB_LOG_DEBUG("getTotalPowerSensor {}", sensorsServiceAndPath.size());
+
+    if (ec)
+    {
+        if (ec != boost::system::errc::io_error)
+        {
+            BMCWEB_LOG_ERROR("DBUS response error {}", ec);
+            messages::internalError(asyncResp->res);
+        }
+        // None found, not an error
+        return;
+    }
+
+    if (sensorsServiceAndPath.empty())
+    {
+        // No power sensors implement Sensor.Purpose, not an error
+        return;
+    }
+
+    // Create vector to hold list of sensors with totalPower purpose
+    std::shared_ptr<sensor_utils::SensorServicePathList> sensorList =
+        std::make_shared<sensor_utils::SensorServicePathList>();
+
+    sensor_utils::getSensorsByPurpose(
+        asyncResp, sensorsServiceAndPath,
+        sensor_utils::SensorPurpose::totalPower, sensorList,
+        std::bind_front(handleTotalPowerList, asyncResp, chassisId));
+}
+
+/**
+ * @brief Find sensor providing totalPower and fill in response
+ *
+ * Multiple D-Bus calls are needed to find the sensor providing the totalPower
+ * details:
+ *
+ * 1. Retrieve list of power sensors associated with specified chassis which
+ * implement the Sensor.Purpose interface.
+ *
+ * 2. For each of those power sensors retrieve the actual purpose of the sensor
+ * to find the sensor implementing totalPower purpose. Expect no more than
+ * one sensor to implement this purpose.
+ *
+ * 3. If a totalPower sensor is found then retrieve its properties to fill in
+ * PowerWatts in the response.
+ *
+ * @param asyncResp Response data
+ * @param validChassisPath Path to chassis, caller confirms path is valid
+ * @param chassisId Chassis id matching <validChassisPath>
+ */
+inline void getPowerWatts(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+                          const std::string& validChassisPath,
+                          const std::string& chassisId)
+{
+    BMCWEB_LOG_DEBUG("getPowerWatts: {}", validChassisPath);
+
+    constexpr std::array<std::string_view, 1> interfaces = {
+        "xyz.openbmc_project.Sensor.Purpose"};
+    sensor_utils::getAllSensorObjects(
+        validChassisPath, "/xyz/openbmc_project/sensors/power", interfaces, 1,
+        std::bind_front(getTotalPowerSensor, asyncResp, chassisId));
+}
+
 inline void handleEnvironmentMetricsHead(
     App& app, const crow::Request& req,
     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
@@ -50,6 +199,30 @@
                                                 std::move(respHandler));
 }
 
+inline void doEnvironmentMetricsGet(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId,
+    const std::optional<std::string>& validChassisPath)
+{
+    if (!validChassisPath)
+    {
+        messages::resourceNotFound(asyncResp->res, "Chassis", chassisId);
+        return;
+    }
+
+    asyncResp->res.addHeader(
+        boost::beast::http::field::link,
+        "</redfish/v1/JsonSchemas/EnvironmentMetrics/EnvironmentMetrics.json>; rel=describedby");
+    asyncResp->res.jsonValue["@odata.type"] =
+        "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics";
+    asyncResp->res.jsonValue["Name"] = "Chassis Environment Metrics";
+    asyncResp->res.jsonValue["Id"] = "EnvironmentMetrics";
+    asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
+        "/redfish/v1/Chassis/{}/EnvironmentMetrics", chassisId);
+
+    getPowerWatts(asyncResp, *validChassisPath, chassisId);
+}
+
 inline void handleEnvironmentMetricsGet(
     App& app, const crow::Request& req,
     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
@@ -60,27 +233,9 @@
         return;
     }
 
-    auto respHandler = [asyncResp, chassisId](
-                           const std::optional<std::string>& validChassisPath) {
-        if (!validChassisPath)
-        {
-            messages::resourceNotFound(asyncResp->res, "Chassis", chassisId);
-            return;
-        }
-
-        asyncResp->res.addHeader(
-            boost::beast::http::field::link,
-            "</redfish/v1/JsonSchemas/EnvironmentMetrics/EnvironmentMetrics.json>; rel=describedby");
-        asyncResp->res.jsonValue["@odata.type"] =
-            "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics";
-        asyncResp->res.jsonValue["Name"] = "Chassis Environment Metrics";
-        asyncResp->res.jsonValue["Id"] = "EnvironmentMetrics";
-        asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
-            "/redfish/v1/Chassis/{}/EnvironmentMetrics", chassisId);
-    };
-
-    redfish::chassis_utils::getValidChassisPath(asyncResp, chassisId,
-                                                std::move(respHandler));
+    redfish::chassis_utils::getValidChassisPath(
+        asyncResp, chassisId,
+        std::bind_front(doEnvironmentMetricsGet, asyncResp, chassisId));
 }
 
 inline void requestRoutesEnvironmentMetrics(App& app)