16714a25aSJames Feist /*
26714a25aSJames Feist // Copyright (c) 2017 Intel Corporation
36714a25aSJames Feist //
46714a25aSJames Feist // Licensed under the Apache License, Version 2.0 (the "License");
56714a25aSJames Feist // you may not use this file except in compliance with the License.
66714a25aSJames Feist // You may obtain a copy of the License at
76714a25aSJames Feist //
86714a25aSJames Feist //      http://www.apache.org/licenses/LICENSE-2.0
96714a25aSJames Feist //
106714a25aSJames Feist // Unless required by applicable law or agreed to in writing, software
116714a25aSJames Feist // distributed under the License is distributed on an "AS IS" BASIS,
126714a25aSJames Feist // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
136714a25aSJames Feist // See the License for the specific language governing permissions and
146714a25aSJames Feist // limitations under the License.
156714a25aSJames Feist */
166714a25aSJames Feist 
17e73bd0a1SAndrew Jeffery #include "DeviceMgmt.hpp"
18e73bd0a1SAndrew Jeffery #include "HwmonTempSensor.hpp"
19e73bd0a1SAndrew Jeffery #include "Utils.hpp"
20e73bd0a1SAndrew Jeffery 
216714a25aSJames Feist #include <boost/algorithm/string/replace.hpp>
2296e97db7SPatrick Venture #include <boost/container/flat_map.hpp>
236714a25aSJames Feist #include <boost/container/flat_set.hpp>
2438fb5983SJames Feist #include <sdbusplus/asio/connection.hpp>
2538fb5983SJames Feist #include <sdbusplus/asio/object_server.hpp>
2638fb5983SJames Feist #include <sdbusplus/bus/match.hpp>
2738fb5983SJames Feist 
2838fb5983SJames Feist #include <array>
297dd6443bSJae Hyun Yoo #include <charconv>
3024f02f24SJames Feist #include <filesystem>
316714a25aSJames Feist #include <fstream>
3296e97db7SPatrick Venture #include <functional>
3396e97db7SPatrick Venture #include <memory>
346714a25aSJames Feist #include <regex>
3596e97db7SPatrick Venture #include <stdexcept>
3696e97db7SPatrick Venture #include <string>
3796e97db7SPatrick Venture #include <utility>
3896e97db7SPatrick Venture #include <variant>
3996e97db7SPatrick Venture #include <vector>
406714a25aSJames Feist 
4187bc67f7SJeff Lin static constexpr float pollRateDefault = 0.5;
426714a25aSJames Feist 
43544e7dc5SBruce Mitchell static constexpr double maxValuePressure = 120000;      // Pascals
44544e7dc5SBruce Mitchell static constexpr double minValuePressure = 30000;       // Pascals
45544e7dc5SBruce Mitchell 
463ec41c53SBruce Mitchell static constexpr double maxValueRelativeHumidity = 100; // PercentRH
473ec41c53SBruce Mitchell static constexpr double minValueRelativeHumidity = 0;   // PercentRH
483ec41c53SBruce Mitchell 
49544e7dc5SBruce Mitchell static constexpr double maxValueTemperature = 127;      // DegreesC
50544e7dc5SBruce Mitchell static constexpr double minValueTemperature = -128;     // DegreesC
51544e7dc5SBruce Mitchell 
52cf3bce6eSJames Feist namespace fs = std::filesystem;
53d29f8aa0SZev Weiss 
54d29f8aa0SZev Weiss static const I2CDeviceTypeMap sensorTypes{
55d29f8aa0SZev Weiss     {"DPS310", I2CDeviceType{"dps310", false}},
56d29f8aa0SZev Weiss     {"EMC1412", I2CDeviceType{"emc1412", true}},
57d29f8aa0SZev Weiss     {"EMC1413", I2CDeviceType{"emc1413", true}},
58d29f8aa0SZev Weiss     {"EMC1414", I2CDeviceType{"emc1414", true}},
59d29f8aa0SZev Weiss     {"HDC1080", I2CDeviceType{"hdc1080", false}},
60d29f8aa0SZev Weiss     {"JC42", I2CDeviceType{"jc42", true}},
61d29f8aa0SZev Weiss     {"LM75A", I2CDeviceType{"lm75a", true}},
62d29f8aa0SZev Weiss     {"LM95234", I2CDeviceType{"lm95234", true}},
63d29f8aa0SZev Weiss     {"MAX31725", I2CDeviceType{"max31725", true}},
64d29f8aa0SZev Weiss     {"MAX31730", I2CDeviceType{"max31730", true}},
65d29f8aa0SZev Weiss     {"MAX6581", I2CDeviceType{"max6581", true}},
66d29f8aa0SZev Weiss     {"MAX6654", I2CDeviceType{"max6654", true}},
67d29f8aa0SZev Weiss     {"NCT6779", I2CDeviceType{"nct6779", true}},
68d29f8aa0SZev Weiss     {"NCT7802", I2CDeviceType{"nct7802", true}},
69d29f8aa0SZev Weiss     {"SBTSI", I2CDeviceType{"sbtsi", true}},
70d29f8aa0SZev Weiss     {"SI7020", I2CDeviceType{"si7020", false}},
719b0a6f67STim Lee     {"TMP100", I2CDeviceType{"tmp100", true}},
72d29f8aa0SZev Weiss     {"TMP112", I2CDeviceType{"tmp112", true}},
73d29f8aa0SZev Weiss     {"TMP175", I2CDeviceType{"tmp175", true}},
74d29f8aa0SZev Weiss     {"TMP421", I2CDeviceType{"tmp421", true}},
75d29f8aa0SZev Weiss     {"TMP441", I2CDeviceType{"tmp441", true}},
769a7db6afSHieu Huynh     {"TMP464", I2CDeviceType{"tmp464", true}},
77d29f8aa0SZev Weiss     {"TMP75", I2CDeviceType{"tmp75", true}},
78d29f8aa0SZev Weiss     {"W83773G", I2CDeviceType{"w83773g", true}},
79d29f8aa0SZev Weiss };
806714a25aSJames Feist 
81544e7dc5SBruce Mitchell static struct SensorParams
82544e7dc5SBruce Mitchell     getSensorParameters(const std::filesystem::path& path)
83544e7dc5SBruce Mitchell {
84544e7dc5SBruce Mitchell     // offset is to default to 0 and scale to 1, see lore
85544e7dc5SBruce Mitchell     // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
86779c96a2SPatrick Williams     struct SensorParams tmpSensorParameters = {
87779c96a2SPatrick Williams         .minValue = minValueTemperature,
88544e7dc5SBruce Mitchell         .maxValue = maxValueTemperature,
89544e7dc5SBruce Mitchell         .offsetValue = 0.0,
90544e7dc5SBruce Mitchell         .scaleValue = 1.0,
91779c96a2SPatrick Williams         .units = sensor_paths::unitDegreesC,
92544e7dc5SBruce Mitchell         .typeName = "temperature"};
93544e7dc5SBruce Mitchell 
94544e7dc5SBruce Mitchell     // For IIO RAW sensors we get a raw_value, an offset, and scale
95544e7dc5SBruce Mitchell     // to compute the value = (raw_value + offset) * scale
96544e7dc5SBruce Mitchell     // with a _raw IIO device we need to get the
97544e7dc5SBruce Mitchell     // offsetValue and scaleValue from the driver
98544e7dc5SBruce Mitchell     // these are used to compute the reading in
99544e7dc5SBruce Mitchell     // units that have yet to be scaled for D-Bus.
100544e7dc5SBruce Mitchell     const std::string pathStr = path.string();
101544e7dc5SBruce Mitchell     if (pathStr.ends_with("_raw"))
102544e7dc5SBruce Mitchell     {
103779c96a2SPatrick Williams         std::string pathOffsetStr = pathStr.substr(0, pathStr.size() - 4) +
104779c96a2SPatrick Williams                                     "_offset";
105544e7dc5SBruce Mitchell         std::optional<double> tmpOffsetValue = readFile(pathOffsetStr, 1.0);
106544e7dc5SBruce Mitchell         // In case there is nothing to read skip this device
107544e7dc5SBruce Mitchell         // This is not an error condition see lore
108544e7dc5SBruce Mitchell         // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
109544e7dc5SBruce Mitchell         if (tmpOffsetValue)
110544e7dc5SBruce Mitchell         {
111544e7dc5SBruce Mitchell             tmpSensorParameters.offsetValue = *tmpOffsetValue;
112544e7dc5SBruce Mitchell         }
113544e7dc5SBruce Mitchell 
114779c96a2SPatrick Williams         std::string pathScaleStr = pathStr.substr(0, pathStr.size() - 4) +
115779c96a2SPatrick Williams                                    "_scale";
116544e7dc5SBruce Mitchell         std::optional<double> tmpScaleValue = readFile(pathScaleStr, 1.0);
117544e7dc5SBruce Mitchell         // In case there is nothing to read skip this device
118544e7dc5SBruce Mitchell         // This is not an error condition see lore
119544e7dc5SBruce Mitchell         // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
120544e7dc5SBruce Mitchell         if (tmpScaleValue)
121544e7dc5SBruce Mitchell         {
122544e7dc5SBruce Mitchell             tmpSensorParameters.scaleValue = *tmpScaleValue;
123544e7dc5SBruce Mitchell         }
124544e7dc5SBruce Mitchell     }
125544e7dc5SBruce Mitchell 
126544e7dc5SBruce Mitchell     // Temperatures are read in milli degrees Celsius, we need
127544e7dc5SBruce Mitchell     // degrees Celsius. Pressures are read in kilopascal, we need
128544e7dc5SBruce Mitchell     // Pascals.  On D-Bus for Open BMC we use the International
129544e7dc5SBruce Mitchell     // System of Units without prefixes. Links to the kernel
130544e7dc5SBruce Mitchell     // documentation:
131544e7dc5SBruce Mitchell     // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface
132544e7dc5SBruce Mitchell     // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-iio
133544e7dc5SBruce Mitchell     if (path.filename() == "in_pressure_input" ||
134544e7dc5SBruce Mitchell         path.filename() == "in_pressure_raw")
135544e7dc5SBruce Mitchell     {
136544e7dc5SBruce Mitchell         tmpSensorParameters.minValue = minValuePressure;
137544e7dc5SBruce Mitchell         tmpSensorParameters.maxValue = maxValuePressure;
138544e7dc5SBruce Mitchell         // Pressures are read in kilopascal, we need Pascals.
139544e7dc5SBruce Mitchell         tmpSensorParameters.scaleValue *= 1000.0;
140544e7dc5SBruce Mitchell         tmpSensorParameters.typeName = "pressure";
1415a86e562SBruce Mitchell         tmpSensorParameters.units = sensor_paths::unitPascals;
142544e7dc5SBruce Mitchell     }
1433ec41c53SBruce Mitchell     else if (path.filename() == "in_humidityrelative_input" ||
1443ec41c53SBruce Mitchell              path.filename() == "in_humidityrelative_raw")
1453ec41c53SBruce Mitchell     {
1463ec41c53SBruce Mitchell         tmpSensorParameters.minValue = minValueRelativeHumidity;
1473ec41c53SBruce Mitchell         tmpSensorParameters.maxValue = maxValueRelativeHumidity;
1483ec41c53SBruce Mitchell         // Relative Humidity are read in milli-percent, we need percent.
1493ec41c53SBruce Mitchell         tmpSensorParameters.scaleValue *= 0.001;
1503ec41c53SBruce Mitchell         tmpSensorParameters.typeName = "humidity";
1513ec41c53SBruce Mitchell         tmpSensorParameters.units = "PercentRH";
1523ec41c53SBruce Mitchell     }
153544e7dc5SBruce Mitchell     else
154544e7dc5SBruce Mitchell     {
155544e7dc5SBruce Mitchell         // Temperatures are read in milli degrees Celsius,
156544e7dc5SBruce Mitchell         // we need degrees Celsius.
157544e7dc5SBruce Mitchell         tmpSensorParameters.scaleValue *= 0.001;
158544e7dc5SBruce Mitchell     }
159544e7dc5SBruce Mitchell 
160544e7dc5SBruce Mitchell     return tmpSensorParameters;
161544e7dc5SBruce Mitchell }
162544e7dc5SBruce Mitchell 
1639f3a74edSJayashree Dhanapal struct SensorConfigKey
1649f3a74edSJayashree Dhanapal {
1659f3a74edSJayashree Dhanapal     uint64_t bus;
1669f3a74edSJayashree Dhanapal     uint64_t addr;
1679f3a74edSJayashree Dhanapal     bool operator<(const SensorConfigKey& other) const
1689f3a74edSJayashree Dhanapal     {
1699f3a74edSJayashree Dhanapal         if (bus != other.bus)
1709f3a74edSJayashree Dhanapal         {
1719f3a74edSJayashree Dhanapal             return bus < other.bus;
1729f3a74edSJayashree Dhanapal         }
1739f3a74edSJayashree Dhanapal         return addr < other.addr;
1749f3a74edSJayashree Dhanapal     }
1759f3a74edSJayashree Dhanapal };
1769f3a74edSJayashree Dhanapal 
1779f3a74edSJayashree Dhanapal struct SensorConfig
1789f3a74edSJayashree Dhanapal {
1799f3a74edSJayashree Dhanapal     std::string sensorPath;
1809f3a74edSJayashree Dhanapal     SensorData sensorData;
1819f3a74edSJayashree Dhanapal     std::string interface;
1829f3a74edSJayashree Dhanapal     SensorBaseConfigMap config;
1839f3a74edSJayashree Dhanapal     std::vector<std::string> name;
1849f3a74edSJayashree Dhanapal };
1859f3a74edSJayashree Dhanapal 
1869f3a74edSJayashree Dhanapal using SensorConfigMap =
1879f3a74edSJayashree Dhanapal     boost::container::flat_map<SensorConfigKey, SensorConfig>;
1889f3a74edSJayashree Dhanapal 
1899f3a74edSJayashree Dhanapal static SensorConfigMap
1909f3a74edSJayashree Dhanapal     buildSensorConfigMap(const ManagedObjectType& sensorConfigs)
1919f3a74edSJayashree Dhanapal {
1929f3a74edSJayashree Dhanapal     SensorConfigMap configMap;
193a1808330SZev Weiss     for (const auto& [path, cfgData] : sensorConfigs)
1949f3a74edSJayashree Dhanapal     {
195a1808330SZev Weiss         for (const auto& [intf, cfg] : cfgData)
1969f3a74edSJayashree Dhanapal         {
1979f3a74edSJayashree Dhanapal             auto busCfg = cfg.find("Bus");
1989f3a74edSJayashree Dhanapal             auto addrCfg = cfg.find("Address");
1999f3a74edSJayashree Dhanapal             if ((busCfg == cfg.end()) || (addrCfg == cfg.end()))
2009f3a74edSJayashree Dhanapal             {
2019f3a74edSJayashree Dhanapal                 continue;
2029f3a74edSJayashree Dhanapal             }
2039f3a74edSJayashree Dhanapal 
2042049bd26SEd Tanous             if ((std::get_if<uint64_t>(&busCfg->second) == nullptr) ||
2052049bd26SEd Tanous                 (std::get_if<uint64_t>(&addrCfg->second) == nullptr))
2069f3a74edSJayashree Dhanapal             {
207a1808330SZev Weiss                 std::cerr << path.str << " Bus or Address invalid\n";
2089f3a74edSJayashree Dhanapal                 continue;
2099f3a74edSJayashree Dhanapal             }
2109f3a74edSJayashree Dhanapal 
2119f3a74edSJayashree Dhanapal             std::vector<std::string> hwmonNames;
2129f3a74edSJayashree Dhanapal             auto nameCfg = cfg.find("Name");
2139f3a74edSJayashree Dhanapal             if (nameCfg != cfg.end())
2149f3a74edSJayashree Dhanapal             {
2159f3a74edSJayashree Dhanapal                 hwmonNames.push_back(std::get<std::string>(nameCfg->second));
2169f3a74edSJayashree Dhanapal                 size_t i = 1;
2179f3a74edSJayashree Dhanapal                 while (true)
2189f3a74edSJayashree Dhanapal                 {
2199f3a74edSJayashree Dhanapal                     auto sensorNameCfg = cfg.find("Name" + std::to_string(i));
2209f3a74edSJayashree Dhanapal                     if (sensorNameCfg == cfg.end())
2219f3a74edSJayashree Dhanapal                     {
2229f3a74edSJayashree Dhanapal                         break;
2239f3a74edSJayashree Dhanapal                     }
2249f3a74edSJayashree Dhanapal                     hwmonNames.push_back(
2259f3a74edSJayashree Dhanapal                         std::get<std::string>(sensorNameCfg->second));
2269f3a74edSJayashree Dhanapal                     i++;
2279f3a74edSJayashree Dhanapal                 }
2289f3a74edSJayashree Dhanapal             }
2299f3a74edSJayashree Dhanapal 
2309f3a74edSJayashree Dhanapal             SensorConfigKey key = {std::get<uint64_t>(busCfg->second),
2319f3a74edSJayashree Dhanapal                                    std::get<uint64_t>(addrCfg->second)};
232a1808330SZev Weiss             SensorConfig val = {path.str, cfgData, intf, cfg, hwmonNames};
2339f3a74edSJayashree Dhanapal 
2349f3a74edSJayashree Dhanapal             auto [it, inserted] = configMap.emplace(key, std::move(val));
2359f3a74edSJayashree Dhanapal             if (!inserted)
2369f3a74edSJayashree Dhanapal             {
237a1808330SZev Weiss                 std::cerr << path.str << ": ignoring duplicate entry for {"
238a1808330SZev Weiss                           << key.bus << ", 0x" << std::hex << key.addr
239a1808330SZev Weiss                           << std::dec << "}\n";
2409f3a74edSJayashree Dhanapal             }
2419f3a74edSJayashree Dhanapal         }
2429f3a74edSJayashree Dhanapal     }
2439f3a74edSJayashree Dhanapal     return configMap;
2449f3a74edSJayashree Dhanapal }
2459f3a74edSJayashree Dhanapal 
2466714a25aSJames Feist void createSensors(
2471f978631SEd Tanous     boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
248f3fd1915SYong Li     boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
2496714a25aSJames Feist         sensors,
2506714a25aSJames Feist     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
2515591cf08SJames Feist     const std::shared_ptr<boost::container::flat_set<std::string>>&
252a1456c4aSZev Weiss         sensorsChanged,
253a1456c4aSZev Weiss     bool activateOnly)
2546714a25aSJames Feist {
255df515159SJames Feist     auto getter = std::make_shared<GetSensorConfiguration>(
256df515159SJames Feist         dbusConnection,
257a1456c4aSZev Weiss         [&io, &objectServer, &sensors, &dbusConnection, sensorsChanged,
258a1456c4aSZev Weiss          activateOnly](const ManagedObjectType& sensorConfigurations) {
2596714a25aSJames Feist         bool firstScan = sensorsChanged == nullptr;
260df515159SJames Feist 
261bb67932aSEd Tanous         SensorConfigMap configMap = buildSensorConfigMap(sensorConfigurations);
2629f3a74edSJayashree Dhanapal 
263*c564eda5SMatt Simmering         auto devices = instantiateDevices(sensorConfigurations, sensors,
264*c564eda5SMatt Simmering                                           sensorTypes);
265a1456c4aSZev Weiss 
266544e7dc5SBruce Mitchell         // IIO _raw devices look like this on sysfs:
267544e7dc5SBruce Mitchell         //     /sys/bus/iio/devices/iio:device0/in_temp_raw
268544e7dc5SBruce Mitchell         //     /sys/bus/iio/devices/iio:device0/in_temp_offset
269544e7dc5SBruce Mitchell         //     /sys/bus/iio/devices/iio:device0/in_temp_scale
270544e7dc5SBruce Mitchell         //
271544e7dc5SBruce Mitchell         // Other IIO devices look like this on sysfs:
272544e7dc5SBruce Mitchell         //     /sys/bus/iio/devices/iio:device1/in_temp_input
273544e7dc5SBruce Mitchell         //     /sys/bus/iio/devices/iio:device1/in_pressure_input
2746714a25aSJames Feist         std::vector<fs::path> paths;
275544e7dc5SBruce Mitchell         fs::path root("/sys/bus/iio/devices");
276544e7dc5SBruce Mitchell         findFiles(root, R"(in_temp\d*_(input|raw))", paths);
277544e7dc5SBruce Mitchell         findFiles(root, R"(in_pressure\d*_(input|raw))", paths);
2783ec41c53SBruce Mitchell         findFiles(root, R"(in_humidityrelative\d*_(input|raw))", paths);
279544e7dc5SBruce Mitchell         findFiles(fs::path("/sys/class/hwmon"), R"(temp\d+_input)", paths);
280544e7dc5SBruce Mitchell 
281544e7dc5SBruce Mitchell         // iterate through all found temp and pressure sensors,
282544e7dc5SBruce Mitchell         // and try to match them with configuration
2836714a25aSJames Feist         for (auto& path : paths)
2846714a25aSJames Feist         {
2856714a25aSJames Feist             std::smatch match;
286544e7dc5SBruce Mitchell             const std::string pathStr = path.string();
2876714a25aSJames Feist             auto directory = path.parent_path();
288544e7dc5SBruce Mitchell             fs::path device;
2896714a25aSJames Feist 
290544e7dc5SBruce Mitchell             std::string deviceName;
291544e7dc5SBruce Mitchell             if (pathStr.starts_with("/sys/bus/iio/devices"))
2926714a25aSJames Feist             {
293544e7dc5SBruce Mitchell                 device = fs::canonical(directory);
294544e7dc5SBruce Mitchell                 deviceName = device.parent_path().stem();
29537266ca9SJames Feist             }
296544e7dc5SBruce Mitchell             else
297544e7dc5SBruce Mitchell             {
298544e7dc5SBruce Mitchell                 device = directory / "device";
299544e7dc5SBruce Mitchell                 deviceName = fs::canonical(device).stem();
300544e7dc5SBruce Mitchell             }
3018a57ec09SEd Tanous             auto findHyphen = deviceName.find('-');
30237266ca9SJames Feist             if (findHyphen == std::string::npos)
30337266ca9SJames Feist             {
30437266ca9SJames Feist                 std::cerr << "found bad device " << deviceName << "\n";
3056714a25aSJames Feist                 continue;
3066714a25aSJames Feist             }
30737266ca9SJames Feist             std::string busStr = deviceName.substr(0, findHyphen);
30837266ca9SJames Feist             std::string addrStr = deviceName.substr(findHyphen + 1);
30937266ca9SJames Feist 
3107dd6443bSJae Hyun Yoo             uint64_t bus = 0;
3117dd6443bSJae Hyun Yoo             uint64_t addr = 0;
3122049bd26SEd Tanous             std::from_chars_result res{};
313bb67932aSEd Tanous             res = std::from_chars(busStr.data(), busStr.data() + busStr.size(),
314bb67932aSEd Tanous                                   bus);
3157dd6443bSJae Hyun Yoo             if (res.ec != std::errc{})
3166714a25aSJames Feist             {
3177dd6443bSJae Hyun Yoo                 continue;
31837266ca9SJames Feist             }
319bb67932aSEd Tanous             res = std::from_chars(addrStr.data(),
320bb67932aSEd Tanous                                   addrStr.data() + addrStr.size(), addr, 16);
3217dd6443bSJae Hyun Yoo             if (res.ec != std::errc{})
32237266ca9SJames Feist             {
3236714a25aSJames Feist                 continue;
3246714a25aSJames Feist             }
32537266ca9SJames Feist 
326544e7dc5SBruce Mitchell             auto thisSensorParameters = getSensorParameters(path);
3279f3a74edSJayashree Dhanapal             auto findSensorCfg = configMap.find({bus, addr});
3289f3a74edSJayashree Dhanapal             if (findSensorCfg == configMap.end())
32937266ca9SJames Feist             {
33037266ca9SJames Feist                 continue;
33137266ca9SJames Feist             }
33237266ca9SJames Feist 
333bb67932aSEd Tanous             const std::string& interfacePath = findSensorCfg->second.sensorPath;
3347627c860SZev Weiss             auto findI2CDev = devices.find(interfacePath);
3357627c860SZev Weiss 
336a1456c4aSZev Weiss             std::shared_ptr<I2CDevice> i2cDev;
3377627c860SZev Weiss             if (findI2CDev != devices.end())
338a1456c4aSZev Weiss             {
3399bbeff75SJoseph Fu                 // If we're only looking to activate newly-instantiated i2c
3409bbeff75SJoseph Fu                 // devices and this sensor's underlying device was already there
3419bbeff75SJoseph Fu                 // before this call, there's nothing more to do here.
3429bbeff75SJoseph Fu                 if (activateOnly && !findI2CDev->second.second)
3439bbeff75SJoseph Fu                 {
3449bbeff75SJoseph Fu                     continue;
3459bbeff75SJoseph Fu                 }
3467627c860SZev Weiss                 i2cDev = findI2CDev->second.first;
347a1456c4aSZev Weiss             }
348a1456c4aSZev Weiss 
3499f3a74edSJayashree Dhanapal             const SensorData& sensorData = findSensorCfg->second.sensorData;
3500489ec20SMatt Spinler             std::string sensorType = findSensorCfg->second.interface;
3510489ec20SMatt Spinler             auto pos = sensorType.find_last_of('.');
3520489ec20SMatt Spinler             if (pos != std::string::npos)
3530489ec20SMatt Spinler             {
3540489ec20SMatt Spinler                 sensorType = sensorType.substr(pos + 1);
3550489ec20SMatt Spinler             }
3569f3a74edSJayashree Dhanapal             const SensorBaseConfigMap& baseConfigMap =
3579f3a74edSJayashree Dhanapal                 findSensorCfg->second.config;
358bb67932aSEd Tanous             std::vector<std::string>& hwmonName = findSensorCfg->second.name;
3596714a25aSJames Feist 
360544e7dc5SBruce Mitchell             // Temperature has "Name", pressure has "Name1"
3619f3a74edSJayashree Dhanapal             auto findSensorName = baseConfigMap.find("Name");
362fefdbe7fSPotin Lai             int index = 1;
3633ec41c53SBruce Mitchell             if (thisSensorParameters.typeName == "pressure" ||
3643ec41c53SBruce Mitchell                 thisSensorParameters.typeName == "humidity")
365544e7dc5SBruce Mitchell             {
3669f3a74edSJayashree Dhanapal                 findSensorName = baseConfigMap.find("Name1");
367fefdbe7fSPotin Lai                 index = 2;
368544e7dc5SBruce Mitchell             }
369544e7dc5SBruce Mitchell 
3709f3a74edSJayashree Dhanapal             if (findSensorName == baseConfigMap.end())
3716714a25aSJames Feist             {
3726714a25aSJames Feist                 std::cerr << "could not determine configuration name for "
37337266ca9SJames Feist                           << deviceName << "\n";
3746714a25aSJames Feist                 continue;
3756714a25aSJames Feist             }
376df515159SJames Feist             std::string sensorName =
377df515159SJames Feist                 std::get<std::string>(findSensorName->second);
3786714a25aSJames Feist             // on rescans, only update sensors we were signaled by
3796714a25aSJames Feist             auto findSensor = sensors.find(sensorName);
3806714a25aSJames Feist             if (!firstScan && findSensor != sensors.end())
3816714a25aSJames Feist             {
3826714a25aSJames Feist                 bool found = false;
383d653b75cSBruce Mitchell                 auto it = sensorsChanged->begin();
384d653b75cSBruce Mitchell                 while (it != sensorsChanged->end())
3856714a25aSJames Feist                 {
3866c106d66SZev Weiss                     if (it->ends_with(findSensor->second->name))
3876714a25aSJames Feist                     {
388d653b75cSBruce Mitchell                         it = sensorsChanged->erase(it);
3896714a25aSJames Feist                         findSensor->second = nullptr;
3906714a25aSJames Feist                         found = true;
3916714a25aSJames Feist                         break;
3926714a25aSJames Feist                     }
393d653b75cSBruce Mitchell                     ++it;
3946714a25aSJames Feist                 }
3956714a25aSJames Feist                 if (!found)
3966714a25aSJames Feist                 {
3976714a25aSJames Feist                     continue;
3986714a25aSJames Feist                 }
3996714a25aSJames Feist             }
4005636d52bSMatt Spinler 
4016714a25aSJames Feist             std::vector<thresholds::Threshold> sensorThresholds;
4025636d52bSMatt Spinler 
4039f3a74edSJayashree Dhanapal             if (!parseThresholdsFromConfig(sensorData, sensorThresholds,
4045636d52bSMatt Spinler                                            nullptr, &index))
4056714a25aSJames Feist             {
406bb67932aSEd Tanous                 std::cerr << "error populating thresholds for " << sensorName
407bb67932aSEd Tanous                           << " index " << index << "\n";
4086714a25aSJames Feist             }
40987bc67f7SJeff Lin 
4108569bf2aSZev Weiss             float pollRate = getPollRate(baseConfigMap, pollRateDefault);
411a4d2768cSZev Weiss             PowerState readState = getPowerState(baseConfigMap);
412100c20bfSJason Ling 
4139f3a74edSJayashree Dhanapal             auto permitSet = getPermitSet(baseConfigMap);
4148b3f7d40SAlex Qiu             auto& sensor = sensors[sensorName];
415a1456c4aSZev Weiss             if (!activateOnly)
416a1456c4aSZev Weiss             {
4178b3f7d40SAlex Qiu                 sensor = nullptr;
418a1456c4aSZev Weiss             }
419779c96a2SPatrick Williams             auto hwmonFile = getFullHwmonFilePath(directory.string(), "temp1",
420779c96a2SPatrick Williams                                                   permitSet);
421544e7dc5SBruce Mitchell             if (pathStr.starts_with("/sys/bus/iio/devices"))
422544e7dc5SBruce Mitchell             {
423544e7dc5SBruce Mitchell                 hwmonFile = pathStr;
424544e7dc5SBruce Mitchell             }
425100c20bfSJason Ling             if (hwmonFile)
426100c20bfSJason Ling             {
427a1456c4aSZev Weiss                 if (sensor != nullptr)
428a1456c4aSZev Weiss                 {
429a1456c4aSZev Weiss                     sensor->activate(*hwmonFile, i2cDev);
430a1456c4aSZev Weiss                 }
431a1456c4aSZev Weiss                 else
432a1456c4aSZev Weiss                 {
433f3fd1915SYong Li                     sensor = std::make_shared<HwmonTempSensor>(
434a1456c4aSZev Weiss                         *hwmonFile, sensorType, objectServer, dbusConnection,
435a1456c4aSZev Weiss                         io, sensorName, std::move(sensorThresholds),
436a1456c4aSZev Weiss                         thisSensorParameters, pollRate, interfacePath,
437a1456c4aSZev Weiss                         readState, i2cDev);
438f3fd1915SYong Li                     sensor->setupRead();
4399eb0cc3dSWilly Tu                 }
440a1456c4aSZev Weiss             }
4419f3a74edSJayashree Dhanapal             hwmonName.erase(
4429f3a74edSJayashree Dhanapal                 remove(hwmonName.begin(), hwmonName.end(), sensorName),
4439f3a74edSJayashree Dhanapal                 hwmonName.end());
4449eb0cc3dSWilly Tu 
4458b3f7d40SAlex Qiu             // Looking for keys like "Name1" for temp2_input,
4468b3f7d40SAlex Qiu             // "Name2" for temp3_input, etc.
4478b3f7d40SAlex Qiu             int i = 0;
4488b3f7d40SAlex Qiu             while (true)
44937266ca9SJames Feist             {
4508b3f7d40SAlex Qiu                 ++i;
451bb67932aSEd Tanous                 auto findKey = baseConfigMap.find("Name" + std::to_string(i));
4529f3a74edSJayashree Dhanapal                 if (findKey == baseConfigMap.end())
4538b3f7d40SAlex Qiu                 {
4548b3f7d40SAlex Qiu                     break;
45537266ca9SJames Feist                 }
456bb67932aSEd Tanous                 std::string sensorName = std::get<std::string>(findKey->second);
457bb67932aSEd Tanous                 hwmonFile = getFullHwmonFilePath(directory.string(),
458bb67932aSEd Tanous                                                  "temp" + std::to_string(i + 1),
459100c20bfSJason Ling                                                  permitSet);
460544e7dc5SBruce Mitchell                 if (pathStr.starts_with("/sys/bus/iio/devices"))
461544e7dc5SBruce Mitchell                 {
462544e7dc5SBruce Mitchell                     continue;
463544e7dc5SBruce Mitchell                 }
464100c20bfSJason Ling                 if (hwmonFile)
465100c20bfSJason Ling                 {
4665636d52bSMatt Spinler                     // To look up thresholds for these additional sensors,
4675636d52bSMatt Spinler                     // match on the Index property in the threshold data
4685636d52bSMatt Spinler                     // where the index comes from the sysfs file we're on,
4695636d52bSMatt Spinler                     // i.e. index = 2 for temp2_input.
4705636d52bSMatt Spinler                     int index = i + 1;
4715636d52bSMatt Spinler                     std::vector<thresholds::Threshold> thresholds;
4725636d52bSMatt Spinler 
4739f3a74edSJayashree Dhanapal                     if (!parseThresholdsFromConfig(sensorData, thresholds,
4745636d52bSMatt Spinler                                                    nullptr, &index))
4755636d52bSMatt Spinler                     {
4765636d52bSMatt Spinler                         std::cerr << "error populating thresholds for "
477bb67932aSEd Tanous                                   << sensorName << " index " << index << "\n";
4785636d52bSMatt Spinler                     }
4795636d52bSMatt Spinler 
4808b3f7d40SAlex Qiu                     auto& sensor = sensors[sensorName];
481a1456c4aSZev Weiss                     if (!activateOnly)
482a1456c4aSZev Weiss                     {
4838b3f7d40SAlex Qiu                         sensor = nullptr;
484a1456c4aSZev Weiss                     }
485a1456c4aSZev Weiss 
486a1456c4aSZev Weiss                     if (sensor != nullptr)
487a1456c4aSZev Weiss                     {
488a1456c4aSZev Weiss                         sensor->activate(*hwmonFile, i2cDev);
489a1456c4aSZev Weiss                     }
490a1456c4aSZev Weiss                     else
491a1456c4aSZev Weiss                     {
492f3fd1915SYong Li                         sensor = std::make_shared<HwmonTempSensor>(
493a1456c4aSZev Weiss                             *hwmonFile, sensorType, objectServer,
494a1456c4aSZev Weiss                             dbusConnection, io, sensorName,
495a1456c4aSZev Weiss                             std::move(thresholds), thisSensorParameters,
496a1456c4aSZev Weiss                             pollRate, interfacePath, readState, i2cDev);
497f3fd1915SYong Li                         sensor->setupRead();
4988b3f7d40SAlex Qiu                     }
499a1456c4aSZev Weiss                 }
5009eb0cc3dSWilly Tu 
5019eb0cc3dSWilly Tu                 hwmonName.erase(
5029eb0cc3dSWilly Tu                     remove(hwmonName.begin(), hwmonName.end(), sensorName),
5039eb0cc3dSWilly Tu                     hwmonName.end());
5046714a25aSJames Feist             }
50531ec7dbbSMatt Spinler             if (hwmonName.empty())
50631ec7dbbSMatt Spinler             {
5079f3a74edSJayashree Dhanapal                 configMap.erase(findSensorCfg);
5089f3a74edSJayashree Dhanapal             }
50931ec7dbbSMatt Spinler         }
5108a17c303SEd Tanous         });
511d29f8aa0SZev Weiss     std::vector<std::string> types(sensorTypes.size());
512d29f8aa0SZev Weiss     for (const auto& [type, dt] : sensorTypes)
513d29f8aa0SZev Weiss     {
514d29f8aa0SZev Weiss         types.push_back(type);
515d29f8aa0SZev Weiss     }
516d29f8aa0SZev Weiss     getter->getConfiguration(types);
5176714a25aSJames Feist }
5186714a25aSJames Feist 
51920bf2c1cSMatt Spinler void interfaceRemoved(
52092f8f515SPatrick Williams     sdbusplus::message_t& message,
52120bf2c1cSMatt Spinler     boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
52220bf2c1cSMatt Spinler         sensors)
52320bf2c1cSMatt Spinler {
52420bf2c1cSMatt Spinler     if (message.is_method_error())
52520bf2c1cSMatt Spinler     {
52620bf2c1cSMatt Spinler         std::cerr << "interfacesRemoved callback method error\n";
52720bf2c1cSMatt Spinler         return;
52820bf2c1cSMatt Spinler     }
52920bf2c1cSMatt Spinler 
53020bf2c1cSMatt Spinler     sdbusplus::message::object_path path;
53120bf2c1cSMatt Spinler     std::vector<std::string> interfaces;
53220bf2c1cSMatt Spinler 
53320bf2c1cSMatt Spinler     message.read(path, interfaces);
53420bf2c1cSMatt Spinler 
53520bf2c1cSMatt Spinler     // If the xyz.openbmc_project.Confguration.X interface was removed
53620bf2c1cSMatt Spinler     // for one or more sensors, delete those sensor objects.
53720bf2c1cSMatt Spinler     auto sensorIt = sensors.begin();
53820bf2c1cSMatt Spinler     while (sensorIt != sensors.end())
53920bf2c1cSMatt Spinler     {
54020bf2c1cSMatt Spinler         if ((sensorIt->second->configurationPath == path) &&
54120bf2c1cSMatt Spinler             (std::find(interfaces.begin(), interfaces.end(),
54255832f37SMatt Spinler                        sensorIt->second->configInterface) != interfaces.end()))
54320bf2c1cSMatt Spinler         {
54420bf2c1cSMatt Spinler             sensorIt = sensors.erase(sensorIt);
54520bf2c1cSMatt Spinler         }
54620bf2c1cSMatt Spinler         else
54720bf2c1cSMatt Spinler         {
54820bf2c1cSMatt Spinler             sensorIt++;
54920bf2c1cSMatt Spinler         }
55020bf2c1cSMatt Spinler     }
55120bf2c1cSMatt Spinler }
55220bf2c1cSMatt Spinler 
553a1456c4aSZev Weiss static void powerStateChanged(
554a1456c4aSZev Weiss     PowerState type, bool newState,
555a1456c4aSZev Weiss     boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
556a1456c4aSZev Weiss         sensors,
5571f978631SEd Tanous     boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
558a1456c4aSZev Weiss     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
559a1456c4aSZev Weiss {
560a1456c4aSZev Weiss     if (newState)
561a1456c4aSZev Weiss     {
562a1456c4aSZev Weiss         createSensors(io, objectServer, sensors, dbusConnection, nullptr, true);
563a1456c4aSZev Weiss     }
564a1456c4aSZev Weiss     else
565a1456c4aSZev Weiss     {
566a1456c4aSZev Weiss         for (auto& [path, sensor] : sensors)
567a1456c4aSZev Weiss         {
568a1456c4aSZev Weiss             if (sensor != nullptr && sensor->readState == type)
569a1456c4aSZev Weiss             {
570a1456c4aSZev Weiss                 sensor->deactivate();
571a1456c4aSZev Weiss             }
572a1456c4aSZev Weiss         }
573a1456c4aSZev Weiss     }
574a1456c4aSZev Weiss }
575a1456c4aSZev Weiss 
576b6c0b914SJames Feist int main()
5776714a25aSJames Feist {
5781f978631SEd Tanous     boost::asio::io_context io;
5796714a25aSJames Feist     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
58014ed5e99SEd Tanous     sdbusplus::asio::object_server objectServer(systemBus, true);
58114ed5e99SEd Tanous     objectServer.add_manager("/xyz/openbmc_project/sensors");
5826714a25aSJames Feist     systemBus->request_name("xyz.openbmc_project.HwmonTempSensor");
58314ed5e99SEd Tanous 
584f3fd1915SYong Li     boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>
5856714a25aSJames Feist         sensors;
5865591cf08SJames Feist     auto sensorsChanged =
5875591cf08SJames Feist         std::make_shared<boost::container::flat_set<std::string>>();
5886714a25aSJames Feist 
589a1456c4aSZev Weiss     auto powerCallBack = [&sensors, &io, &objectServer,
590a1456c4aSZev Weiss                           &systemBus](PowerState type, bool state) {
591a1456c4aSZev Weiss         powerStateChanged(type, state, sensors, io, objectServer, systemBus);
592a1456c4aSZev Weiss     };
593a1456c4aSZev Weiss     setupPowerMatchCallback(systemBus, powerCallBack);
594a1456c4aSZev Weiss 
59583db50caSEd Tanous     boost::asio::post(io, [&]() {
596a1456c4aSZev Weiss         createSensors(io, objectServer, sensors, systemBus, nullptr, false);
5976714a25aSJames Feist     });
5986714a25aSJames Feist 
5999b4a20e9SEd Tanous     boost::asio::steady_timer filterTimer(io);
60092f8f515SPatrick Williams     std::function<void(sdbusplus::message_t&)> eventHandler =
60192f8f515SPatrick Williams         [&](sdbusplus::message_t& message) {
6026714a25aSJames Feist         if (message.is_method_error())
6036714a25aSJames Feist         {
6046714a25aSJames Feist             std::cerr << "callback method error\n";
6056714a25aSJames Feist             return;
6066714a25aSJames Feist         }
6076714a25aSJames Feist         sensorsChanged->insert(message.get_path());
6086714a25aSJames Feist         // this implicitly cancels the timer
60983db50caSEd Tanous         filterTimer.expires_after(std::chrono::seconds(1));
6106714a25aSJames Feist 
6116714a25aSJames Feist         filterTimer.async_wait([&](const boost::system::error_code& ec) {
6126714a25aSJames Feist             if (ec == boost::asio::error::operation_aborted)
6136714a25aSJames Feist             {
6146714a25aSJames Feist                 /* we were canceled*/
6156714a25aSJames Feist                 return;
6166714a25aSJames Feist             }
6178a57ec09SEd Tanous             if (ec)
6186714a25aSJames Feist             {
6196714a25aSJames Feist                 std::cerr << "timer error\n";
6206714a25aSJames Feist                 return;
6216714a25aSJames Feist             }
622a1456c4aSZev Weiss             createSensors(io, objectServer, sensors, systemBus, sensorsChanged,
623a1456c4aSZev Weiss                           false);
6246714a25aSJames Feist         });
6256714a25aSJames Feist     };
6266714a25aSJames Feist 
627214d9717SZev Weiss     std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
628214d9717SZev Weiss         setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
6291263c3daSBruce Lee     setupManufacturingModeMatch(*systemBus);
63020bf2c1cSMatt Spinler 
63120bf2c1cSMatt Spinler     // Watch for entity-manager to remove configuration interfaces
63220bf2c1cSMatt Spinler     // so the corresponding sensors can be removed.
63392f8f515SPatrick Williams     auto ifaceRemovedMatch = std::make_unique<sdbusplus::bus::match_t>(
63492f8f515SPatrick Williams         static_cast<sdbusplus::bus_t&>(*systemBus),
63520bf2c1cSMatt Spinler         "type='signal',member='InterfacesRemoved',arg0path='" +
63620bf2c1cSMatt Spinler             std::string(inventoryPath) + "/'",
63792f8f515SPatrick Williams         [&sensors](sdbusplus::message_t& msg) {
63820bf2c1cSMatt Spinler         interfaceRemoved(msg, sensors);
63920bf2c1cSMatt Spinler         });
64020bf2c1cSMatt Spinler 
64120bf2c1cSMatt Spinler     matches.emplace_back(std::move(ifaceRemovedMatch));
64220bf2c1cSMatt Spinler 
6436714a25aSJames Feist     io.run();
6446714a25aSJames Feist }
645