xref: /openbmc/phosphor-pid-control/dbus/dbusconfiguration.cpp (revision eb1a35c5433bf626715fa7af7896c25b9e701b1d)
1 /*
2 // Copyright (c) 2018 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 #include "config.h"
17 
18 #include "dbusconfiguration.hpp"
19 
20 #include "conf.hpp"
21 #include "dbushelper.hpp"
22 #include "dbusutil.hpp"
23 #include "ec/stepwise.hpp"
24 #include "util.hpp"
25 
26 #include <systemd/sd-bus.h>
27 
28 #include <boost/asio/error.hpp>
29 #include <boost/asio/steady_timer.hpp>
30 #include <sdbusplus/bus.hpp>
31 #include <sdbusplus/bus/match.hpp>
32 #include <sdbusplus/exception.hpp>
33 #include <sdbusplus/message.hpp>
34 #include <sdbusplus/message/native_types.hpp>
35 #include <xyz/openbmc_project/Association/Definitions/common.hpp>
36 #include <xyz/openbmc_project/Association/common.hpp>
37 #include <xyz/openbmc_project/Control/FanPwm/client.hpp>
38 #include <xyz/openbmc_project/Control/ThermalMode/common.hpp>
39 #include <xyz/openbmc_project/ObjectMapper/common.hpp>
40 #include <xyz/openbmc_project/Sensor/Threshold/Critical/common.hpp>
41 #include <xyz/openbmc_project/Sensor/Threshold/Warning/common.hpp>
42 #include <xyz/openbmc_project/Sensor/Value/client.hpp>
43 
44 #include <algorithm>
45 #include <array>
46 #include <chrono>
47 #include <cstdint>
48 #include <format>
49 #include <iostream>
50 #include <limits>
51 #include <list>
52 #include <map>
53 #include <stdexcept>
54 #include <string>
55 #include <tuple>
56 #include <unordered_map>
57 #include <utility>
58 #include <variant>
59 #include <vector>
60 
61 using ObjectMapper = sdbusplus::common::xyz::openbmc_project::ObjectMapper;
62 using SensorValue = sdbusplus::common::xyz::openbmc_project::sensor::Value;
63 using ControlFanPwm = sdbusplus::common::xyz::openbmc_project::control::FanPwm;
64 using ControlThermalMode =
65     sdbusplus::common::xyz::openbmc_project::control::ThermalMode;
66 using SensorThresholdWarning =
67     sdbusplus::common::xyz::openbmc_project::sensor::threshold::Warning;
68 using SensorThresholdCritical =
69     sdbusplus::common::xyz::openbmc_project::sensor::threshold::Critical;
70 
71 namespace pid_control
72 {
73 
74 constexpr const char* pidConfigurationInterface =
75     "xyz.openbmc_project.Configuration.Pid";
76 constexpr const char* objectManagerInterface =
77     "org.freedesktop.DBus.ObjectManager";
78 constexpr const char* pidZoneConfigurationInterface =
79     "xyz.openbmc_project.Configuration.Pid.Zone";
80 constexpr const char* stepwiseConfigurationInterface =
81     "xyz.openbmc_project.Configuration.Stepwise";
82 
83 using Association = std::tuple<std::string, std::string, std::string>;
84 using Associations = std::vector<Association>;
85 
86 namespace thresholds
87 {
88 const std::array<const char*, 4> types = {"CriticalLow", "CriticalHigh",
89                                           "WarningLow", "WarningHigh"};
90 
91 } // namespace thresholds
92 
93 namespace dbus_configuration
94 {
95 using SensorInterfaceType = std::pair<std::string, std::string>;
96 
getSensorNameFromPath(const std::string & dbusPath)97 inline std::string getSensorNameFromPath(const std::string& dbusPath)
98 {
99     return dbusPath.substr(dbusPath.find_last_of('/') + 1);
100 }
101 
sensorNameToDbusName(const std::string & sensorName)102 inline std::string sensorNameToDbusName(const std::string& sensorName)
103 {
104     std::string retString = sensorName;
105     std::replace(retString.begin(), retString.end(), ' ', '_');
106     return retString;
107 }
108 
getSelectedProfiles(sdbusplus::bus_t & bus)109 std::vector<std::string> getSelectedProfiles(sdbusplus::bus_t& bus)
110 {
111     std::vector<std::string> ret;
112     auto mapper = bus.new_method_call(
113         ObjectMapper::default_service, ObjectMapper::instance_path,
114         ObjectMapper::interface, ObjectMapper::method_names::get_sub_tree);
115     mapper.append("/", 0,
116                   std::array<const char*, 1>{ControlThermalMode::interface});
117     std::unordered_map<
118         std::string, std::unordered_map<std::string, std::vector<std::string>>>
119         respData;
120 
121     try
122     {
123         auto resp = bus.call(mapper);
124         resp.read(respData);
125     }
126     catch (const sdbusplus::exception_t&)
127     {
128         // can't do anything without mapper call data
129         throw std::runtime_error("ObjectMapper Call Failure");
130     }
131     if (respData.empty())
132     {
133         // if the user has profiles but doesn't expose the interface to select
134         // one, just go ahead without using profiles
135         return ret;
136     }
137 
138     // assumption is that we should only have a small handful of selected
139     // profiles at a time (probably only 1), so calling each individually should
140     // not incur a large cost
141     for (const auto& objectPair : respData)
142     {
143         const std::string& path = objectPair.first;
144         for (const auto& ownerPair : objectPair.second)
145         {
146             const std::string& busName = ownerPair.first;
147             auto getProfile =
148                 bus.new_method_call(busName.c_str(), path.c_str(),
149                                     "org.freedesktop.DBus.Properties", "Get");
150             getProfile.append(ControlThermalMode::interface,
151                               ControlThermalMode::property_names::current);
152             std::variant<std::string> variantResp;
153             try
154             {
155                 auto resp = bus.call(getProfile);
156                 resp.read(variantResp);
157             }
158             catch (const sdbusplus::exception_t&)
159             {
160                 throw std::runtime_error("Failure getting profile");
161             }
162             std::string mode = std::get<std::string>(variantResp);
163             ret.emplace_back(std::move(mode));
164         }
165     }
166     if constexpr (pid_control::conf::DEBUG)
167     {
168         std::cout << "Profiles selected: ";
169         for (const auto& profile : ret)
170         {
171             std::cout << profile << " ";
172         }
173         std::cout << "\n";
174     }
175     return ret;
176 }
177 
eventHandler(sd_bus_message * m,void * context,sd_bus_error *)178 int eventHandler(sd_bus_message* m, void* context, sd_bus_error*)
179 {
180     if (context == nullptr || m == nullptr)
181     {
182         throw std::runtime_error("Invalid match");
183     }
184 
185     // we skip associations because the mapper populates these, not the sensors
186     const std::array<const char*, 2> skipList = {
187         sdbusplus::common::xyz::openbmc_project::Association::interface,
188         sdbusplus::common::xyz::openbmc_project::association::Definitions::
189             interface};
190 
191     sdbusplus::message_t message(m);
192     if (std::string(message.get_member()) == "InterfacesAdded")
193     {
194         sdbusplus::message::object_path path;
195         std::unordered_map<
196             std::string,
197             std::unordered_map<std::string, std::variant<Associations, bool>>>
198             data;
199 
200         message.read(path, data);
201 
202         for (const char* skip : skipList)
203         {
204             auto find = data.find(skip);
205             if (find != data.end())
206             {
207                 data.erase(find);
208                 if (data.empty())
209                 {
210                     return 1;
211                 }
212             }
213         }
214 
215         if constexpr (pid_control::conf::DEBUG)
216         {
217             std::cout << "New config detected: " << path.str << std::endl;
218             for (auto& d : data)
219             {
220                 std::cout << "\tdata is " << d.first << std::endl;
221                 for (auto& second : d.second)
222                 {
223                     std::cout << "\t\tdata is " << second.first << std::endl;
224                 }
225             }
226         }
227     }
228 
229     boost::asio::steady_timer* timer =
230         static_cast<boost::asio::steady_timer*>(context);
231 
232     // do a brief sleep as we tend to get a bunch of these events at
233     // once
234     timer->expires_after(std::chrono::seconds(2));
235     timer->async_wait([](const boost::system::error_code ec) {
236         if (ec == boost::asio::error::operation_aborted)
237         {
238             /* another timer started*/
239             return;
240         }
241 
242         std::cout << "New configuration detected, reloading\n.";
243         tryRestartControlLoops();
244     });
245 
246     return 1;
247 }
248 
createMatches(sdbusplus::bus_t & bus,boost::asio::steady_timer & timer)249 void createMatches(sdbusplus::bus_t& bus, boost::asio::steady_timer& timer)
250 {
251     // this is a list because the matches can't be moved
252     static std::list<sdbusplus::bus::match_t> matches;
253 
254     const std::array<std::string, 4> interfaces = {
255         ControlThermalMode::interface, pidConfigurationInterface,
256         pidZoneConfigurationInterface, stepwiseConfigurationInterface};
257 
258     // this list only needs to be created once
259     if (!matches.empty())
260     {
261         return;
262     }
263 
264     // we restart when the configuration changes or there are new sensors
265     for (const auto& interface : interfaces)
266     {
267         matches.emplace_back(
268             bus,
269             "type='signal',member='PropertiesChanged',arg0namespace='" +
270                 interface + "'",
271             eventHandler, &timer);
272     }
273     matches.emplace_back(
274         bus,
275         "type='signal',member='InterfacesAdded',arg0path='/xyz/openbmc_project/"
276         "sensors/'",
277         eventHandler, &timer);
278     matches.emplace_back(bus,
279                          "type='signal',member='InterfacesRemoved',arg0path='/"
280                          "xyz/openbmc_project/sensors/'",
281                          eventHandler, &timer);
282 }
283 
284 /**
285  * retrieve an attribute from the pid configuration map
286  * @param[in] base - the PID configuration map, keys are the attributes and
287  * value is the variant associated with that attribute.
288  * @param attributeName - the name of the attribute
289  * @return a variant holding the value associated with a key
290  * @throw runtime_error : attributeName is not in base
291  */
getPIDAttribute(const std::unordered_map<std::string,DbusVariantType> & base,const std::string & attributeName)292 inline DbusVariantType getPIDAttribute(
293     const std::unordered_map<std::string, DbusVariantType>& base,
294     const std::string& attributeName)
295 {
296     auto search = base.find(attributeName);
297     if (search == base.end())
298     {
299         throw std::runtime_error("missing attribute " + attributeName);
300     }
301     return search->second;
302 }
303 
getCycleTimeSetting(const std::unordered_map<std::string,DbusVariantType> & zone,const int zoneIndex,const std::string & attributeName,uint64_t & value)304 inline void getCycleTimeSetting(
305     const std::unordered_map<std::string, DbusVariantType>& zone,
306     const int zoneIndex, const std::string& attributeName, uint64_t& value)
307 {
308     auto findAttributeName = zone.find(attributeName);
309     if (findAttributeName != zone.end())
310     {
311         double tmpAttributeValue =
312             std::visit(VariantToDoubleVisitor(), zone.at(attributeName));
313         if (tmpAttributeValue >= 1.0)
314         {
315             value = static_cast<uint64_t>(tmpAttributeValue);
316         }
317         else
318         {
319             std::cerr << "Zone " << zoneIndex << ": " << attributeName
320                       << " is invalid. Use default " << value << " ms\n";
321         }
322     }
323     else
324     {
325         std::cerr << "Zone " << zoneIndex << ": " << attributeName
326                   << " cannot find setting. Use default " << value << " ms\n";
327     }
328 }
329 
populatePidInfo(sdbusplus::bus_t & bus,const std::unordered_map<std::string,DbusVariantType> & base,conf::ControllerInfo & info,const std::string * thresholdProperty,const std::map<std::string,conf::SensorConfig> & sensorConfig)330 void populatePidInfo(
331     sdbusplus::bus_t& bus,
332     const std::unordered_map<std::string, DbusVariantType>& base,
333     conf::ControllerInfo& info, const std::string* thresholdProperty,
334     const std::map<std::string, conf::SensorConfig>& sensorConfig)
335 {
336     info.type = std::get<std::string>(getPIDAttribute(base, "Class"));
337     if (info.type == "fan")
338     {
339         info.setpoint = 0;
340     }
341     else
342     {
343         info.setpoint = std::visit(VariantToDoubleVisitor(),
344                                    getPIDAttribute(base, "SetPoint"));
345     }
346 
347     int failsafepercent = 0;
348     auto findFailSafe = base.find("FailSafePercent");
349     if (findFailSafe != base.end())
350     {
351         failsafepercent = std::visit(VariantToDoubleVisitor(),
352                                      getPIDAttribute(base, "FailSafePercent"));
353     }
354     info.failSafePercent = failsafepercent;
355 
356     if (thresholdProperty != nullptr)
357     {
358         std::string interface;
359         if (*thresholdProperty ==
360                 SensorThresholdWarning::property_names::warning_high ||
361             *thresholdProperty ==
362                 SensorThresholdWarning::property_names::warning_low)
363         {
364             interface = SensorThresholdWarning::interface;
365         }
366         else
367         {
368             interface = SensorThresholdCritical::interface;
369         }
370 
371         // Although this checks only the first vector element for the
372         // named threshold, it is OK, because the SetPointOffset parser
373         // splits up the input into individual vectors, each with only a
374         // single element, if it detects that SetPointOffset is in use.
375         const std::string& path =
376             sensorConfig.at(info.inputs.front().name).readPath;
377 
378         DbusHelper helper(bus);
379         std::string service = helper.getService(interface, path);
380         double reading = 0;
381         try
382         {
383             helper.getProperty(service, path, interface, *thresholdProperty,
384                                reading);
385         }
386         catch (const sdbusplus::exception_t& ex)
387         {
388             // unsupported threshold, leaving reading at 0
389         }
390 
391         info.setpoint += reading;
392     }
393 
394     info.pidInfo.ts = 1.0; // currently unused
395     info.pidInfo.proportionalCoeff = std::visit(
396         VariantToDoubleVisitor(), getPIDAttribute(base, "PCoefficient"));
397     info.pidInfo.integralCoeff = std::visit(
398         VariantToDoubleVisitor(), getPIDAttribute(base, "ICoefficient"));
399     // DCoefficient is below, it is optional, same reason as in buildjson.cpp
400     info.pidInfo.feedFwdOffset = std::visit(
401         VariantToDoubleVisitor(), getPIDAttribute(base, "FFOffCoefficient"));
402     info.pidInfo.feedFwdGain = std::visit(
403         VariantToDoubleVisitor(), getPIDAttribute(base, "FFGainCoefficient"));
404     info.pidInfo.integralLimit.max = std::visit(
405         VariantToDoubleVisitor(), getPIDAttribute(base, "ILimitMax"));
406     info.pidInfo.integralLimit.min = std::visit(
407         VariantToDoubleVisitor(), getPIDAttribute(base, "ILimitMin"));
408     info.pidInfo.outLim.max = std::visit(VariantToDoubleVisitor(),
409                                          getPIDAttribute(base, "OutLimitMax"));
410     info.pidInfo.outLim.min = std::visit(VariantToDoubleVisitor(),
411                                          getPIDAttribute(base, "OutLimitMin"));
412     info.pidInfo.slewNeg =
413         std::visit(VariantToDoubleVisitor(), getPIDAttribute(base, "SlewNeg"));
414     info.pidInfo.slewPos =
415         std::visit(VariantToDoubleVisitor(), getPIDAttribute(base, "SlewPos"));
416 
417     bool checkHysterWithSetpt = false;
418     double negativeHysteresis = 0;
419     double positiveHysteresis = 0;
420     double derivativeCoeff = 0;
421 
422     auto findCheckHysterFlag = base.find("CheckHysteresisWithSetpoint");
423     auto findNeg = base.find("NegativeHysteresis");
424     auto findPos = base.find("PositiveHysteresis");
425     auto findDerivative = base.find("DCoefficient");
426 
427     if (findCheckHysterFlag != base.end())
428     {
429         checkHysterWithSetpt = std::get<bool>(findCheckHysterFlag->second);
430     }
431     if (findNeg != base.end())
432     {
433         negativeHysteresis =
434             std::visit(VariantToDoubleVisitor(), findNeg->second);
435     }
436     if (findPos != base.end())
437     {
438         positiveHysteresis =
439             std::visit(VariantToDoubleVisitor(), findPos->second);
440     }
441     if (findDerivative != base.end())
442     {
443         derivativeCoeff =
444             std::visit(VariantToDoubleVisitor(), findDerivative->second);
445     }
446 
447     info.pidInfo.checkHysterWithSetpt = checkHysterWithSetpt;
448     info.pidInfo.negativeHysteresis = negativeHysteresis;
449     info.pidInfo.positiveHysteresis = positiveHysteresis;
450     info.pidInfo.derivativeCoeff = derivativeCoeff;
451 }
452 
init(sdbusplus::bus_t & bus,boost::asio::steady_timer & timer,std::map<std::string,conf::SensorConfig> & sensorConfig,std::map<int64_t,conf::PIDConf> & zoneConfig,std::map<int64_t,conf::ZoneConfig> & zoneDetailsConfig)453 bool init(sdbusplus::bus_t& bus, boost::asio::steady_timer& timer,
454           std::map<std::string, conf::SensorConfig>& sensorConfig,
455           std::map<int64_t, conf::PIDConf>& zoneConfig,
456           std::map<int64_t, conf::ZoneConfig>& zoneDetailsConfig)
457 {
458     sensorConfig.clear();
459     zoneConfig.clear();
460     zoneDetailsConfig.clear();
461 
462     createMatches(bus, timer);
463 
464     auto mapper = bus.new_method_call(
465         ObjectMapper::default_service, ObjectMapper::instance_path,
466         ObjectMapper::interface, ObjectMapper::method_names::get_sub_tree);
467     mapper.append(
468         "/", 0,
469         std::array<const char*, 6>{
470             objectManagerInterface, pidConfigurationInterface,
471             pidZoneConfigurationInterface, stepwiseConfigurationInterface,
472             SensorValue::interface, ControlFanPwm::interface});
473     std::unordered_map<
474         std::string, std::unordered_map<std::string, std::vector<std::string>>>
475         respData;
476     try
477     {
478         auto resp = bus.call(mapper);
479         resp.read(respData);
480     }
481     catch (const sdbusplus::exception_t&)
482     {
483         // can't do anything without mapper call data
484         throw std::runtime_error("ObjectMapper Call Failure");
485     }
486 
487     if (respData.empty())
488     {
489         // can't do anything without mapper call data
490         throw std::runtime_error("No configuration data available from Mapper");
491     }
492     // create a map of pair of <has pid configuration, ObjectManager path>
493     std::unordered_map<std::string, std::pair<bool, std::string>> owners;
494     // and a map of <path, interface> for sensors
495     std::unordered_map<std::string, std::string> sensors;
496     for (const auto& objectPair : respData)
497     {
498         for (const auto& ownerPair : objectPair.second)
499         {
500             auto& owner = owners[ownerPair.first];
501             for (const std::string& interface : ownerPair.second)
502             {
503                 if (interface == objectManagerInterface)
504                 {
505                     owner.second = objectPair.first;
506                 }
507                 if (interface == pidConfigurationInterface ||
508                     interface == pidZoneConfigurationInterface ||
509                     interface == stepwiseConfigurationInterface)
510                 {
511                     owner.first = true;
512                 }
513                 if (interface == SensorValue::interface ||
514                     interface == ControlFanPwm::interface)
515                 {
516                     // we're not interested in pwm sensors, just pwm control
517                     if (interface == SensorValue::interface &&
518                         objectPair.first.find("pwm") != std::string::npos)
519                     {
520                         continue;
521                     }
522                     sensors[objectPair.first] = interface;
523                 }
524             }
525         }
526     }
527     ManagedObjectType configurations;
528     for (const auto& owner : owners)
529     {
530         // skip if no pid configuration (means probably a sensor)
531         if (!owner.second.first)
532         {
533             continue;
534         }
535         auto endpoint = bus.new_method_call(
536             owner.first.c_str(), owner.second.second.c_str(),
537             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
538         ManagedObjectType configuration;
539         try
540         {
541             auto response = bus.call(endpoint);
542             response.read(configuration);
543         }
544         catch (const sdbusplus::exception_t&)
545         {
546             // this shouldn't happen, probably means daemon crashed
547             throw std::runtime_error(
548                 "Error getting managed objects from " + owner.first);
549         }
550 
551         for (auto& pathPair : configuration)
552         {
553             if (pathPair.second.find(pidConfigurationInterface) !=
554                     pathPair.second.end() ||
555                 pathPair.second.find(pidZoneConfigurationInterface) !=
556                     pathPair.second.end() ||
557                 pathPair.second.find(stepwiseConfigurationInterface) !=
558                     pathPair.second.end())
559             {
560                 configurations.emplace(pathPair);
561             }
562         }
563     }
564 
565     // remove controllers from config that aren't in the current profile(s)
566     std::vector<std::string> selectedProfiles = getSelectedProfiles(bus);
567     if (selectedProfiles.size())
568     {
569         for (auto pathIt = configurations.begin();
570              pathIt != configurations.end();)
571         {
572             for (auto confIt = pathIt->second.begin();
573                  confIt != pathIt->second.end();)
574             {
575                 auto profilesFind = confIt->second.find("Profiles");
576                 if (profilesFind == confIt->second.end())
577                 {
578                     confIt++;
579                     continue; // if no profiles selected, apply always
580                 }
581                 auto profiles =
582                     std::get<std::vector<std::string>>(profilesFind->second);
583                 if (profiles.empty())
584                 {
585                     confIt++;
586                     continue;
587                 }
588 
589                 bool found = false;
590                 for (const std::string& profile : profiles)
591                 {
592                     if (std::find(selectedProfiles.begin(),
593                                   selectedProfiles.end(), profile) !=
594                         selectedProfiles.end())
595                     {
596                         found = true;
597                         break;
598                     }
599                 }
600                 if (found)
601                 {
602                     confIt++;
603                 }
604                 else
605                 {
606                     confIt = pathIt->second.erase(confIt);
607                 }
608             }
609             if (pathIt->second.empty())
610             {
611                 pathIt = configurations.erase(pathIt);
612             }
613             else
614             {
615                 pathIt++;
616             }
617         }
618     }
619 
620     // On D-Bus, although not necessary,
621     // having the "zoneID" field can still be useful,
622     // as it is used for diagnostic messages,
623     // logging file names, and so on.
624     // Accept optional "ZoneIndex" parameter to explicitly specify.
625     // If not present, or not unique, auto-assign index,
626     // using 0-based numbering, ensuring uniqueness.
627     std::map<std::string, int64_t> foundZones;
628     for (const auto& configuration : configurations)
629     {
630         auto findZone =
631             configuration.second.find(pidZoneConfigurationInterface);
632         if (findZone != configuration.second.end())
633         {
634             const auto& zone = findZone->second;
635 
636             const std::string& name = std::get<std::string>(zone.at("Name"));
637 
638             auto findZoneIndex = zone.find("ZoneIndex");
639             if (findZoneIndex == zone.end())
640             {
641                 continue;
642             }
643 
644             auto ptrZoneIndex = std::get_if<double>(&(findZoneIndex->second));
645             if (!ptrZoneIndex)
646             {
647                 continue;
648             }
649 
650             auto desiredIndex = static_cast<int64_t>(*ptrZoneIndex);
651             auto grantedIndex = setZoneIndex(name, foundZones, desiredIndex);
652             std::cout << "Zone " << name << " is at ZoneIndex " << grantedIndex
653                       << "\n";
654         }
655     }
656 
657     for (const auto& configuration : configurations)
658     {
659         auto findZone =
660             configuration.second.find(pidZoneConfigurationInterface);
661         if (findZone != configuration.second.end())
662         {
663             const auto& zone = findZone->second;
664 
665             const std::string& name = std::get<std::string>(zone.at("Name"));
666 
667             auto index = getZoneIndex(name, foundZones);
668 
669             auto& details = zoneDetailsConfig[index];
670 
671             details.minThermalOutput = std::visit(VariantToDoubleVisitor(),
672                                                   zone.at("MinThermalOutput"));
673 
674             int failsafepercent = 0;
675             auto findFailSafe = zone.find("FailSafePercent");
676             if (findFailSafe != zone.end())
677             {
678                 failsafepercent = std::visit(VariantToDoubleVisitor(),
679                                              zone.at("FailSafePercent"));
680             }
681             details.failsafePercent = failsafepercent;
682 
683             getCycleTimeSetting(zone, index, "CycleIntervalTimeMS",
684                                 details.cycleTime.cycleIntervalTimeMS);
685             getCycleTimeSetting(zone, index, "UpdateThermalsTimeMS",
686                                 details.cycleTime.updateThermalsTimeMS);
687 
688             bool accumulateSetPoint = false;
689             auto findAccSetPoint = zone.find("AccumulateSetPoint");
690             if (findAccSetPoint != zone.end())
691             {
692                 accumulateSetPoint = std::get<bool>(findAccSetPoint->second);
693             }
694             details.accumulateSetPoint = accumulateSetPoint;
695         }
696         auto findBase = configuration.second.find(pidConfigurationInterface);
697         // loop through all the PID configurations and fill out a sensor config
698         if (findBase != configuration.second.end())
699         {
700             const auto& base =
701                 configuration.second.at(pidConfigurationInterface);
702             const std::string pidName =
703                 sensorNameToDbusName(std::get<std::string>(base.at("Name")));
704             const std::string pidClass =
705                 std::get<std::string>(base.at("Class"));
706             const std::vector<std::string>& zones =
707                 std::get<std::vector<std::string>>(base.at("Zones"));
708             for (const std::string& zone : zones)
709             {
710                 auto index = getZoneIndex(zone, foundZones);
711 
712                 conf::PIDConf& conf = zoneConfig[index];
713                 std::vector<std::string> inputSensorNames(
714                     std::get<std::vector<std::string>>(base.at("Inputs")));
715                 std::vector<std::string> outputSensorNames;
716                 std::vector<std::string> missingAcceptableSensorNames;
717                 std::vector<std::string> archivedInputSensorNames;
718 
719                 auto findMissingAcceptable = base.find("MissingIsAcceptable");
720                 if (findMissingAcceptable != base.end())
721                 {
722                     missingAcceptableSensorNames =
723                         std::get<std::vector<std::string>>(
724                             findMissingAcceptable->second);
725                 }
726 
727                 // assumption: all fan pids must have at least one output
728                 if (pidClass == "fan")
729                 {
730                     outputSensorNames = std::get<std::vector<std::string>>(
731                         getPIDAttribute(base, "Outputs"));
732                 }
733 
734                 bool unavailableAsFailed = true;
735                 auto findUnavailableAsFailed =
736                     base.find("InputUnavailableAsFailed");
737                 if (findUnavailableAsFailed != base.end())
738                 {
739                     unavailableAsFailed =
740                         std::get<bool>(findUnavailableAsFailed->second);
741                 }
742 
743                 std::vector<SensorInterfaceType> inputSensorInterfaces;
744                 std::vector<SensorInterfaceType> outputSensorInterfaces;
745                 std::vector<SensorInterfaceType>
746                     missingAcceptableSensorInterfaces;
747 
748                 /* populate an interface list for different sensor direction
749                  * types (input,output)
750                  */
751                 /* take the Inputs from the configuration and generate
752                  * a list of dbus descriptors (path, interface).
753                  * Mapping can be many-to-one since an element of Inputs can be
754                  * a regex
755                  */
756                 for (const std::string& sensorName : inputSensorNames)
757                 {
758 #ifndef HANDLE_MISSING_OBJECT_PATHS
759                     findSensors(sensors, sensorNameToDbusName(sensorName),
760                                 inputSensorInterfaces);
761 #else
762                     std::vector<std::pair<std::string, std::string>>
763                         sensorPathIfacePairs;
764                     auto found =
765                         findSensors(sensors, sensorNameToDbusName(sensorName),
766                                     sensorPathIfacePairs);
767                     if (found)
768                     {
769                         inputSensorInterfaces.insert(
770                             inputSensorInterfaces.end(),
771                             sensorPathIfacePairs.begin(),
772                             sensorPathIfacePairs.end());
773                     }
774                     else if (pidClass != "fan")
775                     {
776                         if (std::find(missingAcceptableSensorNames.begin(),
777                                       missingAcceptableSensorNames.end(),
778                                       sensorName) ==
779                             missingAcceptableSensorNames.end())
780                         {
781                             std::cerr
782                                 << "Pid controller: Missing a missing-unacceptable sensor from D-Bus "
783                                 << sensorName << "\n";
784                             std::string inputSensorName =
785                                 sensorNameToDbusName(sensorName);
786                             auto& config = sensorConfig[inputSensorName];
787                             archivedInputSensorNames.push_back(inputSensorName);
788                             config.type = pidClass;
789                             config.readPath =
790                                 getSensorPath(config.type, inputSensorName);
791                             config.timeout = 0;
792                             config.ignoreDbusMinMax = true;
793                             config.unavailableAsFailed = unavailableAsFailed;
794                         }
795                         else
796                         {
797                             // When an input sensor is NOT on DBus, and it's in
798                             // the MissingIsAcceptable list. Ignore it and
799                             // continue with the next input sensor.
800                             std::cout
801                                 << "Pid controller: Missing a missing-acceptable sensor from D-Bus "
802                                 << sensorName << "\n";
803                             continue;
804                         }
805                     }
806 #endif
807                 }
808                 for (const std::string& sensorName : outputSensorNames)
809                 {
810                     findSensors(sensors, sensorNameToDbusName(sensorName),
811                                 outputSensorInterfaces);
812                 }
813                 for (const std::string& sensorName :
814                      missingAcceptableSensorNames)
815                 {
816                     findSensors(sensors, sensorNameToDbusName(sensorName),
817                                 missingAcceptableSensorInterfaces);
818                 }
819 
820                 for (const SensorInterfaceType& inputSensorInterface :
821                      inputSensorInterfaces)
822                 {
823                     const std::string& dbusInterface =
824                         inputSensorInterface.second;
825                     const std::string& inputSensorPath =
826                         inputSensorInterface.first;
827 
828                     // Setting timeout to 0 is intentional, as D-Bus passive
829                     // sensor updates are pushed in, not pulled by timer poll.
830                     // Setting ignoreDbusMinMax is intentional, as this
831                     // prevents normalization of values to [0.0, 1.0] range,
832                     // which would mess up the PID loop math.
833                     // All non-fan PID classes should be initialized this way.
834                     // As for why a fan should not use this code path, see
835                     // the ed1dafdf168def37c65bfb7a5efd18d9dbe04727 commit.
836                     if ((pidClass == "temp") || (pidClass == "margin") ||
837                         (pidClass == "power") || (pidClass == "powersum"))
838                     {
839                         std::string inputSensorName =
840                             getSensorNameFromPath(inputSensorPath);
841                         auto& config = sensorConfig[inputSensorName];
842                         archivedInputSensorNames.push_back(inputSensorName);
843                         config.type = pidClass;
844                         config.readPath = inputSensorInterface.first;
845                         config.timeout = 0;
846                         config.ignoreDbusMinMax = true;
847                         config.unavailableAsFailed = unavailableAsFailed;
848                     }
849 
850                     if (dbusInterface != SensorValue::interface)
851                     {
852                         /* all expected inputs in the configuration are expected
853                          * to be sensor interfaces
854                          */
855                         throw std::runtime_error(std::format(
856                             "sensor at dbus path [{}] has an interface [{}] that does not match the expected interface of {}",
857                             inputSensorPath, dbusInterface,
858                             SensorValue::interface));
859                     }
860                 }
861 
862                 // MissingIsAcceptable same postprocessing as Inputs
863                 missingAcceptableSensorNames.clear();
864                 for (const SensorInterfaceType&
865                          missingAcceptableSensorInterface :
866                      missingAcceptableSensorInterfaces)
867                 {
868                     const std::string& dbusInterface =
869                         missingAcceptableSensorInterface.second;
870                     const std::string& missingAcceptableSensorPath =
871                         missingAcceptableSensorInterface.first;
872 
873                     std::string missingAcceptableSensorName =
874                         getSensorNameFromPath(missingAcceptableSensorPath);
875                     missingAcceptableSensorNames.push_back(
876                         missingAcceptableSensorName);
877 
878                     if (dbusInterface != SensorValue::interface)
879                     {
880                         /* MissingIsAcceptable same error checking as Inputs
881                          */
882                         throw std::runtime_error(std::format(
883                             "sensor at dbus path [{}] has an interface [{}] that does not match the expected interface of {}",
884                             missingAcceptableSensorPath, dbusInterface,
885                             SensorValue::interface));
886                     }
887                 }
888 
889                 /* fan pids need to pair up tach sensors with their pwm
890                  * counterparts
891                  */
892                 if (pidClass == "fan")
893                 {
894                     /* If a PID is a fan there should be either
895                      * (1) one output(pwm) per input(tach)
896                      * OR
897                      * (2) one putput(pwm) for all inputs(tach)
898                      * everything else indicates a bad configuration.
899                      */
900                     bool singlePwm = false;
901                     if (outputSensorInterfaces.size() == 1)
902                     {
903                         /* one pwm, set write paths for all fan sensors to it */
904                         singlePwm = true;
905                     }
906                     else if (inputSensorInterfaces.size() ==
907                              outputSensorInterfaces.size())
908                     {
909                         /* one to one mapping, each fan sensor gets its own pwm
910                          * control */
911                         singlePwm = false;
912                     }
913                     else
914                     {
915                         throw std::runtime_error(
916                             "fan PID has invalid number of Outputs");
917                     }
918                     std::string fanSensorName;
919                     std::string pwmPath;
920                     std::string pwmInterface;
921                     std::string pwmSensorName;
922                     if (singlePwm)
923                     {
924                         /* if just a single output(pwm) is provided then use
925                          * that pwm control path for all the fan sensor write
926                          * path configs
927                          */
928                         pwmPath = outputSensorInterfaces.at(0).first;
929                         pwmInterface = outputSensorInterfaces.at(0).second;
930                     }
931                     for (uint32_t idx = 0; idx < inputSensorInterfaces.size();
932                          idx++)
933                     {
934                         if (!singlePwm)
935                         {
936                             pwmPath = outputSensorInterfaces.at(idx).first;
937                             pwmInterface =
938                                 outputSensorInterfaces.at(idx).second;
939                         }
940                         if (ControlFanPwm::interface != pwmInterface)
941                         {
942                             throw std::runtime_error(std::format(
943                                 "fan pwm control at dbus path [{}] has an interface [{}] that does not match the expected interface of {}",
944                                 pwmPath, pwmInterface,
945                                 ControlFanPwm::interface));
946                         }
947                         const std::string& fanPath =
948                             inputSensorInterfaces.at(idx).first;
949                         fanSensorName = getSensorNameFromPath(fanPath);
950                         pwmSensorName = getSensorNameFromPath(pwmPath);
951                         std::string fanPwmIndex = fanSensorName + pwmSensorName;
952                         archivedInputSensorNames.push_back(fanPwmIndex);
953                         auto& fanConfig = sensorConfig[fanPwmIndex];
954                         fanConfig.type = pidClass;
955                         fanConfig.readPath = fanPath;
956                         fanConfig.writePath = pwmPath;
957                         // todo: un-hardcode this if there are fans with
958                         // different ranges
959                         fanConfig.max = 255;
960                         fanConfig.min = 0;
961                     }
962                 }
963                 // if the sensors aren't available in the current state, don't
964                 // add them to the configuration.
965                 if (archivedInputSensorNames.empty())
966                 {
967                     continue;
968                 }
969 
970                 std::string offsetType;
971 
972                 // SetPointOffset is a threshold value to pull from the sensor
973                 // to apply an offset. For upper thresholds this means the
974                 // setpoint is usually negative.
975                 auto findSetpointOffset = base.find("SetPointOffset");
976                 if (findSetpointOffset != base.end())
977                 {
978                     offsetType =
979                         std::get<std::string>(findSetpointOffset->second);
980                     if (std::find(thresholds::types.begin(),
981                                   thresholds::types.end(), offsetType) ==
982                         thresholds::types.end())
983                     {
984                         throw std::runtime_error(
985                             "Unsupported type: " + offsetType);
986                     }
987                 }
988 
989                 std::vector<double> inputTempToMargin;
990 
991                 auto findTempToMargin = base.find("TempToMargin");
992                 if (findTempToMargin != base.end())
993                 {
994                     inputTempToMargin =
995                         std::get<std::vector<double>>(findTempToMargin->second);
996                 }
997 
998                 std::vector<pid_control::conf::SensorInput> sensorInputs =
999                     spliceInputs(archivedInputSensorNames, inputTempToMargin,
1000                                  missingAcceptableSensorNames);
1001 
1002                 if (offsetType.empty())
1003                 {
1004                     conf::ControllerInfo& info = conf[pidName];
1005                     info.inputs = std::move(sensorInputs);
1006                     populatePidInfo(bus, base, info, nullptr, sensorConfig);
1007                 }
1008                 else
1009                 {
1010                     // we have to split up the inputs, as in practice t-control
1011                     // values will differ, making setpoints differ
1012                     for (const pid_control::conf::SensorInput& input :
1013                          sensorInputs)
1014                     {
1015                         conf::ControllerInfo& info = conf[input.name];
1016                         info.inputs.emplace_back(input);
1017                         populatePidInfo(bus, base, info, &offsetType,
1018                                         sensorConfig);
1019                     }
1020                 }
1021             }
1022         }
1023         auto findStepwise =
1024             configuration.second.find(stepwiseConfigurationInterface);
1025         if (findStepwise != configuration.second.end())
1026         {
1027             const auto& base = findStepwise->second;
1028             const std::string pidName =
1029                 sensorNameToDbusName(std::get<std::string>(base.at("Name")));
1030             const std::vector<std::string>& zones =
1031                 std::get<std::vector<std::string>>(base.at("Zones"));
1032             for (const std::string& zone : zones)
1033             {
1034                 auto index = getZoneIndex(zone, foundZones);
1035 
1036                 conf::PIDConf& conf = zoneConfig[index];
1037 
1038                 std::vector<std::string> inputs;
1039                 std::vector<std::string> missingAcceptableSensors;
1040                 std::vector<std::string> missingAcceptableSensorNames;
1041                 std::vector<std::string> sensorNames =
1042                     std::get<std::vector<std::string>>(base.at("Inputs"));
1043 
1044                 auto findMissingAcceptable = base.find("MissingIsAcceptable");
1045                 if (findMissingAcceptable != base.end())
1046                 {
1047                     missingAcceptableSensorNames =
1048                         std::get<std::vector<std::string>>(
1049                             findMissingAcceptable->second);
1050                 }
1051 
1052                 bool unavailableAsFailed = true;
1053                 auto findUnavailableAsFailed =
1054                     base.find("InputUnavailableAsFailed");
1055                 if (findUnavailableAsFailed != base.end())
1056                 {
1057                     unavailableAsFailed =
1058                         std::get<bool>(findUnavailableAsFailed->second);
1059                 }
1060 
1061                 bool sensorFound = false;
1062                 for (const std::string& sensorName : sensorNames)
1063                 {
1064                     std::vector<std::pair<std::string, std::string>>
1065                         sensorPathIfacePairs;
1066                     if (!findSensors(sensors, sensorNameToDbusName(sensorName),
1067                                      sensorPathIfacePairs))
1068                     {
1069 #ifndef HANDLE_MISSING_OBJECT_PATHS
1070                         break;
1071 #else
1072                         if (std::find(missingAcceptableSensorNames.begin(),
1073                                       missingAcceptableSensorNames.end(),
1074                                       sensorName) ==
1075                             missingAcceptableSensorNames.end())
1076                         {
1077                             // When an input sensor is NOT on DBus, and it's NOT
1078                             // in the MissingIsAcceptable list. Build it as a
1079                             // failed sensor with default information (temp
1080                             // sensor path, temp type, ...)
1081                             std::cerr
1082                                 << "Stepwise controller: Missing a missing-unacceptable sensor from D-Bus "
1083                                 << sensorName << "\n";
1084                             std::string shortName =
1085                                 sensorNameToDbusName(sensorName);
1086 
1087                             inputs.push_back(shortName);
1088                             auto& config = sensorConfig[shortName];
1089                             config.type = "temp";
1090                             config.readPath =
1091                                 getSensorPath(config.type, shortName);
1092                             config.ignoreDbusMinMax = true;
1093                             config.unavailableAsFailed = unavailableAsFailed;
1094                             // todo: maybe un-hardcode this if we run into
1095                             // slower timeouts with sensors
1096 
1097                             config.timeout = 0;
1098                             sensorFound = true;
1099                         }
1100                         else
1101                         {
1102                             // When an input sensor is NOT on DBus, and it's in
1103                             // the MissingIsAcceptable list. Ignore it and
1104                             // continue with the next input sensor.
1105                             std::cout
1106                                 << "Stepwise controller: Missing a missing-acceptable sensor from D-Bus "
1107                                 << sensorName << "\n";
1108                             continue;
1109                         }
1110 #endif
1111                     }
1112                     else
1113                     {
1114                         for (const auto& sensorPathIfacePair :
1115                              sensorPathIfacePairs)
1116                         {
1117                             std::string shortName = getSensorNameFromPath(
1118                                 sensorPathIfacePair.first);
1119 
1120                             inputs.push_back(shortName);
1121                             auto& config = sensorConfig[shortName];
1122                             config.readPath = sensorPathIfacePair.first;
1123                             config.type = "temp";
1124                             config.ignoreDbusMinMax = true;
1125                             config.unavailableAsFailed = unavailableAsFailed;
1126                             // todo: maybe un-hardcode this if we run into
1127                             // slower timeouts with sensors
1128 
1129                             config.timeout = 0;
1130                             sensorFound = true;
1131                         }
1132                     }
1133                 }
1134                 if (!sensorFound)
1135                 {
1136                     continue;
1137                 }
1138 
1139                 // MissingIsAcceptable same postprocessing as Inputs
1140                 for (const std::string& missingAcceptableSensorName :
1141                      missingAcceptableSensorNames)
1142                 {
1143                     std::vector<std::pair<std::string, std::string>>
1144                         sensorPathIfacePairs;
1145                     if (!findSensors(
1146                             sensors,
1147                             sensorNameToDbusName(missingAcceptableSensorName),
1148                             sensorPathIfacePairs))
1149                     {
1150 #ifndef HANDLE_MISSING_OBJECT_PATHS
1151                         break;
1152 #else
1153                         // When a sensor in the MissingIsAcceptable list is NOT
1154                         // on DBus and it still reaches here, which contradicts
1155                         // to what we did in the Input sensor building step.
1156                         // Continue.
1157                         continue;
1158 #endif
1159                     }
1160 
1161                     for (const auto& sensorPathIfacePair : sensorPathIfacePairs)
1162                     {
1163                         std::string shortName =
1164                             getSensorNameFromPath(sensorPathIfacePair.first);
1165 
1166                         missingAcceptableSensors.push_back(shortName);
1167                     }
1168                 }
1169 
1170                 conf::ControllerInfo& info = conf[pidName];
1171 
1172                 std::vector<double> inputTempToMargin;
1173 
1174                 auto findTempToMargin = base.find("TempToMargin");
1175                 if (findTempToMargin != base.end())
1176                 {
1177                     inputTempToMargin =
1178                         std::get<std::vector<double>>(findTempToMargin->second);
1179                 }
1180 
1181                 info.inputs = spliceInputs(inputs, inputTempToMargin,
1182                                            missingAcceptableSensors);
1183 
1184                 info.type = "stepwise";
1185                 info.stepwiseInfo.ts = 1.0; // currently unused
1186                 info.stepwiseInfo.positiveHysteresis = 0.0;
1187                 info.stepwiseInfo.negativeHysteresis = 0.0;
1188                 std::string subtype = std::get<std::string>(base.at("Class"));
1189 
1190                 info.stepwiseInfo.isCeiling = (subtype == "Ceiling");
1191                 auto findPosHyst = base.find("PositiveHysteresis");
1192                 auto findNegHyst = base.find("NegativeHysteresis");
1193                 if (findPosHyst != base.end())
1194                 {
1195                     info.stepwiseInfo.positiveHysteresis = std::visit(
1196                         VariantToDoubleVisitor(), findPosHyst->second);
1197                 }
1198                 if (findNegHyst != base.end())
1199                 {
1200                     info.stepwiseInfo.negativeHysteresis = std::visit(
1201                         VariantToDoubleVisitor(), findNegHyst->second);
1202                 }
1203                 std::vector<double> readings =
1204                     std::get<std::vector<double>>(base.at("Reading"));
1205                 if (readings.size() > ec::maxStepwisePoints)
1206                 {
1207                     throw std::invalid_argument("Too many stepwise points.");
1208                 }
1209                 if (readings.empty())
1210                 {
1211                     throw std::invalid_argument(
1212                         "Must have one stepwise point.");
1213                 }
1214                 std::copy(readings.begin(), readings.end(),
1215                           info.stepwiseInfo.reading);
1216                 if (readings.size() < ec::maxStepwisePoints)
1217                 {
1218                     info.stepwiseInfo.reading[readings.size()] =
1219                         std::numeric_limits<double>::quiet_NaN();
1220                 }
1221                 std::vector<double> outputs =
1222                     std::get<std::vector<double>>(base.at("Output"));
1223                 if (readings.size() != outputs.size())
1224                 {
1225                     throw std::invalid_argument(
1226                         "Outputs size must match readings");
1227                 }
1228                 std::copy(outputs.begin(), outputs.end(),
1229                           info.stepwiseInfo.output);
1230                 if (outputs.size() < ec::maxStepwisePoints)
1231                 {
1232                     info.stepwiseInfo.output[outputs.size()] =
1233                         std::numeric_limits<double>::quiet_NaN();
1234                 }
1235             }
1236         }
1237     }
1238     if constexpr (pid_control::conf::DEBUG)
1239     {
1240         debugPrint(sensorConfig, zoneConfig, zoneDetailsConfig);
1241     }
1242     if (zoneConfig.empty() || zoneDetailsConfig.empty())
1243     {
1244         std::cerr
1245             << "No fan zones, application pausing until new configuration\n";
1246         return false;
1247     }
1248     return true;
1249 }
1250 
1251 } // namespace dbus_configuration
1252 } // namespace pid_control
1253