blob: e777c42d356c515e28f04081294cb64e8e952b2d [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
Zev Weissd29f8aa2022-08-03 16:24:59 -070017#include <DeviceMgmt.hpp>
Ed Tanous8a57ec02020-10-09 12:46:52 -070018#include <HwmonTempSensor.hpp>
19#include <Utils.hpp>
James Feist6714a252018-09-10 15:26:18 -070020#include <boost/algorithm/string/replace.hpp>
Patrick Venture96e97db2019-10-31 13:44:38 -070021#include <boost/container/flat_map.hpp>
James Feist6714a252018-09-10 15:26:18 -070022#include <boost/container/flat_set.hpp>
James Feist38fb5982020-05-28 10:09:54 -070023#include <sdbusplus/asio/connection.hpp>
24#include <sdbusplus/asio/object_server.hpp>
25#include <sdbusplus/bus/match.hpp>
26
27#include <array>
Jae Hyun Yoo7dd64432022-03-30 14:28:33 -070028#include <charconv>
James Feist24f02f22019-04-15 11:05:39 -070029#include <filesystem>
James Feist6714a252018-09-10 15:26:18 -070030#include <fstream>
Patrick Venture96e97db2019-10-31 13:44:38 -070031#include <functional>
32#include <memory>
James Feist6714a252018-09-10 15:26:18 -070033#include <regex>
Patrick Venture96e97db2019-10-31 13:44:38 -070034#include <stdexcept>
35#include <string>
36#include <utility>
37#include <variant>
38#include <vector>
James Feist6714a252018-09-10 15:26:18 -070039
Jeff Lin87bc67f2020-12-04 20:58:01 +080040static constexpr float pollRateDefault = 0.5;
James Feist6714a252018-09-10 15:26:18 -070041
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050042static constexpr double maxValuePressure = 120000; // Pascals
43static constexpr double minValuePressure = 30000; // Pascals
44
Bruce Mitchell3ec41c52021-12-10 16:05:17 -060045static constexpr double maxValueRelativeHumidity = 100; // PercentRH
46static constexpr double minValueRelativeHumidity = 0; // PercentRH
47
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050048static constexpr double maxValueTemperature = 127; // DegreesC
49static constexpr double minValueTemperature = -128; // DegreesC
50
James Feistcf3bce62019-01-08 10:07:19 -080051namespace fs = std::filesystem;
Zev Weissd29f8aa2022-08-03 16:24:59 -070052
53static const I2CDeviceTypeMap sensorTypes{
54 {"DPS310", I2CDeviceType{"dps310", false}},
55 {"EMC1412", I2CDeviceType{"emc1412", true}},
56 {"EMC1413", I2CDeviceType{"emc1413", true}},
57 {"EMC1414", I2CDeviceType{"emc1414", true}},
58 {"HDC1080", I2CDeviceType{"hdc1080", false}},
59 {"JC42", I2CDeviceType{"jc42", true}},
60 {"LM75A", I2CDeviceType{"lm75a", true}},
61 {"LM95234", I2CDeviceType{"lm95234", true}},
62 {"MAX31725", I2CDeviceType{"max31725", true}},
63 {"MAX31730", I2CDeviceType{"max31730", true}},
64 {"MAX6581", I2CDeviceType{"max6581", true}},
65 {"MAX6654", I2CDeviceType{"max6654", true}},
66 {"NCT6779", I2CDeviceType{"nct6779", true}},
67 {"NCT7802", I2CDeviceType{"nct7802", true}},
68 {"SBTSI", I2CDeviceType{"sbtsi", true}},
69 {"SI7020", I2CDeviceType{"si7020", false}},
Tim Lee9b0a6f62022-12-23 14:47:02 +080070 {"TMP100", I2CDeviceType{"tmp100", true}},
Zev Weissd29f8aa2022-08-03 16:24:59 -070071 {"TMP112", I2CDeviceType{"tmp112", true}},
72 {"TMP175", I2CDeviceType{"tmp175", true}},
73 {"TMP421", I2CDeviceType{"tmp421", true}},
74 {"TMP441", I2CDeviceType{"tmp441", true}},
75 {"TMP75", I2CDeviceType{"tmp75", true}},
76 {"W83773G", I2CDeviceType{"w83773g", true}},
77};
James Feist6714a252018-09-10 15:26:18 -070078
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050079static struct SensorParams
80 getSensorParameters(const std::filesystem::path& path)
81{
82 // offset is to default to 0 and scale to 1, see lore
83 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
84 struct SensorParams tmpSensorParameters = {.minValue = minValueTemperature,
85 .maxValue = maxValueTemperature,
86 .offsetValue = 0.0,
87 .scaleValue = 1.0,
Bruce Mitchell5a86e562021-12-10 12:26:22 -060088 .units =
89 sensor_paths::unitDegreesC,
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050090 .typeName = "temperature"};
91
92 // For IIO RAW sensors we get a raw_value, an offset, and scale
93 // to compute the value = (raw_value + offset) * scale
94 // with a _raw IIO device we need to get the
95 // offsetValue and scaleValue from the driver
96 // these are used to compute the reading in
97 // units that have yet to be scaled for D-Bus.
98 const std::string pathStr = path.string();
99 if (pathStr.ends_with("_raw"))
100 {
101 std::string pathOffsetStr =
102 pathStr.substr(0, pathStr.size() - 4) + "_offset";
103 std::optional<double> tmpOffsetValue = readFile(pathOffsetStr, 1.0);
104 // In case there is nothing to read skip this device
105 // This is not an error condition see lore
106 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
107 if (tmpOffsetValue)
108 {
109 tmpSensorParameters.offsetValue = *tmpOffsetValue;
110 }
111
112 std::string pathScaleStr =
113 pathStr.substr(0, pathStr.size() - 4) + "_scale";
114 std::optional<double> tmpScaleValue = readFile(pathScaleStr, 1.0);
115 // In case there is nothing to read skip this device
116 // This is not an error condition see lore
117 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
118 if (tmpScaleValue)
119 {
120 tmpSensorParameters.scaleValue = *tmpScaleValue;
121 }
122 }
123
124 // Temperatures are read in milli degrees Celsius, we need
125 // degrees Celsius. Pressures are read in kilopascal, we need
126 // Pascals. On D-Bus for Open BMC we use the International
127 // System of Units without prefixes. Links to the kernel
128 // documentation:
129 // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface
130 // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-iio
131 if (path.filename() == "in_pressure_input" ||
132 path.filename() == "in_pressure_raw")
133 {
134 tmpSensorParameters.minValue = minValuePressure;
135 tmpSensorParameters.maxValue = maxValuePressure;
136 // Pressures are read in kilopascal, we need Pascals.
137 tmpSensorParameters.scaleValue *= 1000.0;
138 tmpSensorParameters.typeName = "pressure";
Bruce Mitchell5a86e562021-12-10 12:26:22 -0600139 tmpSensorParameters.units = sensor_paths::unitPascals;
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500140 }
Bruce Mitchell3ec41c52021-12-10 16:05:17 -0600141 else if (path.filename() == "in_humidityrelative_input" ||
142 path.filename() == "in_humidityrelative_raw")
143 {
144 tmpSensorParameters.minValue = minValueRelativeHumidity;
145 tmpSensorParameters.maxValue = maxValueRelativeHumidity;
146 // Relative Humidity are read in milli-percent, we need percent.
147 tmpSensorParameters.scaleValue *= 0.001;
148 tmpSensorParameters.typeName = "humidity";
149 tmpSensorParameters.units = "PercentRH";
150 }
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500151 else
152 {
153 // Temperatures are read in milli degrees Celsius,
154 // we need degrees Celsius.
155 tmpSensorParameters.scaleValue *= 0.001;
156 }
157
158 return tmpSensorParameters;
159}
160
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530161struct SensorConfigKey
162{
163 uint64_t bus;
164 uint64_t addr;
165 bool operator<(const SensorConfigKey& other) const
166 {
167 if (bus != other.bus)
168 {
169 return bus < other.bus;
170 }
171 return addr < other.addr;
172 }
173};
174
175struct SensorConfig
176{
177 std::string sensorPath;
178 SensorData sensorData;
179 std::string interface;
180 SensorBaseConfigMap config;
181 std::vector<std::string> name;
182};
183
184using SensorConfigMap =
185 boost::container::flat_map<SensorConfigKey, SensorConfig>;
186
187static SensorConfigMap
188 buildSensorConfigMap(const ManagedObjectType& sensorConfigs)
189{
190 SensorConfigMap configMap;
Zev Weissa1808332022-08-12 18:21:01 -0700191 for (const auto& [path, cfgData] : sensorConfigs)
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530192 {
Zev Weissa1808332022-08-12 18:21:01 -0700193 for (const auto& [intf, cfg] : cfgData)
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530194 {
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530195 auto busCfg = cfg.find("Bus");
196 auto addrCfg = cfg.find("Address");
197 if ((busCfg == cfg.end()) || (addrCfg == cfg.end()))
198 {
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530199 continue;
200 }
201
Ed Tanous2049bd22022-07-09 07:20:26 -0700202 if ((std::get_if<uint64_t>(&busCfg->second) == nullptr) ||
203 (std::get_if<uint64_t>(&addrCfg->second) == nullptr))
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530204 {
Zev Weissa1808332022-08-12 18:21:01 -0700205 std::cerr << path.str << " Bus or Address invalid\n";
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530206 continue;
207 }
208
209 std::vector<std::string> hwmonNames;
210 auto nameCfg = cfg.find("Name");
211 if (nameCfg != cfg.end())
212 {
213 hwmonNames.push_back(std::get<std::string>(nameCfg->second));
214 size_t i = 1;
215 while (true)
216 {
217 auto sensorNameCfg = cfg.find("Name" + std::to_string(i));
218 if (sensorNameCfg == cfg.end())
219 {
220 break;
221 }
222 hwmonNames.push_back(
223 std::get<std::string>(sensorNameCfg->second));
224 i++;
225 }
226 }
227
228 SensorConfigKey key = {std::get<uint64_t>(busCfg->second),
229 std::get<uint64_t>(addrCfg->second)};
Zev Weissa1808332022-08-12 18:21:01 -0700230 SensorConfig val = {path.str, cfgData, intf, cfg, hwmonNames};
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530231
232 auto [it, inserted] = configMap.emplace(key, std::move(val));
233 if (!inserted)
234 {
Zev Weissa1808332022-08-12 18:21:01 -0700235 std::cerr << path.str << ": ignoring duplicate entry for {"
236 << key.bus << ", 0x" << std::hex << key.addr
237 << std::dec << "}\n";
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530238 }
239 }
240 }
241 return configMap;
242}
243
Zev Weiss7627c862022-11-17 14:23:04 -0800244// returns a {path: <I2CDevice, is_new>} map. is_new indicates if the I2CDevice
245// is newly instantiated by this call (true) or was already there (false).
246boost::container::flat_map<std::string,
247 std::pair<std::shared_ptr<I2CDevice>, bool>>
Zev Weissa1456c42022-07-18 16:59:35 -0700248 instantiateDevices(
249 const ManagedObjectType& sensorConfigs,
250 const boost::container::flat_map<
251 std::string, std::shared_ptr<HwmonTempSensor>>& sensors)
252{
Zev Weiss7627c862022-11-17 14:23:04 -0800253 boost::container::flat_map<std::string,
254 std::pair<std::shared_ptr<I2CDevice>, bool>>
255 devices;
Zev Weissa1456c42022-07-18 16:59:35 -0700256 for (const auto& [path, sensor] : sensorConfigs)
257 {
258 for (const auto& [name, cfg] : sensor)
259 {
260 PowerState powerState = getPowerState(cfg);
261 if (!readingStateGood(powerState))
262 {
263 continue;
264 }
265
266 auto findSensorName = cfg.find("Name");
267 if (findSensorName == cfg.end())
268 {
269 continue;
270 }
271 std::string sensorName =
272 std::get<std::string>(findSensorName->second);
273
274 auto findSensor = sensors.find(sensorName);
275 if (findSensor != sensors.end() && findSensor->second != nullptr &&
276 findSensor->second->isActive())
277 {
Zev Weiss7627c862022-11-17 14:23:04 -0800278 devices.emplace(
279 path.str,
280 std::make_pair(findSensor->second->getI2CDevice(), false));
Zev Weissa1456c42022-07-18 16:59:35 -0700281 continue;
282 }
283
284 std::optional<I2CDeviceParams> params =
285 getI2CDeviceParams(sensorTypes, cfg);
286 if (params.has_value() && !params->deviceStatic())
287 {
288 // There exist error cases in which a sensor device that we
289 // need is already instantiated, but needs to be destroyed and
290 // re-created in order to be useful (for example if we crash
291 // after instantiating a device and the sensor device's power
292 // is cut before we get restarted, leaving it "present" but
293 // not really usable). To be on the safe side, instantiate a
294 // temporary device that's immediately destroyed so as to
295 // ensure that we end up with a fresh instance of it.
296 if (params->devicePresent())
297 {
298 std::cerr << "Clearing out previous instance for "
299 << path.str << "\n";
300 I2CDevice tmp(*params);
301 }
302
303 try
304 {
Zev Weiss7627c862022-11-17 14:23:04 -0800305 devices.emplace(
306 path.str,
307 std::make_pair(std::make_shared<I2CDevice>(*params),
308 true));
Zev Weissa1456c42022-07-18 16:59:35 -0700309 }
310 catch (std::runtime_error&)
311 {
312 std::cerr << "Failed to instantiate " << params->type->name
313 << " at address " << params->address << " on bus "
314 << params->bus << "\n";
315 }
316 }
317 }
318 }
Zev Weiss7627c862022-11-17 14:23:04 -0800319 return devices;
Zev Weissa1456c42022-07-18 16:59:35 -0700320}
321
James Feist6714a252018-09-10 15:26:18 -0700322void createSensors(
323 boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
Yong Lif3fd1912020-03-25 21:35:23 +0800324 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
James Feist6714a252018-09-10 15:26:18 -0700325 sensors,
326 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
James Feist5591cf082020-07-15 16:44:54 -0700327 const std::shared_ptr<boost::container::flat_set<std::string>>&
Zev Weissa1456c42022-07-18 16:59:35 -0700328 sensorsChanged,
329 bool activateOnly)
James Feist6714a252018-09-10 15:26:18 -0700330{
James Feistdf515152019-09-18 16:40:40 -0700331 auto getter = std::make_shared<GetSensorConfiguration>(
332 dbusConnection,
Zev Weissa1456c42022-07-18 16:59:35 -0700333 [&io, &objectServer, &sensors, &dbusConnection, sensorsChanged,
334 activateOnly](const ManagedObjectType& sensorConfigurations) {
Ed Tanousbb679322022-05-16 16:10:00 -0700335 bool firstScan = sensorsChanged == nullptr;
James Feist6714a252018-09-10 15:26:18 -0700336
Ed Tanousbb679322022-05-16 16:10:00 -0700337 SensorConfigMap configMap = buildSensorConfigMap(sensorConfigurations);
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530338
Zev Weiss7627c862022-11-17 14:23:04 -0800339 auto devices = instantiateDevices(sensorConfigurations, sensors);
Zev Weissa1456c42022-07-18 16:59:35 -0700340
Ed Tanousbb679322022-05-16 16:10:00 -0700341 // IIO _raw devices look like this on sysfs:
342 // /sys/bus/iio/devices/iio:device0/in_temp_raw
343 // /sys/bus/iio/devices/iio:device0/in_temp_offset
344 // /sys/bus/iio/devices/iio:device0/in_temp_scale
345 //
346 // Other IIO devices look like this on sysfs:
347 // /sys/bus/iio/devices/iio:device1/in_temp_input
348 // /sys/bus/iio/devices/iio:device1/in_pressure_input
349 std::vector<fs::path> paths;
350 fs::path root("/sys/bus/iio/devices");
351 findFiles(root, R"(in_temp\d*_(input|raw))", paths);
352 findFiles(root, R"(in_pressure\d*_(input|raw))", paths);
353 findFiles(root, R"(in_humidityrelative\d*_(input|raw))", paths);
354 findFiles(fs::path("/sys/class/hwmon"), R"(temp\d+_input)", paths);
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500355
Ed Tanousbb679322022-05-16 16:10:00 -0700356 // iterate through all found temp and pressure sensors,
357 // and try to match them with configuration
358 for (auto& path : paths)
359 {
360 std::smatch match;
361 const std::string pathStr = path.string();
362 auto directory = path.parent_path();
363 fs::path device;
364
365 std::string deviceName;
366 if (pathStr.starts_with("/sys/bus/iio/devices"))
James Feist37266ca2018-10-15 15:56:28 -0700367 {
Ed Tanousbb679322022-05-16 16:10:00 -0700368 device = fs::canonical(directory);
369 deviceName = device.parent_path().stem();
370 }
371 else
372 {
373 device = directory / "device";
374 deviceName = fs::canonical(device).stem();
375 }
376 auto findHyphen = deviceName.find('-');
377 if (findHyphen == std::string::npos)
378 {
379 std::cerr << "found bad device " << deviceName << "\n";
380 continue;
381 }
382 std::string busStr = deviceName.substr(0, findHyphen);
383 std::string addrStr = deviceName.substr(findHyphen + 1);
384
385 uint64_t bus = 0;
386 uint64_t addr = 0;
Ed Tanous2049bd22022-07-09 07:20:26 -0700387 std::from_chars_result res{};
Ed Tanousbb679322022-05-16 16:10:00 -0700388 res = std::from_chars(busStr.data(), busStr.data() + busStr.size(),
389 bus);
390 if (res.ec != std::errc{})
391 {
392 continue;
393 }
394 res = std::from_chars(addrStr.data(),
395 addrStr.data() + addrStr.size(), addr, 16);
396 if (res.ec != std::errc{})
397 {
398 continue;
James Feistdf515152019-09-18 16:40:40 -0700399 }
400
Ed Tanousbb679322022-05-16 16:10:00 -0700401 auto thisSensorParameters = getSensorParameters(path);
402 auto findSensorCfg = configMap.find({bus, addr});
403 if (findSensorCfg == configMap.end())
James Feistdf515152019-09-18 16:40:40 -0700404 {
Ed Tanousbb679322022-05-16 16:10:00 -0700405 continue;
406 }
James Feistdf515152019-09-18 16:40:40 -0700407
Ed Tanousbb679322022-05-16 16:10:00 -0700408 const std::string& interfacePath = findSensorCfg->second.sensorPath;
Zev Weiss7627c862022-11-17 14:23:04 -0800409 auto findI2CDev = devices.find(interfacePath);
410
Zev Weissa1456c42022-07-18 16:59:35 -0700411 std::shared_ptr<I2CDevice> i2cDev;
Zev Weiss7627c862022-11-17 14:23:04 -0800412 if (findI2CDev != devices.end())
Zev Weissa1456c42022-07-18 16:59:35 -0700413 {
Joseph Fu9bbeff72022-12-05 19:09:16 +0800414 // If we're only looking to activate newly-instantiated i2c
415 // devices and this sensor's underlying device was already there
416 // before this call, there's nothing more to do here.
417 if (activateOnly && !findI2CDev->second.second)
418 {
419 continue;
420 }
Zev Weiss7627c862022-11-17 14:23:04 -0800421 i2cDev = findI2CDev->second.first;
Zev Weissa1456c42022-07-18 16:59:35 -0700422 }
423
Ed Tanousbb679322022-05-16 16:10:00 -0700424 const SensorData& sensorData = findSensorCfg->second.sensorData;
425 const std::string& sensorType = findSensorCfg->second.interface;
426 const SensorBaseConfigMap& baseConfigMap =
427 findSensorCfg->second.config;
428 std::vector<std::string>& hwmonName = findSensorCfg->second.name;
429
430 // Temperature has "Name", pressure has "Name1"
431 auto findSensorName = baseConfigMap.find("Name");
432 int index = 1;
433 if (thisSensorParameters.typeName == "pressure" ||
434 thisSensorParameters.typeName == "humidity")
435 {
436 findSensorName = baseConfigMap.find("Name1");
437 index = 2;
438 }
439
440 if (findSensorName == baseConfigMap.end())
441 {
442 std::cerr << "could not determine configuration name for "
443 << deviceName << "\n";
444 continue;
445 }
446 std::string sensorName =
447 std::get<std::string>(findSensorName->second);
448 // on rescans, only update sensors we were signaled by
449 auto findSensor = sensors.find(sensorName);
450 if (!firstScan && findSensor != sensors.end())
451 {
452 bool found = false;
453 auto it = sensorsChanged->begin();
454 while (it != sensorsChanged->end())
455 {
Zev Weiss6c106d62022-08-17 20:50:00 -0700456 if (it->ends_with(findSensor->second->name))
Ed Tanousbb679322022-05-16 16:10:00 -0700457 {
458 it = sensorsChanged->erase(it);
459 findSensor->second = nullptr;
460 found = true;
461 break;
462 }
463 ++it;
464 }
465 if (!found)
466 {
467 continue;
468 }
469 }
470
471 std::vector<thresholds::Threshold> sensorThresholds;
472
473 if (!parseThresholdsFromConfig(sensorData, sensorThresholds,
474 nullptr, &index))
475 {
476 std::cerr << "error populating thresholds for " << sensorName
477 << " index " << index << "\n";
478 }
479
Zev Weiss8569bf22022-10-11 15:37:44 -0700480 float pollRate = getPollRate(baseConfigMap, pollRateDefault);
Zev Weissa4d27682022-07-19 15:30:36 -0700481 PowerState readState = getPowerState(baseConfigMap);
Ed Tanousbb679322022-05-16 16:10:00 -0700482
483 auto permitSet = getPermitSet(baseConfigMap);
484 auto& sensor = sensors[sensorName];
Zev Weissa1456c42022-07-18 16:59:35 -0700485 if (!activateOnly)
486 {
487 sensor = nullptr;
488 }
Ed Tanousbb679322022-05-16 16:10:00 -0700489 auto hwmonFile =
490 getFullHwmonFilePath(directory.string(), "temp1", permitSet);
491 if (pathStr.starts_with("/sys/bus/iio/devices"))
492 {
493 hwmonFile = pathStr;
494 }
495 if (hwmonFile)
496 {
Zev Weissa1456c42022-07-18 16:59:35 -0700497 if (sensor != nullptr)
498 {
499 sensor->activate(*hwmonFile, i2cDev);
500 }
501 else
502 {
503 sensor = std::make_shared<HwmonTempSensor>(
504 *hwmonFile, sensorType, objectServer, dbusConnection,
505 io, sensorName, std::move(sensorThresholds),
506 thisSensorParameters, pollRate, interfacePath,
507 readState, i2cDev);
508 sensor->setupRead();
509 }
Ed Tanousbb679322022-05-16 16:10:00 -0700510 }
511 hwmonName.erase(
512 remove(hwmonName.begin(), hwmonName.end(), sensorName),
513 hwmonName.end());
514
515 // Looking for keys like "Name1" for temp2_input,
516 // "Name2" for temp3_input, etc.
517 int i = 0;
518 while (true)
519 {
520 ++i;
521 auto findKey = baseConfigMap.find("Name" + std::to_string(i));
522 if (findKey == baseConfigMap.end())
523 {
524 break;
525 }
526 std::string sensorName = std::get<std::string>(findKey->second);
527 hwmonFile = getFullHwmonFilePath(directory.string(),
528 "temp" + std::to_string(i + 1),
529 permitSet);
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500530 if (pathStr.starts_with("/sys/bus/iio/devices"))
James Feist37266ca2018-10-15 15:56:28 -0700531 {
James Feistdf515152019-09-18 16:40:40 -0700532 continue;
533 }
Jason Ling100c20b2020-08-11 14:50:33 -0700534 if (hwmonFile)
535 {
Ed Tanousbb679322022-05-16 16:10:00 -0700536 // To look up thresholds for these additional sensors,
537 // match on the Index property in the threshold data
538 // where the index comes from the sysfs file we're on,
539 // i.e. index = 2 for temp2_input.
540 int index = i + 1;
541 std::vector<thresholds::Threshold> thresholds;
542
543 if (!parseThresholdsFromConfig(sensorData, thresholds,
544 nullptr, &index))
545 {
546 std::cerr << "error populating thresholds for "
547 << sensorName << " index " << index << "\n";
548 }
549
550 auto& sensor = sensors[sensorName];
Zev Weissa1456c42022-07-18 16:59:35 -0700551 if (!activateOnly)
552 {
553 sensor = nullptr;
554 }
555
556 if (sensor != nullptr)
557 {
558 sensor->activate(*hwmonFile, i2cDev);
559 }
560 else
561 {
562 sensor = std::make_shared<HwmonTempSensor>(
563 *hwmonFile, sensorType, objectServer,
564 dbusConnection, io, sensorName,
565 std::move(thresholds), thisSensorParameters,
566 pollRate, interfacePath, readState, i2cDev);
567 sensor->setupRead();
568 }
Jason Ling100c20b2020-08-11 14:50:33 -0700569 }
Ed Tanousbb679322022-05-16 16:10:00 -0700570
Willy Tu9eb0cc32022-04-06 11:03:32 -0700571 hwmonName.erase(
572 remove(hwmonName.begin(), hwmonName.end(), sensorName),
573 hwmonName.end());
James Feistdf515152019-09-18 16:40:40 -0700574 }
Ed Tanousbb679322022-05-16 16:10:00 -0700575 if (hwmonName.empty())
576 {
577 configMap.erase(findSensorCfg);
578 }
579 }
Ed Tanous8a17c302021-09-02 15:07:11 -0700580 });
Zev Weissd29f8aa2022-08-03 16:24:59 -0700581 std::vector<std::string> types(sensorTypes.size());
582 for (const auto& [type, dt] : sensorTypes)
583 {
584 types.push_back(type);
585 }
586 getter->getConfiguration(types);
James Feist6714a252018-09-10 15:26:18 -0700587}
588
Matt Spinler20bf2c12021-09-14 11:07:07 -0500589void interfaceRemoved(
Patrick Williams92f8f512022-07-22 19:26:55 -0500590 sdbusplus::message_t& message,
Matt Spinler20bf2c12021-09-14 11:07:07 -0500591 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
592 sensors)
593{
594 if (message.is_method_error())
595 {
596 std::cerr << "interfacesRemoved callback method error\n";
597 return;
598 }
599
600 sdbusplus::message::object_path path;
601 std::vector<std::string> interfaces;
602
603 message.read(path, interfaces);
604
605 // If the xyz.openbmc_project.Confguration.X interface was removed
606 // for one or more sensors, delete those sensor objects.
607 auto sensorIt = sensors.begin();
608 while (sensorIt != sensors.end())
609 {
610 if ((sensorIt->second->configurationPath == path) &&
611 (std::find(interfaces.begin(), interfaces.end(),
612 sensorIt->second->objectType) != interfaces.end()))
613 {
614 sensorIt = sensors.erase(sensorIt);
615 }
616 else
617 {
618 sensorIt++;
619 }
620 }
621}
622
Zev Weissa1456c42022-07-18 16:59:35 -0700623static void powerStateChanged(
624 PowerState type, bool newState,
625 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
626 sensors,
627 boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
628 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
629{
630 if (newState)
631 {
632 createSensors(io, objectServer, sensors, dbusConnection, nullptr, true);
633 }
634 else
635 {
636 for (auto& [path, sensor] : sensors)
637 {
638 if (sensor != nullptr && sensor->readState == type)
639 {
640 sensor->deactivate();
641 }
642 }
643 }
644}
645
James Feistb6c0b912019-07-09 12:21:44 -0700646int main()
James Feist6714a252018-09-10 15:26:18 -0700647{
648 boost::asio::io_service io;
649 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
Ed Tanous14ed5e92022-07-12 15:50:23 -0700650 sdbusplus::asio::object_server objectServer(systemBus, true);
651 objectServer.add_manager("/xyz/openbmc_project/sensors");
James Feist6714a252018-09-10 15:26:18 -0700652 systemBus->request_name("xyz.openbmc_project.HwmonTempSensor");
Ed Tanous14ed5e92022-07-12 15:50:23 -0700653
Yong Lif3fd1912020-03-25 21:35:23 +0800654 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>
James Feist6714a252018-09-10 15:26:18 -0700655 sensors;
James Feist5591cf082020-07-15 16:44:54 -0700656 auto sensorsChanged =
657 std::make_shared<boost::container::flat_set<std::string>>();
James Feist6714a252018-09-10 15:26:18 -0700658
Zev Weissa1456c42022-07-18 16:59:35 -0700659 auto powerCallBack = [&sensors, &io, &objectServer,
660 &systemBus](PowerState type, bool state) {
661 powerStateChanged(type, state, sensors, io, objectServer, systemBus);
662 };
663 setupPowerMatchCallback(systemBus, powerCallBack);
664
James Feist6714a252018-09-10 15:26:18 -0700665 io.post([&]() {
Zev Weissa1456c42022-07-18 16:59:35 -0700666 createSensors(io, objectServer, sensors, systemBus, nullptr, false);
James Feist6714a252018-09-10 15:26:18 -0700667 });
668
Ed Tanous9b4a20e2022-09-06 08:47:11 -0700669 boost::asio::steady_timer filterTimer(io);
Patrick Williams92f8f512022-07-22 19:26:55 -0500670 std::function<void(sdbusplus::message_t&)> eventHandler =
671 [&](sdbusplus::message_t& message) {
Ed Tanousbb679322022-05-16 16:10:00 -0700672 if (message.is_method_error())
673 {
674 std::cerr << "callback method error\n";
675 return;
676 }
677 sensorsChanged->insert(message.get_path());
678 // this implicitly cancels the timer
Ed Tanous9b4a20e2022-09-06 08:47:11 -0700679 filterTimer.expires_from_now(std::chrono::seconds(1));
Ed Tanousbb679322022-05-16 16:10:00 -0700680
681 filterTimer.async_wait([&](const boost::system::error_code& ec) {
682 if (ec == boost::asio::error::operation_aborted)
James Feist6714a252018-09-10 15:26:18 -0700683 {
Ed Tanousbb679322022-05-16 16:10:00 -0700684 /* we were canceled*/
James Feist6714a252018-09-10 15:26:18 -0700685 return;
686 }
Ed Tanousbb679322022-05-16 16:10:00 -0700687 if (ec)
688 {
689 std::cerr << "timer error\n";
690 return;
691 }
Zev Weissa1456c42022-07-18 16:59:35 -0700692 createSensors(io, objectServer, sensors, systemBus, sensorsChanged,
693 false);
Ed Tanousbb679322022-05-16 16:10:00 -0700694 });
695 };
James Feist6714a252018-09-10 15:26:18 -0700696
Zev Weiss214d9712022-08-12 12:54:31 -0700697 std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
698 setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
Bruce Lee1263c3d2021-06-04 15:16:33 +0800699 setupManufacturingModeMatch(*systemBus);
Matt Spinler20bf2c12021-09-14 11:07:07 -0500700
701 // Watch for entity-manager to remove configuration interfaces
702 // so the corresponding sensors can be removed.
Patrick Williams92f8f512022-07-22 19:26:55 -0500703 auto ifaceRemovedMatch = std::make_unique<sdbusplus::bus::match_t>(
704 static_cast<sdbusplus::bus_t&>(*systemBus),
Matt Spinler20bf2c12021-09-14 11:07:07 -0500705 "type='signal',member='InterfacesRemoved',arg0path='" +
706 std::string(inventoryPath) + "/'",
Patrick Williams92f8f512022-07-22 19:26:55 -0500707 [&sensors](sdbusplus::message_t& msg) {
Ed Tanousbb679322022-05-16 16:10:00 -0700708 interfaceRemoved(msg, sensors);
Matt Spinler20bf2c12021-09-14 11:07:07 -0500709 });
710
711 matches.emplace_back(std::move(ifaceRemovedMatch));
712
James Feist6714a252018-09-10 15:26:18 -0700713 io.run();
714}