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 bool ignoreFailIfHostOff = false;
744 auto findIgnoreFailIfHostOff = base.find("IgnoreFailIfHostOff");
745 if (findIgnoreFailIfHostOff != base.end())
746 {
747 ignoreFailIfHostOff =
748 std::get<bool>(findIgnoreFailIfHostOff->second);
749 }
750
751 std::vector<SensorInterfaceType> inputSensorInterfaces;
752 std::vector<SensorInterfaceType> outputSensorInterfaces;
753 std::vector<SensorInterfaceType>
754 missingAcceptableSensorInterfaces;
755
756 /* populate an interface list for different sensor direction
757 * types (input,output)
758 */
759 /* take the Inputs from the configuration and generate
760 * a list of dbus descriptors (path, interface).
761 * Mapping can be many-to-one since an element of Inputs can be
762 * a regex
763 */
764 for (const std::string& sensorName : inputSensorNames)
765 {
766 #ifndef HANDLE_MISSING_OBJECT_PATHS
767 findSensors(sensors, sensorNameToDbusName(sensorName),
768 inputSensorInterfaces);
769 #else
770 std::vector<std::pair<std::string, std::string>>
771 sensorPathIfacePairs;
772 auto found =
773 findSensors(sensors, sensorNameToDbusName(sensorName),
774 sensorPathIfacePairs);
775 if (found)
776 {
777 inputSensorInterfaces.insert(
778 inputSensorInterfaces.end(),
779 sensorPathIfacePairs.begin(),
780 sensorPathIfacePairs.end());
781 }
782 else if (pidClass != "fan")
783 {
784 if (std::find(missingAcceptableSensorNames.begin(),
785 missingAcceptableSensorNames.end(),
786 sensorName) ==
787 missingAcceptableSensorNames.end())
788 {
789 std::cerr
790 << "Pid controller: Missing a missing-unacceptable sensor from D-Bus "
791 << sensorName << "\n";
792 std::string inputSensorName =
793 sensorNameToDbusName(sensorName);
794 auto& config = sensorConfig[inputSensorName];
795 archivedInputSensorNames.push_back(inputSensorName);
796 config.type = pidClass;
797 config.readPath =
798 getSensorPath(config.type, inputSensorName);
799 config.timeout = 0;
800 config.ignoreDbusMinMax = true;
801 config.unavailableAsFailed = unavailableAsFailed;
802 config.ignoreFailIfHostOff = ignoreFailIfHostOff;
803 }
804 else
805 {
806 // When an input sensor is NOT on DBus, and it's in
807 // the MissingIsAcceptable list. Ignore it and
808 // continue with the next input sensor.
809 std::cout
810 << "Pid controller: Missing a missing-acceptable sensor from D-Bus "
811 << sensorName << "\n";
812 continue;
813 }
814 }
815 #endif
816 }
817 for (const std::string& sensorName : outputSensorNames)
818 {
819 findSensors(sensors, sensorNameToDbusName(sensorName),
820 outputSensorInterfaces);
821 }
822 for (const std::string& sensorName :
823 missingAcceptableSensorNames)
824 {
825 findSensors(sensors, sensorNameToDbusName(sensorName),
826 missingAcceptableSensorInterfaces);
827 }
828
829 for (const SensorInterfaceType& inputSensorInterface :
830 inputSensorInterfaces)
831 {
832 const std::string& dbusInterface =
833 inputSensorInterface.second;
834 const std::string& inputSensorPath =
835 inputSensorInterface.first;
836
837 // Setting timeout to 0 is intentional, as D-Bus passive
838 // sensor updates are pushed in, not pulled by timer poll.
839 // Setting ignoreDbusMinMax is intentional, as this
840 // prevents normalization of values to [0.0, 1.0] range,
841 // which would mess up the PID loop math.
842 // All non-fan PID classes should be initialized this way.
843 // As for why a fan should not use this code path, see
844 // the ed1dafdf168def37c65bfb7a5efd18d9dbe04727 commit.
845 if ((pidClass == "temp") || (pidClass == "margin") ||
846 (pidClass == "power") || (pidClass == "powersum"))
847 {
848 std::string inputSensorName =
849 getSensorNameFromPath(inputSensorPath);
850 auto& config = sensorConfig[inputSensorName];
851 archivedInputSensorNames.push_back(inputSensorName);
852 config.type = pidClass;
853 config.readPath = inputSensorInterface.first;
854 config.timeout = 0;
855 config.ignoreDbusMinMax = true;
856 config.unavailableAsFailed = unavailableAsFailed;
857 config.ignoreFailIfHostOff = ignoreFailIfHostOff;
858 }
859
860 if (dbusInterface != SensorValue::interface)
861 {
862 /* all expected inputs in the configuration are expected
863 * to be sensor interfaces
864 */
865 throw std::runtime_error(std::format(
866 "sensor at dbus path [{}] has an interface [{}] that does not match the expected interface of {}",
867 inputSensorPath, dbusInterface,
868 SensorValue::interface));
869 }
870 }
871
872 // MissingIsAcceptable same postprocessing as Inputs
873 missingAcceptableSensorNames.clear();
874 for (const SensorInterfaceType&
875 missingAcceptableSensorInterface :
876 missingAcceptableSensorInterfaces)
877 {
878 const std::string& dbusInterface =
879 missingAcceptableSensorInterface.second;
880 const std::string& missingAcceptableSensorPath =
881 missingAcceptableSensorInterface.first;
882
883 std::string missingAcceptableSensorName =
884 getSensorNameFromPath(missingAcceptableSensorPath);
885 missingAcceptableSensorNames.push_back(
886 missingAcceptableSensorName);
887
888 if (dbusInterface != SensorValue::interface)
889 {
890 /* MissingIsAcceptable same error checking as Inputs
891 */
892 throw std::runtime_error(std::format(
893 "sensor at dbus path [{}] has an interface [{}] that does not match the expected interface of {}",
894 missingAcceptableSensorPath, dbusInterface,
895 SensorValue::interface));
896 }
897 }
898
899 /* fan pids need to pair up tach sensors with their pwm
900 * counterparts
901 */
902 if (pidClass == "fan")
903 {
904 /* If a PID is a fan there should be either
905 * (1) one output(pwm) per input(tach)
906 * OR
907 * (2) one putput(pwm) for all inputs(tach)
908 * everything else indicates a bad configuration.
909 */
910 bool singlePwm = false;
911 if (outputSensorInterfaces.size() == 1)
912 {
913 /* one pwm, set write paths for all fan sensors to it */
914 singlePwm = true;
915 }
916 else if (inputSensorInterfaces.size() ==
917 outputSensorInterfaces.size())
918 {
919 /* one to one mapping, each fan sensor gets its own pwm
920 * control */
921 singlePwm = false;
922 }
923 else
924 {
925 throw std::runtime_error(
926 "fan PID has invalid number of Outputs");
927 }
928 std::string fanSensorName;
929 std::string pwmPath;
930 std::string pwmInterface;
931 std::string pwmSensorName;
932 if (singlePwm)
933 {
934 /* if just a single output(pwm) is provided then use
935 * that pwm control path for all the fan sensor write
936 * path configs
937 */
938 pwmPath = outputSensorInterfaces.at(0).first;
939 pwmInterface = outputSensorInterfaces.at(0).second;
940 }
941 for (uint32_t idx = 0; idx < inputSensorInterfaces.size();
942 idx++)
943 {
944 if (!singlePwm)
945 {
946 pwmPath = outputSensorInterfaces.at(idx).first;
947 pwmInterface =
948 outputSensorInterfaces.at(idx).second;
949 }
950 if (ControlFanPwm::interface != pwmInterface)
951 {
952 throw std::runtime_error(std::format(
953 "fan pwm control at dbus path [{}] has an interface [{}] that does not match the expected interface of {}",
954 pwmPath, pwmInterface,
955 ControlFanPwm::interface));
956 }
957 const std::string& fanPath =
958 inputSensorInterfaces.at(idx).first;
959 fanSensorName = getSensorNameFromPath(fanPath);
960 pwmSensorName = getSensorNameFromPath(pwmPath);
961 std::string fanPwmIndex = fanSensorName + pwmSensorName;
962 archivedInputSensorNames.push_back(fanPwmIndex);
963 auto& fanConfig = sensorConfig[fanPwmIndex];
964 fanConfig.type = pidClass;
965 fanConfig.readPath = fanPath;
966 fanConfig.writePath = pwmPath;
967 // todo: un-hardcode this if there are fans with
968 // different ranges
969 fanConfig.max = 255;
970 fanConfig.min = 0;
971 }
972 }
973 // if the sensors aren't available in the current state, don't
974 // add them to the configuration.
975 if (archivedInputSensorNames.empty())
976 {
977 continue;
978 }
979
980 std::string offsetType;
981
982 // SetPointOffset is a threshold value to pull from the sensor
983 // to apply an offset. For upper thresholds this means the
984 // setpoint is usually negative.
985 auto findSetpointOffset = base.find("SetPointOffset");
986 if (findSetpointOffset != base.end())
987 {
988 offsetType =
989 std::get<std::string>(findSetpointOffset->second);
990 if (std::find(thresholds::types.begin(),
991 thresholds::types.end(), offsetType) ==
992 thresholds::types.end())
993 {
994 throw std::runtime_error(
995 "Unsupported type: " + offsetType);
996 }
997 }
998
999 std::vector<double> inputTempToMargin;
1000
1001 auto findTempToMargin = base.find("TempToMargin");
1002 if (findTempToMargin != base.end())
1003 {
1004 inputTempToMargin =
1005 std::get<std::vector<double>>(findTempToMargin->second);
1006 }
1007
1008 std::vector<pid_control::conf::SensorInput> sensorInputs =
1009 spliceInputs(archivedInputSensorNames, inputTempToMargin,
1010 missingAcceptableSensorNames);
1011
1012 if (offsetType.empty())
1013 {
1014 conf::ControllerInfo& info = conf[pidName];
1015 info.inputs = std::move(sensorInputs);
1016 populatePidInfo(bus, base, info, nullptr, sensorConfig);
1017 }
1018 else
1019 {
1020 // we have to split up the inputs, as in practice t-control
1021 // values will differ, making setpoints differ
1022 for (const pid_control::conf::SensorInput& input :
1023 sensorInputs)
1024 {
1025 conf::ControllerInfo& info = conf[input.name];
1026 info.inputs.emplace_back(input);
1027 populatePidInfo(bus, base, info, &offsetType,
1028 sensorConfig);
1029 }
1030 }
1031 }
1032 }
1033 auto findStepwise =
1034 configuration.second.find(stepwiseConfigurationInterface);
1035 if (findStepwise != configuration.second.end())
1036 {
1037 const auto& base = findStepwise->second;
1038 const std::string pidName =
1039 sensorNameToDbusName(std::get<std::string>(base.at("Name")));
1040 const std::vector<std::string>& zones =
1041 std::get<std::vector<std::string>>(base.at("Zones"));
1042 for (const std::string& zone : zones)
1043 {
1044 auto index = getZoneIndex(zone, foundZones);
1045
1046 conf::PIDConf& conf = zoneConfig[index];
1047
1048 std::vector<std::string> inputs;
1049 std::vector<std::string> missingAcceptableSensors;
1050 std::vector<std::string> missingAcceptableSensorNames;
1051 std::vector<std::string> sensorNames =
1052 std::get<std::vector<std::string>>(base.at("Inputs"));
1053
1054 auto findMissingAcceptable = base.find("MissingIsAcceptable");
1055 if (findMissingAcceptable != base.end())
1056 {
1057 missingAcceptableSensorNames =
1058 std::get<std::vector<std::string>>(
1059 findMissingAcceptable->second);
1060 }
1061
1062 bool unavailableAsFailed = true;
1063 auto findUnavailableAsFailed =
1064 base.find("InputUnavailableAsFailed");
1065 if (findUnavailableAsFailed != base.end())
1066 {
1067 unavailableAsFailed =
1068 std::get<bool>(findUnavailableAsFailed->second);
1069 }
1070
1071 bool ignoreFailIfHostOff = false;
1072 auto findIgnoreFailIfHostOff = base.find("IgnoreFailIfHostOff");
1073 if (findIgnoreFailIfHostOff != base.end())
1074 {
1075 ignoreFailIfHostOff =
1076 std::get<bool>(findIgnoreFailIfHostOff->second);
1077 }
1078
1079 bool sensorFound = false;
1080 for (const std::string& sensorName : sensorNames)
1081 {
1082 std::vector<std::pair<std::string, std::string>>
1083 sensorPathIfacePairs;
1084 if (!findSensors(sensors, sensorNameToDbusName(sensorName),
1085 sensorPathIfacePairs))
1086 {
1087 #ifndef HANDLE_MISSING_OBJECT_PATHS
1088 break;
1089 #else
1090 if (std::find(missingAcceptableSensorNames.begin(),
1091 missingAcceptableSensorNames.end(),
1092 sensorName) ==
1093 missingAcceptableSensorNames.end())
1094 {
1095 // When an input sensor is NOT on DBus, and it's NOT
1096 // in the MissingIsAcceptable list. Build it as a
1097 // failed sensor with default information (temp
1098 // sensor path, temp type, ...)
1099 std::cerr
1100 << "Stepwise controller: Missing a missing-unacceptable sensor from D-Bus "
1101 << sensorName << "\n";
1102 std::string shortName =
1103 sensorNameToDbusName(sensorName);
1104
1105 inputs.push_back(shortName);
1106 auto& config = sensorConfig[shortName];
1107 config.type = "temp";
1108 config.readPath =
1109 getSensorPath(config.type, shortName);
1110 config.ignoreDbusMinMax = true;
1111 config.unavailableAsFailed = unavailableAsFailed;
1112 config.ignoreFailIfHostOff = ignoreFailIfHostOff;
1113 // todo: maybe un-hardcode this if we run into
1114 // slower timeouts with sensors
1115
1116 config.timeout = 0;
1117 sensorFound = true;
1118 }
1119 else
1120 {
1121 // When an input sensor is NOT on DBus, and it's in
1122 // the MissingIsAcceptable list. Ignore it and
1123 // continue with the next input sensor.
1124 std::cout
1125 << "Stepwise controller: Missing a missing-acceptable sensor from D-Bus "
1126 << sensorName << "\n";
1127 continue;
1128 }
1129 #endif
1130 }
1131 else
1132 {
1133 for (const auto& sensorPathIfacePair :
1134 sensorPathIfacePairs)
1135 {
1136 std::string shortName = getSensorNameFromPath(
1137 sensorPathIfacePair.first);
1138
1139 inputs.push_back(shortName);
1140 auto& config = sensorConfig[shortName];
1141 config.readPath = sensorPathIfacePair.first;
1142 config.type = "temp";
1143 config.ignoreDbusMinMax = true;
1144 config.unavailableAsFailed = unavailableAsFailed;
1145 config.ignoreFailIfHostOff = ignoreFailIfHostOff;
1146 // todo: maybe un-hardcode this if we run into
1147 // slower timeouts with sensors
1148
1149 config.timeout = 0;
1150 sensorFound = true;
1151 }
1152 }
1153 }
1154 if (!sensorFound)
1155 {
1156 continue;
1157 }
1158
1159 // MissingIsAcceptable same postprocessing as Inputs
1160 for (const std::string& missingAcceptableSensorName :
1161 missingAcceptableSensorNames)
1162 {
1163 std::vector<std::pair<std::string, std::string>>
1164 sensorPathIfacePairs;
1165 if (!findSensors(
1166 sensors,
1167 sensorNameToDbusName(missingAcceptableSensorName),
1168 sensorPathIfacePairs))
1169 {
1170 #ifndef HANDLE_MISSING_OBJECT_PATHS
1171 break;
1172 #else
1173 // When a sensor in the MissingIsAcceptable list is NOT
1174 // on DBus and it still reaches here, which contradicts
1175 // to what we did in the Input sensor building step.
1176 // Continue.
1177 continue;
1178 #endif
1179 }
1180
1181 for (const auto& sensorPathIfacePair : sensorPathIfacePairs)
1182 {
1183 std::string shortName =
1184 getSensorNameFromPath(sensorPathIfacePair.first);
1185
1186 missingAcceptableSensors.push_back(shortName);
1187 }
1188 }
1189
1190 conf::ControllerInfo& info = conf[pidName];
1191
1192 std::vector<double> inputTempToMargin;
1193
1194 auto findTempToMargin = base.find("TempToMargin");
1195 if (findTempToMargin != base.end())
1196 {
1197 inputTempToMargin =
1198 std::get<std::vector<double>>(findTempToMargin->second);
1199 }
1200
1201 info.inputs = spliceInputs(inputs, inputTempToMargin,
1202 missingAcceptableSensors);
1203
1204 info.type = "stepwise";
1205 info.stepwiseInfo.ts = 1.0; // currently unused
1206 info.stepwiseInfo.positiveHysteresis = 0.0;
1207 info.stepwiseInfo.negativeHysteresis = 0.0;
1208 std::string subtype = std::get<std::string>(base.at("Class"));
1209
1210 info.stepwiseInfo.isCeiling = (subtype == "Ceiling");
1211 auto findPosHyst = base.find("PositiveHysteresis");
1212 auto findNegHyst = base.find("NegativeHysteresis");
1213 if (findPosHyst != base.end())
1214 {
1215 info.stepwiseInfo.positiveHysteresis = std::visit(
1216 VariantToDoubleVisitor(), findPosHyst->second);
1217 }
1218 if (findNegHyst != base.end())
1219 {
1220 info.stepwiseInfo.negativeHysteresis = std::visit(
1221 VariantToDoubleVisitor(), findNegHyst->second);
1222 }
1223 std::vector<double> readings =
1224 std::get<std::vector<double>>(base.at("Reading"));
1225 if (readings.size() > ec::maxStepwisePoints)
1226 {
1227 throw std::invalid_argument("Too many stepwise points.");
1228 }
1229 if (readings.empty())
1230 {
1231 throw std::invalid_argument(
1232 "Must have one stepwise point.");
1233 }
1234 std::copy(readings.begin(), readings.end(),
1235 info.stepwiseInfo.reading);
1236 if (readings.size() < ec::maxStepwisePoints)
1237 {
1238 info.stepwiseInfo.reading[readings.size()] =
1239 std::numeric_limits<double>::quiet_NaN();
1240 }
1241 std::vector<double> outputs =
1242 std::get<std::vector<double>>(base.at("Output"));
1243 if (readings.size() != outputs.size())
1244 {
1245 throw std::invalid_argument(
1246 "Outputs size must match readings");
1247 }
1248 std::copy(outputs.begin(), outputs.end(),
1249 info.stepwiseInfo.output);
1250 if (outputs.size() < ec::maxStepwisePoints)
1251 {
1252 info.stepwiseInfo.output[outputs.size()] =
1253 std::numeric_limits<double>::quiet_NaN();
1254 }
1255 }
1256 }
1257 }
1258 if constexpr (pid_control::conf::DEBUG)
1259 {
1260 debugPrint(sensorConfig, zoneConfig, zoneDetailsConfig);
1261 }
1262 if (zoneConfig.empty() || zoneDetailsConfig.empty())
1263 {
1264 std::cerr
1265 << "No fan zones, application pausing until new configuration\n";
1266 return false;
1267 }
1268 return true;
1269 }
1270
1271 } // namespace dbus_configuration
1272 } // namespace pid_control
1273