blob: bb2f6a4bc99a5012cc67570fceeac8b1a0951651 [file] [log] [blame]
James Feist6714a252018-09-10 15:26:18 -07001/*
2// Copyright (c) 2017 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
Andrew Jefferye73bd0a2023-01-25 10:39:57 +103017#include "DeviceMgmt.hpp"
18#include "HwmonTempSensor.hpp"
19#include "Utils.hpp"
20
James Feist6714a252018-09-10 15:26:18 -070021#include <boost/algorithm/string/replace.hpp>
Patrick Venture96e97db2019-10-31 13:44:38 -070022#include <boost/container/flat_map.hpp>
James Feist6714a252018-09-10 15:26:18 -070023#include <boost/container/flat_set.hpp>
James Feist38fb5982020-05-28 10:09:54 -070024#include <sdbusplus/asio/connection.hpp>
25#include <sdbusplus/asio/object_server.hpp>
26#include <sdbusplus/bus/match.hpp>
27
28#include <array>
Jae Hyun Yoo7dd64432022-03-30 14:28:33 -070029#include <charconv>
James Feist24f02f22019-04-15 11:05:39 -070030#include <filesystem>
James Feist6714a252018-09-10 15:26:18 -070031#include <fstream>
Patrick Venture96e97db2019-10-31 13:44:38 -070032#include <functional>
33#include <memory>
James Feist6714a252018-09-10 15:26:18 -070034#include <regex>
Patrick Venture96e97db2019-10-31 13:44:38 -070035#include <stdexcept>
36#include <string>
37#include <utility>
38#include <variant>
39#include <vector>
James Feist6714a252018-09-10 15:26:18 -070040
Jeff Lin87bc67f2020-12-04 20:58:01 +080041static constexpr float pollRateDefault = 0.5;
James Feist6714a252018-09-10 15:26:18 -070042
Zhikui Rencb359da2023-08-03 16:45:44 -070043static constexpr double maxValuePressure = 120000; // Pascals
44static constexpr double minValuePressure = 30000; // Pascals
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050045
Bruce Mitchell3ec41c52021-12-10 16:05:17 -060046static constexpr double maxValueRelativeHumidity = 100; // PercentRH
47static constexpr double minValueRelativeHumidity = 0; // PercentRH
48
Zhikui Rencb359da2023-08-03 16:45:44 -070049static constexpr double maxValueTemperature = 127; // DegreesC
50static constexpr double minValueTemperature = -128; // DegreesC
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050051
James Feistcf3bce62019-01-08 10:07:19 -080052namespace fs = std::filesystem;
Zev Weissd29f8aa2022-08-03 16:24:59 -070053
54static const I2CDeviceTypeMap sensorTypes{
55 {"DPS310", I2CDeviceType{"dps310", false}},
56 {"EMC1412", I2CDeviceType{"emc1412", true}},
57 {"EMC1413", I2CDeviceType{"emc1413", true}},
58 {"EMC1414", I2CDeviceType{"emc1414", true}},
59 {"HDC1080", I2CDeviceType{"hdc1080", false}},
60 {"JC42", I2CDeviceType{"jc42", true}},
61 {"LM75A", I2CDeviceType{"lm75a", true}},
62 {"LM95234", I2CDeviceType{"lm95234", true}},
63 {"MAX31725", I2CDeviceType{"max31725", true}},
64 {"MAX31730", I2CDeviceType{"max31730", true}},
65 {"MAX6581", I2CDeviceType{"max6581", true}},
66 {"MAX6654", I2CDeviceType{"max6654", true}},
67 {"NCT6779", I2CDeviceType{"nct6779", true}},
68 {"NCT7802", I2CDeviceType{"nct7802", true}},
69 {"SBTSI", I2CDeviceType{"sbtsi", true}},
70 {"SI7020", I2CDeviceType{"si7020", false}},
Tim Lee9b0a6f62022-12-23 14:47:02 +080071 {"TMP100", I2CDeviceType{"tmp100", true}},
Zev Weissd29f8aa2022-08-03 16:24:59 -070072 {"TMP112", I2CDeviceType{"tmp112", true}},
73 {"TMP175", I2CDeviceType{"tmp175", true}},
74 {"TMP421", I2CDeviceType{"tmp421", true}},
75 {"TMP441", I2CDeviceType{"tmp441", true}},
Hieu Huynh9a7db6a2023-06-19 11:02:07 +000076 {"TMP464", I2CDeviceType{"tmp464", true}},
Zev Weissd29f8aa2022-08-03 16:24:59 -070077 {"TMP75", I2CDeviceType{"tmp75", true}},
78 {"W83773G", I2CDeviceType{"w83773g", true}},
79};
James Feist6714a252018-09-10 15:26:18 -070080
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050081static struct SensorParams
82 getSensorParameters(const std::filesystem::path& path)
83{
84 // offset is to default to 0 and scale to 1, see lore
85 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
Patrick Williams779c96a2023-05-10 07:50:42 -050086 struct SensorParams tmpSensorParameters = {
87 .minValue = minValueTemperature,
88 .maxValue = maxValueTemperature,
89 .offsetValue = 0.0,
90 .scaleValue = 1.0,
91 .units = sensor_paths::unitDegreesC,
92 .typeName = "temperature"};
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050093
94 // For IIO RAW sensors we get a raw_value, an offset, and scale
95 // to compute the value = (raw_value + offset) * scale
96 // with a _raw IIO device we need to get the
97 // offsetValue and scaleValue from the driver
98 // these are used to compute the reading in
99 // units that have yet to be scaled for D-Bus.
100 const std::string pathStr = path.string();
101 if (pathStr.ends_with("_raw"))
102 {
Patrick Williams779c96a2023-05-10 07:50:42 -0500103 std::string pathOffsetStr = pathStr.substr(0, pathStr.size() - 4) +
104 "_offset";
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500105 std::optional<double> tmpOffsetValue = readFile(pathOffsetStr, 1.0);
106 // In case there is nothing to read skip this device
107 // This is not an error condition see lore
108 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
109 if (tmpOffsetValue)
110 {
111 tmpSensorParameters.offsetValue = *tmpOffsetValue;
112 }
113
Patrick Williams779c96a2023-05-10 07:50:42 -0500114 std::string pathScaleStr = pathStr.substr(0, pathStr.size() - 4) +
115 "_scale";
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500116 std::optional<double> tmpScaleValue = readFile(pathScaleStr, 1.0);
117 // In case there is nothing to read skip this device
118 // This is not an error condition see lore
119 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
120 if (tmpScaleValue)
121 {
122 tmpSensorParameters.scaleValue = *tmpScaleValue;
123 }
124 }
125
126 // Temperatures are read in milli degrees Celsius, we need
127 // degrees Celsius. Pressures are read in kilopascal, we need
128 // Pascals. On D-Bus for Open BMC we use the International
129 // System of Units without prefixes. Links to the kernel
130 // documentation:
131 // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface
132 // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-iio
133 if (path.filename() == "in_pressure_input" ||
134 path.filename() == "in_pressure_raw")
135 {
136 tmpSensorParameters.minValue = minValuePressure;
137 tmpSensorParameters.maxValue = maxValuePressure;
138 // Pressures are read in kilopascal, we need Pascals.
139 tmpSensorParameters.scaleValue *= 1000.0;
140 tmpSensorParameters.typeName = "pressure";
Bruce Mitchell5a86e562021-12-10 12:26:22 -0600141 tmpSensorParameters.units = sensor_paths::unitPascals;
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500142 }
Bruce Mitchell3ec41c52021-12-10 16:05:17 -0600143 else if (path.filename() == "in_humidityrelative_input" ||
144 path.filename() == "in_humidityrelative_raw")
145 {
146 tmpSensorParameters.minValue = minValueRelativeHumidity;
147 tmpSensorParameters.maxValue = maxValueRelativeHumidity;
148 // Relative Humidity are read in milli-percent, we need percent.
149 tmpSensorParameters.scaleValue *= 0.001;
150 tmpSensorParameters.typeName = "humidity";
151 tmpSensorParameters.units = "PercentRH";
152 }
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500153 else
154 {
155 // Temperatures are read in milli degrees Celsius,
156 // we need degrees Celsius.
157 tmpSensorParameters.scaleValue *= 0.001;
158 }
159
160 return tmpSensorParameters;
161}
162
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530163struct SensorConfigKey
164{
165 uint64_t bus;
166 uint64_t addr;
167 bool operator<(const SensorConfigKey& other) const
168 {
169 if (bus != other.bus)
170 {
171 return bus < other.bus;
172 }
173 return addr < other.addr;
174 }
175};
176
177struct SensorConfig
178{
179 std::string sensorPath;
180 SensorData sensorData;
181 std::string interface;
182 SensorBaseConfigMap config;
183 std::vector<std::string> name;
184};
185
186using SensorConfigMap =
187 boost::container::flat_map<SensorConfigKey, SensorConfig>;
188
189static SensorConfigMap
190 buildSensorConfigMap(const ManagedObjectType& sensorConfigs)
191{
192 SensorConfigMap configMap;
Zev Weissa1808332022-08-12 18:21:01 -0700193 for (const auto& [path, cfgData] : sensorConfigs)
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530194 {
Zev Weissa1808332022-08-12 18:21:01 -0700195 for (const auto& [intf, cfg] : cfgData)
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530196 {
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530197 auto busCfg = cfg.find("Bus");
198 auto addrCfg = cfg.find("Address");
199 if ((busCfg == cfg.end()) || (addrCfg == cfg.end()))
200 {
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530201 continue;
202 }
203
Ed Tanous2049bd22022-07-09 07:20:26 -0700204 if ((std::get_if<uint64_t>(&busCfg->second) == nullptr) ||
205 (std::get_if<uint64_t>(&addrCfg->second) == nullptr))
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530206 {
Zev Weissa1808332022-08-12 18:21:01 -0700207 std::cerr << path.str << " Bus or Address invalid\n";
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530208 continue;
209 }
210
211 std::vector<std::string> hwmonNames;
212 auto nameCfg = cfg.find("Name");
213 if (nameCfg != cfg.end())
214 {
215 hwmonNames.push_back(std::get<std::string>(nameCfg->second));
216 size_t i = 1;
217 while (true)
218 {
219 auto sensorNameCfg = cfg.find("Name" + std::to_string(i));
220 if (sensorNameCfg == cfg.end())
221 {
222 break;
223 }
224 hwmonNames.push_back(
225 std::get<std::string>(sensorNameCfg->second));
226 i++;
227 }
228 }
229
230 SensorConfigKey key = {std::get<uint64_t>(busCfg->second),
231 std::get<uint64_t>(addrCfg->second)};
Zev Weissa1808332022-08-12 18:21:01 -0700232 SensorConfig val = {path.str, cfgData, intf, cfg, hwmonNames};
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530233
234 auto [it, inserted] = configMap.emplace(key, std::move(val));
235 if (!inserted)
236 {
Zev Weissa1808332022-08-12 18:21:01 -0700237 std::cerr << path.str << ": ignoring duplicate entry for {"
238 << key.bus << ", 0x" << std::hex << key.addr
239 << std::dec << "}\n";
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530240 }
241 }
242 }
243 return configMap;
244}
245
James Feist6714a252018-09-10 15:26:18 -0700246void createSensors(
Ed Tanous1f978632023-02-28 18:16:39 -0800247 boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
Yong Lif3fd1912020-03-25 21:35:23 +0800248 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
James Feist6714a252018-09-10 15:26:18 -0700249 sensors,
250 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
James Feist5591cf082020-07-15 16:44:54 -0700251 const std::shared_ptr<boost::container::flat_set<std::string>>&
Zev Weissa1456c42022-07-18 16:59:35 -0700252 sensorsChanged,
253 bool activateOnly)
James Feist6714a252018-09-10 15:26:18 -0700254{
James Feistdf515152019-09-18 16:40:40 -0700255 auto getter = std::make_shared<GetSensorConfiguration>(
256 dbusConnection,
Zev Weissa1456c42022-07-18 16:59:35 -0700257 [&io, &objectServer, &sensors, &dbusConnection, sensorsChanged,
258 activateOnly](const ManagedObjectType& sensorConfigurations) {
Ed Tanousbb679322022-05-16 16:10:00 -0700259 bool firstScan = sensorsChanged == nullptr;
James Feist6714a252018-09-10 15:26:18 -0700260
Ed Tanousbb679322022-05-16 16:10:00 -0700261 SensorConfigMap configMap = buildSensorConfigMap(sensorConfigurations);
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530262
Matt Simmeringc564eda2023-05-12 13:04:43 -0700263 auto devices = instantiateDevices(sensorConfigurations, sensors,
264 sensorTypes);
Zev Weissa1456c42022-07-18 16:59:35 -0700265
Ed Tanousbb679322022-05-16 16:10:00 -0700266 // IIO _raw devices look like this on sysfs:
267 // /sys/bus/iio/devices/iio:device0/in_temp_raw
268 // /sys/bus/iio/devices/iio:device0/in_temp_offset
269 // /sys/bus/iio/devices/iio:device0/in_temp_scale
270 //
271 // Other IIO devices look like this on sysfs:
272 // /sys/bus/iio/devices/iio:device1/in_temp_input
273 // /sys/bus/iio/devices/iio:device1/in_pressure_input
274 std::vector<fs::path> paths;
275 fs::path root("/sys/bus/iio/devices");
276 findFiles(root, R"(in_temp\d*_(input|raw))", paths);
277 findFiles(root, R"(in_pressure\d*_(input|raw))", paths);
278 findFiles(root, R"(in_humidityrelative\d*_(input|raw))", paths);
279 findFiles(fs::path("/sys/class/hwmon"), R"(temp\d+_input)", paths);
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500280
Ed Tanousbb679322022-05-16 16:10:00 -0700281 // iterate through all found temp and pressure sensors,
282 // and try to match them with configuration
283 for (auto& path : paths)
284 {
285 std::smatch match;
286 const std::string pathStr = path.string();
287 auto directory = path.parent_path();
288 fs::path device;
289
290 std::string deviceName;
291 if (pathStr.starts_with("/sys/bus/iio/devices"))
James Feist37266ca2018-10-15 15:56:28 -0700292 {
Ed Tanousbb679322022-05-16 16:10:00 -0700293 device = fs::canonical(directory);
294 deviceName = device.parent_path().stem();
295 }
296 else
297 {
298 device = directory / "device";
299 deviceName = fs::canonical(device).stem();
300 }
301 auto findHyphen = deviceName.find('-');
302 if (findHyphen == std::string::npos)
303 {
304 std::cerr << "found bad device " << deviceName << "\n";
305 continue;
306 }
307 std::string busStr = deviceName.substr(0, findHyphen);
308 std::string addrStr = deviceName.substr(findHyphen + 1);
309
310 uint64_t bus = 0;
311 uint64_t addr = 0;
Ed Tanous2049bd22022-07-09 07:20:26 -0700312 std::from_chars_result res{};
Ed Tanousbb679322022-05-16 16:10:00 -0700313 res = std::from_chars(busStr.data(), busStr.data() + busStr.size(),
314 bus);
315 if (res.ec != std::errc{})
316 {
317 continue;
318 }
319 res = std::from_chars(addrStr.data(),
320 addrStr.data() + addrStr.size(), addr, 16);
321 if (res.ec != std::errc{})
322 {
323 continue;
James Feistdf515152019-09-18 16:40:40 -0700324 }
325
Ed Tanousbb679322022-05-16 16:10:00 -0700326 auto thisSensorParameters = getSensorParameters(path);
327 auto findSensorCfg = configMap.find({bus, addr});
328 if (findSensorCfg == configMap.end())
James Feistdf515152019-09-18 16:40:40 -0700329 {
Ed Tanousbb679322022-05-16 16:10:00 -0700330 continue;
331 }
James Feistdf515152019-09-18 16:40:40 -0700332
Ed Tanousbb679322022-05-16 16:10:00 -0700333 const std::string& interfacePath = findSensorCfg->second.sensorPath;
Zev Weiss7627c862022-11-17 14:23:04 -0800334 auto findI2CDev = devices.find(interfacePath);
335
Zev Weissa1456c42022-07-18 16:59:35 -0700336 std::shared_ptr<I2CDevice> i2cDev;
Zev Weiss7627c862022-11-17 14:23:04 -0800337 if (findI2CDev != devices.end())
Zev Weissa1456c42022-07-18 16:59:35 -0700338 {
Joseph Fu9bbeff72022-12-05 19:09:16 +0800339 // If we're only looking to activate newly-instantiated i2c
340 // devices and this sensor's underlying device was already there
341 // before this call, there's nothing more to do here.
342 if (activateOnly && !findI2CDev->second.second)
343 {
344 continue;
345 }
Zev Weiss7627c862022-11-17 14:23:04 -0800346 i2cDev = findI2CDev->second.first;
Zev Weissa1456c42022-07-18 16:59:35 -0700347 }
348
Ed Tanousbb679322022-05-16 16:10:00 -0700349 const SensorData& sensorData = findSensorCfg->second.sensorData;
Matt Spinler0489ec22023-06-05 15:08:59 -0500350 std::string sensorType = findSensorCfg->second.interface;
351 auto pos = sensorType.find_last_of('.');
352 if (pos != std::string::npos)
353 {
354 sensorType = sensorType.substr(pos + 1);
355 }
Ed Tanousbb679322022-05-16 16:10:00 -0700356 const SensorBaseConfigMap& baseConfigMap =
357 findSensorCfg->second.config;
358 std::vector<std::string>& hwmonName = findSensorCfg->second.name;
359
360 // Temperature has "Name", pressure has "Name1"
361 auto findSensorName = baseConfigMap.find("Name");
362 int index = 1;
363 if (thisSensorParameters.typeName == "pressure" ||
364 thisSensorParameters.typeName == "humidity")
365 {
366 findSensorName = baseConfigMap.find("Name1");
367 index = 2;
368 }
369
370 if (findSensorName == baseConfigMap.end())
371 {
372 std::cerr << "could not determine configuration name for "
373 << deviceName << "\n";
374 continue;
375 }
376 std::string sensorName =
377 std::get<std::string>(findSensorName->second);
378 // on rescans, only update sensors we were signaled by
379 auto findSensor = sensors.find(sensorName);
380 if (!firstScan && findSensor != sensors.end())
381 {
382 bool found = false;
383 auto it = sensorsChanged->begin();
384 while (it != sensorsChanged->end())
385 {
Zev Weiss6c106d62022-08-17 20:50:00 -0700386 if (it->ends_with(findSensor->second->name))
Ed Tanousbb679322022-05-16 16:10:00 -0700387 {
388 it = sensorsChanged->erase(it);
389 findSensor->second = nullptr;
390 found = true;
391 break;
392 }
393 ++it;
394 }
395 if (!found)
396 {
397 continue;
398 }
399 }
400
401 std::vector<thresholds::Threshold> sensorThresholds;
402
403 if (!parseThresholdsFromConfig(sensorData, sensorThresholds,
404 nullptr, &index))
405 {
406 std::cerr << "error populating thresholds for " << sensorName
407 << " index " << index << "\n";
408 }
409
Zev Weiss8569bf22022-10-11 15:37:44 -0700410 float pollRate = getPollRate(baseConfigMap, pollRateDefault);
Zev Weissa4d27682022-07-19 15:30:36 -0700411 PowerState readState = getPowerState(baseConfigMap);
Ed Tanousbb679322022-05-16 16:10:00 -0700412
413 auto permitSet = getPermitSet(baseConfigMap);
414 auto& sensor = sensors[sensorName];
Zev Weissa1456c42022-07-18 16:59:35 -0700415 if (!activateOnly)
416 {
417 sensor = nullptr;
418 }
Patrick Williams779c96a2023-05-10 07:50:42 -0500419 auto hwmonFile = getFullHwmonFilePath(directory.string(), "temp1",
420 permitSet);
Ed Tanousbb679322022-05-16 16:10:00 -0700421 if (pathStr.starts_with("/sys/bus/iio/devices"))
422 {
423 hwmonFile = pathStr;
424 }
425 if (hwmonFile)
426 {
Zev Weissa1456c42022-07-18 16:59:35 -0700427 if (sensor != nullptr)
428 {
429 sensor->activate(*hwmonFile, i2cDev);
430 }
431 else
432 {
433 sensor = std::make_shared<HwmonTempSensor>(
434 *hwmonFile, sensorType, objectServer, dbusConnection,
435 io, sensorName, std::move(sensorThresholds),
436 thisSensorParameters, pollRate, interfacePath,
437 readState, i2cDev);
438 sensor->setupRead();
439 }
Ed Tanousbb679322022-05-16 16:10:00 -0700440 }
441 hwmonName.erase(
442 remove(hwmonName.begin(), hwmonName.end(), sensorName),
443 hwmonName.end());
444
445 // Looking for keys like "Name1" for temp2_input,
446 // "Name2" for temp3_input, etc.
447 int i = 0;
448 while (true)
449 {
450 ++i;
451 auto findKey = baseConfigMap.find("Name" + std::to_string(i));
452 if (findKey == baseConfigMap.end())
453 {
454 break;
455 }
456 std::string sensorName = std::get<std::string>(findKey->second);
457 hwmonFile = getFullHwmonFilePath(directory.string(),
458 "temp" + std::to_string(i + 1),
459 permitSet);
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500460 if (pathStr.starts_with("/sys/bus/iio/devices"))
James Feist37266ca2018-10-15 15:56:28 -0700461 {
James Feistdf515152019-09-18 16:40:40 -0700462 continue;
463 }
Jason Ling100c20b2020-08-11 14:50:33 -0700464 if (hwmonFile)
465 {
Ed Tanousbb679322022-05-16 16:10:00 -0700466 // To look up thresholds for these additional sensors,
467 // match on the Index property in the threshold data
468 // where the index comes from the sysfs file we're on,
469 // i.e. index = 2 for temp2_input.
470 int index = i + 1;
471 std::vector<thresholds::Threshold> thresholds;
472
473 if (!parseThresholdsFromConfig(sensorData, thresholds,
474 nullptr, &index))
475 {
476 std::cerr << "error populating thresholds for "
477 << sensorName << " index " << index << "\n";
478 }
479
480 auto& sensor = sensors[sensorName];
Zev Weissa1456c42022-07-18 16:59:35 -0700481 if (!activateOnly)
482 {
483 sensor = nullptr;
484 }
485
486 if (sensor != nullptr)
487 {
488 sensor->activate(*hwmonFile, i2cDev);
489 }
490 else
491 {
492 sensor = std::make_shared<HwmonTempSensor>(
493 *hwmonFile, sensorType, objectServer,
494 dbusConnection, io, sensorName,
495 std::move(thresholds), thisSensorParameters,
496 pollRate, interfacePath, readState, i2cDev);
497 sensor->setupRead();
498 }
Jason Ling100c20b2020-08-11 14:50:33 -0700499 }
Ed Tanousbb679322022-05-16 16:10:00 -0700500
Willy Tu9eb0cc32022-04-06 11:03:32 -0700501 hwmonName.erase(
502 remove(hwmonName.begin(), hwmonName.end(), sensorName),
503 hwmonName.end());
James Feistdf515152019-09-18 16:40:40 -0700504 }
Ed Tanousbb679322022-05-16 16:10:00 -0700505 if (hwmonName.empty())
506 {
507 configMap.erase(findSensorCfg);
508 }
509 }
Ed Tanous8a17c302021-09-02 15:07:11 -0700510 });
Zev Weissd29f8aa2022-08-03 16:24:59 -0700511 std::vector<std::string> types(sensorTypes.size());
512 for (const auto& [type, dt] : sensorTypes)
513 {
514 types.push_back(type);
515 }
516 getter->getConfiguration(types);
James Feist6714a252018-09-10 15:26:18 -0700517}
518
Matt Spinler20bf2c12021-09-14 11:07:07 -0500519void interfaceRemoved(
Patrick Williams92f8f512022-07-22 19:26:55 -0500520 sdbusplus::message_t& message,
Matt Spinler20bf2c12021-09-14 11:07:07 -0500521 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
522 sensors)
523{
524 if (message.is_method_error())
525 {
526 std::cerr << "interfacesRemoved callback method error\n";
527 return;
528 }
529
530 sdbusplus::message::object_path path;
531 std::vector<std::string> interfaces;
532
533 message.read(path, interfaces);
534
535 // If the xyz.openbmc_project.Confguration.X interface was removed
536 // for one or more sensors, delete those sensor objects.
537 auto sensorIt = sensors.begin();
538 while (sensorIt != sensors.end())
539 {
540 if ((sensorIt->second->configurationPath == path) &&
541 (std::find(interfaces.begin(), interfaces.end(),
Matt Spinler55832f32023-06-07 10:24:00 -0500542 sensorIt->second->configInterface) != interfaces.end()))
Matt Spinler20bf2c12021-09-14 11:07:07 -0500543 {
544 sensorIt = sensors.erase(sensorIt);
545 }
546 else
547 {
548 sensorIt++;
549 }
550 }
551}
552
Zev Weissa1456c42022-07-18 16:59:35 -0700553static void powerStateChanged(
554 PowerState type, bool newState,
555 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
556 sensors,
Ed Tanous1f978632023-02-28 18:16:39 -0800557 boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
Zev Weissa1456c42022-07-18 16:59:35 -0700558 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
559{
560 if (newState)
561 {
562 createSensors(io, objectServer, sensors, dbusConnection, nullptr, true);
563 }
564 else
565 {
566 for (auto& [path, sensor] : sensors)
567 {
568 if (sensor != nullptr && sensor->readState == type)
569 {
570 sensor->deactivate();
571 }
572 }
573 }
574}
575
James Feistb6c0b912019-07-09 12:21:44 -0700576int main()
James Feist6714a252018-09-10 15:26:18 -0700577{
Ed Tanous1f978632023-02-28 18:16:39 -0800578 boost::asio::io_context io;
James Feist6714a252018-09-10 15:26:18 -0700579 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
Ed Tanous14ed5e92022-07-12 15:50:23 -0700580 sdbusplus::asio::object_server objectServer(systemBus, true);
581 objectServer.add_manager("/xyz/openbmc_project/sensors");
James Feist6714a252018-09-10 15:26:18 -0700582 systemBus->request_name("xyz.openbmc_project.HwmonTempSensor");
Ed Tanous14ed5e92022-07-12 15:50:23 -0700583
Yong Lif3fd1912020-03-25 21:35:23 +0800584 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>
James Feist6714a252018-09-10 15:26:18 -0700585 sensors;
James Feist5591cf082020-07-15 16:44:54 -0700586 auto sensorsChanged =
587 std::make_shared<boost::container::flat_set<std::string>>();
James Feist6714a252018-09-10 15:26:18 -0700588
Zev Weissa1456c42022-07-18 16:59:35 -0700589 auto powerCallBack = [&sensors, &io, &objectServer,
590 &systemBus](PowerState type, bool state) {
591 powerStateChanged(type, state, sensors, io, objectServer, systemBus);
592 };
593 setupPowerMatchCallback(systemBus, powerCallBack);
594
Ed Tanous83db50c2023-03-01 10:20:24 -0800595 boost::asio::post(io, [&]() {
Zev Weissa1456c42022-07-18 16:59:35 -0700596 createSensors(io, objectServer, sensors, systemBus, nullptr, false);
James Feist6714a252018-09-10 15:26:18 -0700597 });
598
Ed Tanous9b4a20e2022-09-06 08:47:11 -0700599 boost::asio::steady_timer filterTimer(io);
Patrick Williams92f8f512022-07-22 19:26:55 -0500600 std::function<void(sdbusplus::message_t&)> eventHandler =
601 [&](sdbusplus::message_t& message) {
Ed Tanousbb679322022-05-16 16:10:00 -0700602 if (message.is_method_error())
603 {
604 std::cerr << "callback method error\n";
605 return;
606 }
607 sensorsChanged->insert(message.get_path());
608 // this implicitly cancels the timer
Ed Tanous83db50c2023-03-01 10:20:24 -0800609 filterTimer.expires_after(std::chrono::seconds(1));
Ed Tanousbb679322022-05-16 16:10:00 -0700610
611 filterTimer.async_wait([&](const boost::system::error_code& ec) {
612 if (ec == boost::asio::error::operation_aborted)
James Feist6714a252018-09-10 15:26:18 -0700613 {
Ed Tanousbb679322022-05-16 16:10:00 -0700614 /* we were canceled*/
James Feist6714a252018-09-10 15:26:18 -0700615 return;
616 }
Ed Tanousbb679322022-05-16 16:10:00 -0700617 if (ec)
618 {
619 std::cerr << "timer error\n";
620 return;
621 }
Zev Weissa1456c42022-07-18 16:59:35 -0700622 createSensors(io, objectServer, sensors, systemBus, sensorsChanged,
623 false);
Ed Tanousbb679322022-05-16 16:10:00 -0700624 });
625 };
James Feist6714a252018-09-10 15:26:18 -0700626
Zev Weiss214d9712022-08-12 12:54:31 -0700627 std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
628 setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
Bruce Lee1263c3d2021-06-04 15:16:33 +0800629 setupManufacturingModeMatch(*systemBus);
Matt Spinler20bf2c12021-09-14 11:07:07 -0500630
631 // Watch for entity-manager to remove configuration interfaces
632 // so the corresponding sensors can be removed.
Patrick Williams92f8f512022-07-22 19:26:55 -0500633 auto ifaceRemovedMatch = std::make_unique<sdbusplus::bus::match_t>(
634 static_cast<sdbusplus::bus_t&>(*systemBus),
Matt Spinler20bf2c12021-09-14 11:07:07 -0500635 "type='signal',member='InterfacesRemoved',arg0path='" +
636 std::string(inventoryPath) + "/'",
Patrick Williams92f8f512022-07-22 19:26:55 -0500637 [&sensors](sdbusplus::message_t& msg) {
Ed Tanousbb679322022-05-16 16:10:00 -0700638 interfaceRemoved(msg, sensors);
Matt Spinler20bf2c12021-09-14 11:07:07 -0500639 });
640
641 matches.emplace_back(std::move(ifaceRemovedMatch));
642
James Feist6714a252018-09-10 15:26:18 -0700643 io.run();
644}