blob: 27b28d5c9200460ee29cda0ae731bae5ce306336 [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}},
70 {"TMP112", I2CDeviceType{"tmp112", true}},
71 {"TMP175", I2CDeviceType{"tmp175", true}},
72 {"TMP421", I2CDeviceType{"tmp421", true}},
73 {"TMP441", I2CDeviceType{"tmp441", true}},
74 {"TMP75", I2CDeviceType{"tmp75", true}},
75 {"W83773G", I2CDeviceType{"w83773g", true}},
76};
James Feist6714a252018-09-10 15:26:18 -070077
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050078static struct SensorParams
79 getSensorParameters(const std::filesystem::path& path)
80{
81 // offset is to default to 0 and scale to 1, see lore
82 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
83 struct SensorParams tmpSensorParameters = {.minValue = minValueTemperature,
84 .maxValue = maxValueTemperature,
85 .offsetValue = 0.0,
86 .scaleValue = 1.0,
Bruce Mitchell5a86e562021-12-10 12:26:22 -060087 .units =
88 sensor_paths::unitDegreesC,
Bruce Mitchell544e7dc2021-07-29 18:05:49 -050089 .typeName = "temperature"};
90
91 // For IIO RAW sensors we get a raw_value, an offset, and scale
92 // to compute the value = (raw_value + offset) * scale
93 // with a _raw IIO device we need to get the
94 // offsetValue and scaleValue from the driver
95 // these are used to compute the reading in
96 // units that have yet to be scaled for D-Bus.
97 const std::string pathStr = path.string();
98 if (pathStr.ends_with("_raw"))
99 {
100 std::string pathOffsetStr =
101 pathStr.substr(0, pathStr.size() - 4) + "_offset";
102 std::optional<double> tmpOffsetValue = readFile(pathOffsetStr, 1.0);
103 // In case there is nothing to read skip this device
104 // This is not an error condition see lore
105 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
106 if (tmpOffsetValue)
107 {
108 tmpSensorParameters.offsetValue = *tmpOffsetValue;
109 }
110
111 std::string pathScaleStr =
112 pathStr.substr(0, pathStr.size() - 4) + "_scale";
113 std::optional<double> tmpScaleValue = readFile(pathScaleStr, 1.0);
114 // In case there is nothing to read skip this device
115 // This is not an error condition see lore
116 // https://lore.kernel.org/linux-iio/5c79425f-6e88-36b6-cdfe-4080738d039f@metafoo.de/
117 if (tmpScaleValue)
118 {
119 tmpSensorParameters.scaleValue = *tmpScaleValue;
120 }
121 }
122
123 // Temperatures are read in milli degrees Celsius, we need
124 // degrees Celsius. Pressures are read in kilopascal, we need
125 // Pascals. On D-Bus for Open BMC we use the International
126 // System of Units without prefixes. Links to the kernel
127 // documentation:
128 // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface
129 // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-iio
130 if (path.filename() == "in_pressure_input" ||
131 path.filename() == "in_pressure_raw")
132 {
133 tmpSensorParameters.minValue = minValuePressure;
134 tmpSensorParameters.maxValue = maxValuePressure;
135 // Pressures are read in kilopascal, we need Pascals.
136 tmpSensorParameters.scaleValue *= 1000.0;
137 tmpSensorParameters.typeName = "pressure";
Bruce Mitchell5a86e562021-12-10 12:26:22 -0600138 tmpSensorParameters.units = sensor_paths::unitPascals;
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500139 }
Bruce Mitchell3ec41c52021-12-10 16:05:17 -0600140 else if (path.filename() == "in_humidityrelative_input" ||
141 path.filename() == "in_humidityrelative_raw")
142 {
143 tmpSensorParameters.minValue = minValueRelativeHumidity;
144 tmpSensorParameters.maxValue = maxValueRelativeHumidity;
145 // Relative Humidity are read in milli-percent, we need percent.
146 tmpSensorParameters.scaleValue *= 0.001;
147 tmpSensorParameters.typeName = "humidity";
148 tmpSensorParameters.units = "PercentRH";
149 }
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500150 else
151 {
152 // Temperatures are read in milli degrees Celsius,
153 // we need degrees Celsius.
154 tmpSensorParameters.scaleValue *= 0.001;
155 }
156
157 return tmpSensorParameters;
158}
159
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530160struct SensorConfigKey
161{
162 uint64_t bus;
163 uint64_t addr;
164 bool operator<(const SensorConfigKey& other) const
165 {
166 if (bus != other.bus)
167 {
168 return bus < other.bus;
169 }
170 return addr < other.addr;
171 }
172};
173
174struct SensorConfig
175{
176 std::string sensorPath;
177 SensorData sensorData;
178 std::string interface;
179 SensorBaseConfigMap config;
180 std::vector<std::string> name;
181};
182
183using SensorConfigMap =
184 boost::container::flat_map<SensorConfigKey, SensorConfig>;
185
186static SensorConfigMap
187 buildSensorConfigMap(const ManagedObjectType& sensorConfigs)
188{
189 SensorConfigMap configMap;
Zev Weissa1808332022-08-12 18:21:01 -0700190 for (const auto& [path, cfgData] : sensorConfigs)
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530191 {
Zev Weissa1808332022-08-12 18:21:01 -0700192 for (const auto& [intf, cfg] : cfgData)
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530193 {
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530194 auto busCfg = cfg.find("Bus");
195 auto addrCfg = cfg.find("Address");
196 if ((busCfg == cfg.end()) || (addrCfg == cfg.end()))
197 {
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530198 continue;
199 }
200
Ed Tanous2049bd22022-07-09 07:20:26 -0700201 if ((std::get_if<uint64_t>(&busCfg->second) == nullptr) ||
202 (std::get_if<uint64_t>(&addrCfg->second) == nullptr))
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530203 {
Zev Weissa1808332022-08-12 18:21:01 -0700204 std::cerr << path.str << " Bus or Address invalid\n";
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530205 continue;
206 }
207
208 std::vector<std::string> hwmonNames;
209 auto nameCfg = cfg.find("Name");
210 if (nameCfg != cfg.end())
211 {
212 hwmonNames.push_back(std::get<std::string>(nameCfg->second));
213 size_t i = 1;
214 while (true)
215 {
216 auto sensorNameCfg = cfg.find("Name" + std::to_string(i));
217 if (sensorNameCfg == cfg.end())
218 {
219 break;
220 }
221 hwmonNames.push_back(
222 std::get<std::string>(sensorNameCfg->second));
223 i++;
224 }
225 }
226
227 SensorConfigKey key = {std::get<uint64_t>(busCfg->second),
228 std::get<uint64_t>(addrCfg->second)};
Zev Weissa1808332022-08-12 18:21:01 -0700229 SensorConfig val = {path.str, cfgData, intf, cfg, hwmonNames};
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530230
231 auto [it, inserted] = configMap.emplace(key, std::move(val));
232 if (!inserted)
233 {
Zev Weissa1808332022-08-12 18:21:01 -0700234 std::cerr << path.str << ": ignoring duplicate entry for {"
235 << key.bus << ", 0x" << std::hex << key.addr
236 << std::dec << "}\n";
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530237 }
238 }
239 }
240 return configMap;
241}
242
Zev Weiss7627c862022-11-17 14:23:04 -0800243// returns a {path: <I2CDevice, is_new>} map. is_new indicates if the I2CDevice
244// is newly instantiated by this call (true) or was already there (false).
245boost::container::flat_map<std::string,
246 std::pair<std::shared_ptr<I2CDevice>, bool>>
Zev Weissa1456c42022-07-18 16:59:35 -0700247 instantiateDevices(
248 const ManagedObjectType& sensorConfigs,
249 const boost::container::flat_map<
250 std::string, std::shared_ptr<HwmonTempSensor>>& sensors)
251{
Zev Weiss7627c862022-11-17 14:23:04 -0800252 boost::container::flat_map<std::string,
253 std::pair<std::shared_ptr<I2CDevice>, bool>>
254 devices;
Zev Weissa1456c42022-07-18 16:59:35 -0700255 for (const auto& [path, sensor] : sensorConfigs)
256 {
257 for (const auto& [name, cfg] : sensor)
258 {
259 PowerState powerState = getPowerState(cfg);
260 if (!readingStateGood(powerState))
261 {
262 continue;
263 }
264
265 auto findSensorName = cfg.find("Name");
266 if (findSensorName == cfg.end())
267 {
268 continue;
269 }
270 std::string sensorName =
271 std::get<std::string>(findSensorName->second);
272
273 auto findSensor = sensors.find(sensorName);
274 if (findSensor != sensors.end() && findSensor->second != nullptr &&
275 findSensor->second->isActive())
276 {
Zev Weiss7627c862022-11-17 14:23:04 -0800277 devices.emplace(
278 path.str,
279 std::make_pair(findSensor->second->getI2CDevice(), false));
Zev Weissa1456c42022-07-18 16:59:35 -0700280 continue;
281 }
282
283 std::optional<I2CDeviceParams> params =
284 getI2CDeviceParams(sensorTypes, cfg);
285 if (params.has_value() && !params->deviceStatic())
286 {
287 // There exist error cases in which a sensor device that we
288 // need is already instantiated, but needs to be destroyed and
289 // re-created in order to be useful (for example if we crash
290 // after instantiating a device and the sensor device's power
291 // is cut before we get restarted, leaving it "present" but
292 // not really usable). To be on the safe side, instantiate a
293 // temporary device that's immediately destroyed so as to
294 // ensure that we end up with a fresh instance of it.
295 if (params->devicePresent())
296 {
297 std::cerr << "Clearing out previous instance for "
298 << path.str << "\n";
299 I2CDevice tmp(*params);
300 }
301
302 try
303 {
Zev Weiss7627c862022-11-17 14:23:04 -0800304 devices.emplace(
305 path.str,
306 std::make_pair(std::make_shared<I2CDevice>(*params),
307 true));
Zev Weissa1456c42022-07-18 16:59:35 -0700308 }
309 catch (std::runtime_error&)
310 {
311 std::cerr << "Failed to instantiate " << params->type->name
312 << " at address " << params->address << " on bus "
313 << params->bus << "\n";
314 }
315 }
316 }
317 }
Zev Weiss7627c862022-11-17 14:23:04 -0800318 return devices;
Zev Weissa1456c42022-07-18 16:59:35 -0700319}
320
James Feist6714a252018-09-10 15:26:18 -0700321void createSensors(
322 boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
Yong Lif3fd1912020-03-25 21:35:23 +0800323 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
James Feist6714a252018-09-10 15:26:18 -0700324 sensors,
325 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
James Feist5591cf082020-07-15 16:44:54 -0700326 const std::shared_ptr<boost::container::flat_set<std::string>>&
Zev Weissa1456c42022-07-18 16:59:35 -0700327 sensorsChanged,
328 bool activateOnly)
James Feist6714a252018-09-10 15:26:18 -0700329{
James Feistdf515152019-09-18 16:40:40 -0700330 auto getter = std::make_shared<GetSensorConfiguration>(
331 dbusConnection,
Zev Weissa1456c42022-07-18 16:59:35 -0700332 [&io, &objectServer, &sensors, &dbusConnection, sensorsChanged,
333 activateOnly](const ManagedObjectType& sensorConfigurations) {
Ed Tanousbb679322022-05-16 16:10:00 -0700334 bool firstScan = sensorsChanged == nullptr;
James Feist6714a252018-09-10 15:26:18 -0700335
Ed Tanousbb679322022-05-16 16:10:00 -0700336 SensorConfigMap configMap = buildSensorConfigMap(sensorConfigurations);
Jayashree Dhanapal9f3a74e2022-01-06 12:05:06 +0530337
Zev Weiss7627c862022-11-17 14:23:04 -0800338 auto devices = instantiateDevices(sensorConfigurations, sensors);
Zev Weissa1456c42022-07-18 16:59:35 -0700339
Ed Tanousbb679322022-05-16 16:10:00 -0700340 // IIO _raw devices look like this on sysfs:
341 // /sys/bus/iio/devices/iio:device0/in_temp_raw
342 // /sys/bus/iio/devices/iio:device0/in_temp_offset
343 // /sys/bus/iio/devices/iio:device0/in_temp_scale
344 //
345 // Other IIO devices look like this on sysfs:
346 // /sys/bus/iio/devices/iio:device1/in_temp_input
347 // /sys/bus/iio/devices/iio:device1/in_pressure_input
348 std::vector<fs::path> paths;
349 fs::path root("/sys/bus/iio/devices");
350 findFiles(root, R"(in_temp\d*_(input|raw))", paths);
351 findFiles(root, R"(in_pressure\d*_(input|raw))", paths);
352 findFiles(root, R"(in_humidityrelative\d*_(input|raw))", paths);
353 findFiles(fs::path("/sys/class/hwmon"), R"(temp\d+_input)", paths);
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500354
Ed Tanousbb679322022-05-16 16:10:00 -0700355 // iterate through all found temp and pressure sensors,
356 // and try to match them with configuration
357 for (auto& path : paths)
358 {
359 std::smatch match;
360 const std::string pathStr = path.string();
361 auto directory = path.parent_path();
362 fs::path device;
363
364 std::string deviceName;
365 if (pathStr.starts_with("/sys/bus/iio/devices"))
James Feist37266ca2018-10-15 15:56:28 -0700366 {
Ed Tanousbb679322022-05-16 16:10:00 -0700367 device = fs::canonical(directory);
368 deviceName = device.parent_path().stem();
369 }
370 else
371 {
372 device = directory / "device";
373 deviceName = fs::canonical(device).stem();
374 }
375 auto findHyphen = deviceName.find('-');
376 if (findHyphen == std::string::npos)
377 {
378 std::cerr << "found bad device " << deviceName << "\n";
379 continue;
380 }
381 std::string busStr = deviceName.substr(0, findHyphen);
382 std::string addrStr = deviceName.substr(findHyphen + 1);
383
384 uint64_t bus = 0;
385 uint64_t addr = 0;
Ed Tanous2049bd22022-07-09 07:20:26 -0700386 std::from_chars_result res{};
Ed Tanousbb679322022-05-16 16:10:00 -0700387 res = std::from_chars(busStr.data(), busStr.data() + busStr.size(),
388 bus);
389 if (res.ec != std::errc{})
390 {
391 continue;
392 }
393 res = std::from_chars(addrStr.data(),
394 addrStr.data() + addrStr.size(), addr, 16);
395 if (res.ec != std::errc{})
396 {
397 continue;
James Feistdf515152019-09-18 16:40:40 -0700398 }
399
Ed Tanousbb679322022-05-16 16:10:00 -0700400 auto thisSensorParameters = getSensorParameters(path);
401 auto findSensorCfg = configMap.find({bus, addr});
402 if (findSensorCfg == configMap.end())
James Feistdf515152019-09-18 16:40:40 -0700403 {
Ed Tanousbb679322022-05-16 16:10:00 -0700404 continue;
405 }
James Feistdf515152019-09-18 16:40:40 -0700406
Ed Tanousbb679322022-05-16 16:10:00 -0700407 const std::string& interfacePath = findSensorCfg->second.sensorPath;
Zev Weiss7627c862022-11-17 14:23:04 -0800408 auto findI2CDev = devices.find(interfacePath);
409
410 // If we're only looking to activate newly-instantiated i2c
411 // devices and this sensor's underlying device either (a) wasn't
412 // found (e.g. because it's a static device and not a dynamic one
413 // whose lifetime we're managing) or (b) was already there before
414 // this call, there's nothing more to do here.
415 if (activateOnly &&
416 (findI2CDev == devices.end() || !findI2CDev->second.second))
Zev Weissa1456c42022-07-18 16:59:35 -0700417 {
418 continue;
419 }
420
421 std::shared_ptr<I2CDevice> i2cDev;
Zev Weiss7627c862022-11-17 14:23:04 -0800422 if (findI2CDev != devices.end())
Zev Weissa1456c42022-07-18 16:59:35 -0700423 {
Zev Weiss7627c862022-11-17 14:23:04 -0800424 i2cDev = findI2CDev->second.first;
Zev Weissa1456c42022-07-18 16:59:35 -0700425 }
426
Ed Tanousbb679322022-05-16 16:10:00 -0700427 const SensorData& sensorData = findSensorCfg->second.sensorData;
428 const std::string& sensorType = findSensorCfg->second.interface;
429 const SensorBaseConfigMap& baseConfigMap =
430 findSensorCfg->second.config;
431 std::vector<std::string>& hwmonName = findSensorCfg->second.name;
432
433 // Temperature has "Name", pressure has "Name1"
434 auto findSensorName = baseConfigMap.find("Name");
435 int index = 1;
436 if (thisSensorParameters.typeName == "pressure" ||
437 thisSensorParameters.typeName == "humidity")
438 {
439 findSensorName = baseConfigMap.find("Name1");
440 index = 2;
441 }
442
443 if (findSensorName == baseConfigMap.end())
444 {
445 std::cerr << "could not determine configuration name for "
446 << deviceName << "\n";
447 continue;
448 }
449 std::string sensorName =
450 std::get<std::string>(findSensorName->second);
451 // on rescans, only update sensors we were signaled by
452 auto findSensor = sensors.find(sensorName);
453 if (!firstScan && findSensor != sensors.end())
454 {
455 bool found = false;
456 auto it = sensorsChanged->begin();
457 while (it != sensorsChanged->end())
458 {
Zev Weiss6c106d62022-08-17 20:50:00 -0700459 if (it->ends_with(findSensor->second->name))
Ed Tanousbb679322022-05-16 16:10:00 -0700460 {
461 it = sensorsChanged->erase(it);
462 findSensor->second = nullptr;
463 found = true;
464 break;
465 }
466 ++it;
467 }
468 if (!found)
469 {
470 continue;
471 }
472 }
473
474 std::vector<thresholds::Threshold> sensorThresholds;
475
476 if (!parseThresholdsFromConfig(sensorData, sensorThresholds,
477 nullptr, &index))
478 {
479 std::cerr << "error populating thresholds for " << sensorName
480 << " index " << index << "\n";
481 }
482
Zev Weiss8569bf22022-10-11 15:37:44 -0700483 float pollRate = getPollRate(baseConfigMap, pollRateDefault);
Zev Weissa4d27682022-07-19 15:30:36 -0700484 PowerState readState = getPowerState(baseConfigMap);
Ed Tanousbb679322022-05-16 16:10:00 -0700485
486 auto permitSet = getPermitSet(baseConfigMap);
487 auto& sensor = sensors[sensorName];
Zev Weissa1456c42022-07-18 16:59:35 -0700488 if (!activateOnly)
489 {
490 sensor = nullptr;
491 }
Ed Tanousbb679322022-05-16 16:10:00 -0700492 auto hwmonFile =
493 getFullHwmonFilePath(directory.string(), "temp1", permitSet);
494 if (pathStr.starts_with("/sys/bus/iio/devices"))
495 {
496 hwmonFile = pathStr;
497 }
498 if (hwmonFile)
499 {
Zev Weissa1456c42022-07-18 16:59:35 -0700500 if (sensor != nullptr)
501 {
502 sensor->activate(*hwmonFile, i2cDev);
503 }
504 else
505 {
506 sensor = std::make_shared<HwmonTempSensor>(
507 *hwmonFile, sensorType, objectServer, dbusConnection,
508 io, sensorName, std::move(sensorThresholds),
509 thisSensorParameters, pollRate, interfacePath,
510 readState, i2cDev);
511 sensor->setupRead();
512 }
Ed Tanousbb679322022-05-16 16:10:00 -0700513 }
514 hwmonName.erase(
515 remove(hwmonName.begin(), hwmonName.end(), sensorName),
516 hwmonName.end());
517
518 // Looking for keys like "Name1" for temp2_input,
519 // "Name2" for temp3_input, etc.
520 int i = 0;
521 while (true)
522 {
523 ++i;
524 auto findKey = baseConfigMap.find("Name" + std::to_string(i));
525 if (findKey == baseConfigMap.end())
526 {
527 break;
528 }
529 std::string sensorName = std::get<std::string>(findKey->second);
530 hwmonFile = getFullHwmonFilePath(directory.string(),
531 "temp" + std::to_string(i + 1),
532 permitSet);
Bruce Mitchell544e7dc2021-07-29 18:05:49 -0500533 if (pathStr.starts_with("/sys/bus/iio/devices"))
James Feist37266ca2018-10-15 15:56:28 -0700534 {
James Feistdf515152019-09-18 16:40:40 -0700535 continue;
536 }
Jason Ling100c20b2020-08-11 14:50:33 -0700537 if (hwmonFile)
538 {
Ed Tanousbb679322022-05-16 16:10:00 -0700539 // To look up thresholds for these additional sensors,
540 // match on the Index property in the threshold data
541 // where the index comes from the sysfs file we're on,
542 // i.e. index = 2 for temp2_input.
543 int index = i + 1;
544 std::vector<thresholds::Threshold> thresholds;
545
546 if (!parseThresholdsFromConfig(sensorData, thresholds,
547 nullptr, &index))
548 {
549 std::cerr << "error populating thresholds for "
550 << sensorName << " index " << index << "\n";
551 }
552
553 auto& sensor = sensors[sensorName];
Zev Weissa1456c42022-07-18 16:59:35 -0700554 if (!activateOnly)
555 {
556 sensor = nullptr;
557 }
558
559 if (sensor != nullptr)
560 {
561 sensor->activate(*hwmonFile, i2cDev);
562 }
563 else
564 {
565 sensor = std::make_shared<HwmonTempSensor>(
566 *hwmonFile, sensorType, objectServer,
567 dbusConnection, io, sensorName,
568 std::move(thresholds), thisSensorParameters,
569 pollRate, interfacePath, readState, i2cDev);
570 sensor->setupRead();
571 }
Jason Ling100c20b2020-08-11 14:50:33 -0700572 }
Ed Tanousbb679322022-05-16 16:10:00 -0700573
Willy Tu9eb0cc32022-04-06 11:03:32 -0700574 hwmonName.erase(
575 remove(hwmonName.begin(), hwmonName.end(), sensorName),
576 hwmonName.end());
James Feistdf515152019-09-18 16:40:40 -0700577 }
Ed Tanousbb679322022-05-16 16:10:00 -0700578 if (hwmonName.empty())
579 {
580 configMap.erase(findSensorCfg);
581 }
582 }
Ed Tanous8a17c302021-09-02 15:07:11 -0700583 });
Zev Weissd29f8aa2022-08-03 16:24:59 -0700584 std::vector<std::string> types(sensorTypes.size());
585 for (const auto& [type, dt] : sensorTypes)
586 {
587 types.push_back(type);
588 }
589 getter->getConfiguration(types);
James Feist6714a252018-09-10 15:26:18 -0700590}
591
Matt Spinler20bf2c12021-09-14 11:07:07 -0500592void interfaceRemoved(
Patrick Williams92f8f512022-07-22 19:26:55 -0500593 sdbusplus::message_t& message,
Matt Spinler20bf2c12021-09-14 11:07:07 -0500594 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
595 sensors)
596{
597 if (message.is_method_error())
598 {
599 std::cerr << "interfacesRemoved callback method error\n";
600 return;
601 }
602
603 sdbusplus::message::object_path path;
604 std::vector<std::string> interfaces;
605
606 message.read(path, interfaces);
607
608 // If the xyz.openbmc_project.Confguration.X interface was removed
609 // for one or more sensors, delete those sensor objects.
610 auto sensorIt = sensors.begin();
611 while (sensorIt != sensors.end())
612 {
613 if ((sensorIt->second->configurationPath == path) &&
614 (std::find(interfaces.begin(), interfaces.end(),
615 sensorIt->second->objectType) != interfaces.end()))
616 {
617 sensorIt = sensors.erase(sensorIt);
618 }
619 else
620 {
621 sensorIt++;
622 }
623 }
624}
625
Zev Weissa1456c42022-07-18 16:59:35 -0700626static void powerStateChanged(
627 PowerState type, bool newState,
628 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>&
629 sensors,
630 boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
631 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
632{
633 if (newState)
634 {
635 createSensors(io, objectServer, sensors, dbusConnection, nullptr, true);
636 }
637 else
638 {
639 for (auto& [path, sensor] : sensors)
640 {
641 if (sensor != nullptr && sensor->readState == type)
642 {
643 sensor->deactivate();
644 }
645 }
646 }
647}
648
James Feistb6c0b912019-07-09 12:21:44 -0700649int main()
James Feist6714a252018-09-10 15:26:18 -0700650{
651 boost::asio::io_service io;
652 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
Ed Tanous14ed5e92022-07-12 15:50:23 -0700653 sdbusplus::asio::object_server objectServer(systemBus, true);
654 objectServer.add_manager("/xyz/openbmc_project/sensors");
James Feist6714a252018-09-10 15:26:18 -0700655 systemBus->request_name("xyz.openbmc_project.HwmonTempSensor");
Ed Tanous14ed5e92022-07-12 15:50:23 -0700656
Yong Lif3fd1912020-03-25 21:35:23 +0800657 boost::container::flat_map<std::string, std::shared_ptr<HwmonTempSensor>>
James Feist6714a252018-09-10 15:26:18 -0700658 sensors;
James Feist5591cf082020-07-15 16:44:54 -0700659 auto sensorsChanged =
660 std::make_shared<boost::container::flat_set<std::string>>();
James Feist6714a252018-09-10 15:26:18 -0700661
Zev Weissa1456c42022-07-18 16:59:35 -0700662 auto powerCallBack = [&sensors, &io, &objectServer,
663 &systemBus](PowerState type, bool state) {
664 powerStateChanged(type, state, sensors, io, objectServer, systemBus);
665 };
666 setupPowerMatchCallback(systemBus, powerCallBack);
667
James Feist6714a252018-09-10 15:26:18 -0700668 io.post([&]() {
Zev Weissa1456c42022-07-18 16:59:35 -0700669 createSensors(io, objectServer, sensors, systemBus, nullptr, false);
James Feist6714a252018-09-10 15:26:18 -0700670 });
671
Ed Tanous9b4a20e2022-09-06 08:47:11 -0700672 boost::asio::steady_timer filterTimer(io);
Patrick Williams92f8f512022-07-22 19:26:55 -0500673 std::function<void(sdbusplus::message_t&)> eventHandler =
674 [&](sdbusplus::message_t& message) {
Ed Tanousbb679322022-05-16 16:10:00 -0700675 if (message.is_method_error())
676 {
677 std::cerr << "callback method error\n";
678 return;
679 }
680 sensorsChanged->insert(message.get_path());
681 // this implicitly cancels the timer
Ed Tanous9b4a20e2022-09-06 08:47:11 -0700682 filterTimer.expires_from_now(std::chrono::seconds(1));
Ed Tanousbb679322022-05-16 16:10:00 -0700683
684 filterTimer.async_wait([&](const boost::system::error_code& ec) {
685 if (ec == boost::asio::error::operation_aborted)
James Feist6714a252018-09-10 15:26:18 -0700686 {
Ed Tanousbb679322022-05-16 16:10:00 -0700687 /* we were canceled*/
James Feist6714a252018-09-10 15:26:18 -0700688 return;
689 }
Ed Tanousbb679322022-05-16 16:10:00 -0700690 if (ec)
691 {
692 std::cerr << "timer error\n";
693 return;
694 }
Zev Weissa1456c42022-07-18 16:59:35 -0700695 createSensors(io, objectServer, sensors, systemBus, sensorsChanged,
696 false);
Ed Tanousbb679322022-05-16 16:10:00 -0700697 });
698 };
James Feist6714a252018-09-10 15:26:18 -0700699
Zev Weiss214d9712022-08-12 12:54:31 -0700700 std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
701 setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
Bruce Lee1263c3d2021-06-04 15:16:33 +0800702 setupManufacturingModeMatch(*systemBus);
Matt Spinler20bf2c12021-09-14 11:07:07 -0500703
704 // Watch for entity-manager to remove configuration interfaces
705 // so the corresponding sensors can be removed.
Patrick Williams92f8f512022-07-22 19:26:55 -0500706 auto ifaceRemovedMatch = std::make_unique<sdbusplus::bus::match_t>(
707 static_cast<sdbusplus::bus_t&>(*systemBus),
Matt Spinler20bf2c12021-09-14 11:07:07 -0500708 "type='signal',member='InterfacesRemoved',arg0path='" +
709 std::string(inventoryPath) + "/'",
Patrick Williams92f8f512022-07-22 19:26:55 -0500710 [&sensors](sdbusplus::message_t& msg) {
Ed Tanousbb679322022-05-16 16:10:00 -0700711 interfaceRemoved(msg, sensors);
Matt Spinler20bf2c12021-09-14 11:07:07 -0500712 });
713
714 matches.emplace_back(std::move(ifaceRemovedMatch));
715
James Feist6714a252018-09-10 15:26:18 -0700716 io.run();
717}