xref: /openbmc/dbus-sensors/src/adc/ADCSensorMain.cpp (revision d4bc41f295c919c985366a4abe53db99f611c2b5)
1 /*
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 
17 #include "ADCSensor.hpp"
18 #include "Thresholds.hpp"
19 #include "Utils.hpp"
20 #include "VariantVisitors.hpp"
21 
22 #include <boost/algorithm/string/case_conv.hpp>
23 #include <boost/asio/error.hpp>
24 #include <boost/asio/io_context.hpp>
25 #include <boost/asio/post.hpp>
26 #include <boost/asio/steady_timer.hpp>
27 #include <boost/container/flat_map.hpp>
28 #include <boost/container/flat_set.hpp>
29 #include <gpiod.hpp>
30 #include <phosphor-logging/lg2.hpp>
31 #include <sdbusplus/asio/connection.hpp>
32 #include <sdbusplus/asio/object_server.hpp>
33 #include <sdbusplus/bus.hpp>
34 #include <sdbusplus/bus/match.hpp>
35 #include <sdbusplus/message.hpp>
36 #include <sdbusplus/message/native_types.hpp>
37 
38 #include <array>
39 #include <chrono>
40 #include <cstddef>
41 #include <filesystem>
42 #include <fstream>
43 #include <functional>
44 #include <memory>
45 #include <optional>
46 #include <regex>
47 #include <stdexcept>
48 #include <string>
49 #include <utility>
50 #include <variant>
51 #include <vector>
52 
53 static constexpr bool debug = false;
54 static constexpr float pollRateDefault = 0.5;
55 static constexpr float gpioBridgeSetupTimeDefault = 0.02;
56 
57 static constexpr auto sensorTypes{std::to_array<const char*>({"ADC"})};
58 static std::regex inputRegex(R"(in(\d+)_input)");
59 
60 static boost::container::flat_map<size_t, bool> cpuPresence;
61 
62 enum class UpdateType
63 {
64     init,
65     cpuPresenceChange
66 };
67 
68 // filter out adc from any other voltage sensor
isAdc(const std::filesystem::path & parentPath)69 bool isAdc(const std::filesystem::path& parentPath)
70 {
71     std::filesystem::path namePath = parentPath / "name";
72 
73     std::ifstream nameFile(namePath);
74     if (!nameFile.good())
75     {
76         lg2::error("Failure reading '{PATH}'", "PATH", namePath.string());
77         return false;
78     }
79 
80     std::string name;
81     std::getline(nameFile, name);
82 
83     return name == "iio_hwmon";
84 }
85 
createSensors(boost::asio::io_context & io,sdbusplus::asio::object_server & objectServer,boost::container::flat_map<std::string,std::shared_ptr<ADCSensor>> & sensors,std::shared_ptr<sdbusplus::asio::connection> & dbusConnection,const std::shared_ptr<boost::container::flat_set<std::string>> & sensorsChanged,UpdateType updateType)86 void createSensors(
87     boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
88     boost::container::flat_map<std::string, std::shared_ptr<ADCSensor>>&
89         sensors,
90     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
91     const std::shared_ptr<boost::container::flat_set<std::string>>&
92         sensorsChanged,
93     UpdateType updateType)
94 {
95     auto getter = std::make_shared<GetSensorConfiguration>(
96         dbusConnection,
97         [&io, &objectServer, &sensors, &dbusConnection, sensorsChanged,
98          updateType](const ManagedObjectType& sensorConfigurations) {
99             bool firstScan = sensorsChanged == nullptr;
100             std::vector<std::filesystem::path> paths;
101             if (!findFiles(std::filesystem::path("/sys/class/hwmon"),
102                            R"(in\d+_input)", paths))
103             {
104                 lg2::error("No adc sensors in system");
105                 return;
106             }
107 
108             // iterate through all found adc sensors, and try to match them with
109             // configuration
110             for (auto& path : paths)
111             {
112                 if (!isAdc(path.parent_path()))
113                 {
114                     continue;
115                 }
116                 std::smatch match;
117                 std::string pathStr = path.string();
118 
119                 std::regex_search(pathStr, match, inputRegex);
120                 std::string indexStr = *(match.begin() + 1);
121 
122                 // convert to 0 based
123                 size_t index = std::stoul(indexStr) - 1;
124 
125                 const SensorData* sensorData = nullptr;
126                 const std::string* interfacePath = nullptr;
127                 const std::pair<std::string, SensorBaseConfigMap>*
128                     baseConfiguration = nullptr;
129                 for (const auto& [path, cfgData] : sensorConfigurations)
130                 {
131                     // clear it out each loop
132                     baseConfiguration = nullptr;
133 
134                     // find base configuration
135                     for (const char* type : sensorTypes)
136                     {
137                         auto sensorBase =
138                             cfgData.find(configInterfaceName(type));
139                         if (sensorBase != cfgData.end())
140                         {
141                             baseConfiguration = &(*sensorBase);
142                             break;
143                         }
144                     }
145                     if (baseConfiguration == nullptr)
146                     {
147                         continue;
148                     }
149                     auto findIndex = baseConfiguration->second.find("Index");
150                     if (findIndex == baseConfiguration->second.end())
151                     {
152                         lg2::error(
153                             "Base configuration missing Index: '{INTERFACE}'",
154                             "INTERFACE", baseConfiguration->first);
155                         continue;
156                     }
157 
158                     unsigned int number = std::visit(
159                         VariantToUnsignedIntVisitor(), findIndex->second);
160 
161                     if (number != index)
162                     {
163                         continue;
164                     }
165 
166                     sensorData = &cfgData;
167                     interfacePath = &path.str;
168                     break;
169                 }
170                 if (sensorData == nullptr)
171                 {
172                     if constexpr (debug)
173                     {
174                         lg2::error("failed to find match for '{PATH}'", "PATH",
175                                    path.string());
176                     }
177                     continue;
178                 }
179 
180                 if (baseConfiguration == nullptr)
181                 {
182                     lg2::error("error finding base configuration for '{PATH}'",
183                                "PATH", path.string());
184                     continue;
185                 }
186 
187                 auto findSensorName = baseConfiguration->second.find("Name");
188                 if (findSensorName == baseConfiguration->second.end())
189                 {
190                     lg2::error(
191                         "could not determine configuration name for '{PATH}'",
192                         "PATH", path.string());
193                     continue;
194                 }
195                 std::string sensorName =
196                     std::get<std::string>(findSensorName->second);
197 
198                 // on rescans, only update sensors we were signaled by
199                 auto findSensor = sensors.find(sensorName);
200                 if (!firstScan && findSensor != sensors.end())
201                 {
202                     bool found = false;
203                     for (auto it = sensorsChanged->begin();
204                          it != sensorsChanged->end(); it++)
205                     {
206                         if (findSensor->second &&
207                             it->ends_with(findSensor->second->name))
208                         {
209                             sensorsChanged->erase(it);
210                             findSensor->second = nullptr;
211                             found = true;
212                             break;
213                         }
214                     }
215                     if (!found)
216                     {
217                         continue;
218                     }
219                 }
220 
221                 auto findCPU = baseConfiguration->second.find("CPURequired");
222                 if (findCPU != baseConfiguration->second.end())
223                 {
224                     size_t index =
225                         std::visit(VariantToIntVisitor(), findCPU->second);
226                     auto presenceFind = cpuPresence.find(index);
227                     if (presenceFind == cpuPresence.end())
228                     {
229                         continue; // no such cpu
230                     }
231                     if (!presenceFind->second)
232                     {
233                         continue; // cpu not installed
234                     }
235                 }
236                 else if (updateType == UpdateType::cpuPresenceChange)
237                 {
238                     continue;
239                 }
240 
241                 std::vector<thresholds::Threshold> sensorThresholds;
242                 if (!parseThresholdsFromConfig(*sensorData, sensorThresholds))
243                 {
244                     lg2::error("error populating thresholds for '{NAME}'",
245                                "NAME", sensorName);
246                 }
247 
248                 auto findScaleFactor =
249                     baseConfiguration->second.find("ScaleFactor");
250                 float scaleFactor = 1.0;
251                 if (findScaleFactor != baseConfiguration->second.end())
252                 {
253                     scaleFactor = std::visit(VariantToFloatVisitor(),
254                                              findScaleFactor->second);
255                     // scaleFactor is used in division
256                     if (scaleFactor == 0.0F)
257                     {
258                         scaleFactor = 1.0;
259                     }
260                 }
261 
262                 float pollRate =
263                     getPollRate(baseConfiguration->second, pollRateDefault);
264                 PowerState readState = getPowerState(baseConfiguration->second);
265 
266                 auto& sensor = sensors[sensorName];
267                 sensor = nullptr;
268 
269                 std::optional<BridgeGpio> bridgeGpio;
270                 for (const auto& [key, cfgMap] : *sensorData)
271                 {
272                     if (key.find("BridgeGpio") != std::string::npos)
273                     {
274                         auto findName = cfgMap.find("Name");
275                         if (findName != cfgMap.end())
276                         {
277                             std::string gpioName = std::visit(
278                                 VariantToStringVisitor(), findName->second);
279 
280                             int polarity = gpiod::line::ACTIVE_HIGH;
281                             auto findPolarity = cfgMap.find("Polarity");
282                             if (findPolarity != cfgMap.end())
283                             {
284                                 if (std::string("Low") ==
285                                     std::visit(VariantToStringVisitor(),
286                                                findPolarity->second))
287                                 {
288                                     polarity = gpiod::line::ACTIVE_LOW;
289                                 }
290                             }
291 
292                             float setupTime = gpioBridgeSetupTimeDefault;
293                             auto findSetupTime = cfgMap.find("SetupTime");
294                             if (findSetupTime != cfgMap.end())
295                             {
296                                 setupTime = std::visit(VariantToFloatVisitor(),
297                                                        findSetupTime->second);
298                             }
299 
300                             bridgeGpio =
301                                 BridgeGpio(gpioName, polarity, setupTime);
302                         }
303 
304                         break;
305                     }
306                 }
307 
308                 sensor = std::make_shared<ADCSensor>(
309                     path.string(), objectServer, dbusConnection, io, sensorName,
310                     std::move(sensorThresholds), scaleFactor, pollRate,
311                     readState, *interfacePath, std::move(bridgeGpio));
312                 sensor->setupRead();
313             }
314         });
315 
316     getter->getConfiguration(
317         std::vector<std::string>{sensorTypes.begin(), sensorTypes.end()});
318 }
319 
main()320 int main()
321 {
322     boost::asio::io_context io;
323     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
324     sdbusplus::asio::object_server objectServer(systemBus, true);
325     objectServer.add_manager("/xyz/openbmc_project/sensors");
326 
327     systemBus->request_name("xyz.openbmc_project.ADCSensor");
328     boost::container::flat_map<std::string, std::shared_ptr<ADCSensor>> sensors;
329     auto sensorsChanged =
330         std::make_shared<boost::container::flat_set<std::string>>();
331 
332     boost::asio::post(io, [&]() {
333         createSensors(io, objectServer, sensors, systemBus, nullptr,
334                       UpdateType::init);
335     });
336 
337     boost::asio::steady_timer filterTimer(io);
338     std::function<void(sdbusplus::message_t&)> eventHandler =
339         [&](sdbusplus::message_t& message) {
340             if (message.is_method_error())
341             {
342                 lg2::error("callback method error");
343                 return;
344             }
345             sensorsChanged->insert(message.get_path());
346             // this implicitly cancels the timer
347             filterTimer.expires_after(std::chrono::seconds(1));
348 
349             filterTimer.async_wait([&](const boost::system::error_code& ec) {
350                 if (ec == boost::asio::error::operation_aborted)
351                 {
352                     /* we were canceled*/
353                     return;
354                 }
355                 if (ec)
356                 {
357                     lg2::error("timer error");
358                     return;
359                 }
360                 createSensors(io, objectServer, sensors, systemBus,
361                               sensorsChanged, UpdateType::init);
362             });
363         };
364 
365     boost::asio::steady_timer cpuFilterTimer(io);
366     std::function<void(sdbusplus::message_t&)> cpuPresenceHandler =
367         [&](sdbusplus::message_t& message) {
368             std::string path = message.get_path();
369             boost::to_lower(path);
370 
371             sdbusplus::message::object_path cpuPath(path);
372             std::string cpuName = cpuPath.filename();
373             if (!cpuName.starts_with("cpu"))
374             {
375                 return; // not interested
376             }
377             size_t index = 0;
378             try
379             {
380                 index = std::stoi(path.substr(path.size() - 1));
381             }
382             catch (const std::invalid_argument&)
383             {
384                 lg2::error("Found invalid path: '{PATH}'", "PATH", path);
385                 return;
386             }
387 
388             std::string objectName;
389             boost::container::flat_map<std::string, std::variant<bool>> values;
390             message.read(objectName, values);
391             auto findPresence = values.find("Present");
392             if (findPresence != values.end())
393             {
394                 cpuPresence[index] = std::get<bool>(findPresence->second);
395             }
396 
397             // this implicitly cancels the timer
398             cpuFilterTimer.expires_after(std::chrono::seconds(1));
399 
400             cpuFilterTimer.async_wait([&](const boost::system::error_code& ec) {
401                 if (ec == boost::asio::error::operation_aborted)
402                 {
403                     /* we were canceled*/
404                     return;
405                 }
406                 if (ec)
407                 {
408                     lg2::error("timer error");
409                     return;
410                 }
411                 createSensors(io, objectServer, sensors, systemBus, nullptr,
412                               UpdateType::cpuPresenceChange);
413             });
414         };
415 
416     std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
417         setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
418     matches.emplace_back(std::make_unique<sdbusplus::bus::match_t>(
419         static_cast<sdbusplus::bus_t&>(*systemBus),
420         "type='signal',member='PropertiesChanged',path_namespace='" +
421             std::string(cpuInventoryPath) +
422             "',arg0namespace='xyz.openbmc_project.Inventory.Item'",
423         cpuPresenceHandler));
424 
425     setupManufacturingModeMatch(*systemBus);
426     io.run();
427 }
428