blob: 1cd55b8dc6beef69683053a062c09a6878dc6990 [file] [log] [blame]
James Feistbc896df2018-11-26 16:28:17 -08001/*
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
Ed Tanous8a57ec02020-10-09 12:46:52 -070017#include <ExitAirTempSensor.hpp>
18#include <Utils.hpp>
19#include <VariantVisitors.hpp>
James Feistbc896df2018-11-26 16:28:17 -080020#include <boost/algorithm/string/predicate.hpp>
21#include <boost/algorithm/string/replace.hpp>
Patrick Venture96e97db2019-10-31 13:44:38 -070022#include <boost/container/flat_map.hpp>
James Feist38fb5982020-05-28 10:09:54 -070023#include <sdbusplus/asio/connection.hpp>
24#include <sdbusplus/asio/object_server.hpp>
25#include <sdbusplus/bus/match.hpp>
26
27#include <array>
James Feistbc896df2018-11-26 16:28:17 -080028#include <chrono>
Patrick Venture96e97db2019-10-31 13:44:38 -070029#include <cmath>
30#include <functional>
James Feistbc896df2018-11-26 16:28:17 -080031#include <iostream>
32#include <limits>
Patrick Venture96e97db2019-10-31 13:44:38 -070033#include <memory>
James Feistbc896df2018-11-26 16:28:17 -080034#include <numeric>
Patrick Venture96e97db2019-10-31 13:44:38 -070035#include <stdexcept>
36#include <utility>
37#include <variant>
James Feistbc896df2018-11-26 16:28:17 -080038#include <vector>
39
Ed Tanous8a57ec02020-10-09 12:46:52 -070040constexpr const double altitudeFactor = 1.14;
James Feistbc896df2018-11-26 16:28:17 -080041constexpr const char* exitAirIface =
42 "xyz.openbmc_project.Configuration.ExitAirTempSensor";
43constexpr const char* cfmIface = "xyz.openbmc_project.Configuration.CFMSensor";
44
45// todo: this *might* need to be configurable
46constexpr const char* inletTemperatureSensor = "temperature/Front_Panel_Temp";
James Feist13452092019-03-07 16:38:12 -080047constexpr const char* pidConfigurationType =
48 "xyz.openbmc_project.Configuration.Pid";
49constexpr const char* settingsDaemon = "xyz.openbmc_project.Settings";
50constexpr const char* cfmSettingPath = "/xyz/openbmc_project/control/cfm_limit";
51constexpr const char* cfmSettingIface = "xyz.openbmc_project.Control.CFMLimit";
James Feistbc896df2018-11-26 16:28:17 -080052
Ed Tanous8a57ec02020-10-09 12:46:52 -070053static constexpr bool debug = false;
James Feistbc896df2018-11-26 16:28:17 -080054
James Feistb2eb3f52018-12-04 16:17:50 -080055static constexpr double cfmMaxReading = 255;
56static constexpr double cfmMinReading = 0;
57
James Feist13452092019-03-07 16:38:12 -080058static constexpr size_t minSystemCfm = 50;
59
James Feist655f3762020-10-05 15:28:15 -070060constexpr const std::array<const char*, 2> monitorIfaces = {exitAirIface,
61 cfmIface};
62
James Feist9a25ed42019-10-15 15:43:44 -070063static std::vector<std::shared_ptr<CFMSensor>> cfmSensors;
64
James Feistb2eb3f52018-12-04 16:17:50 -080065static void setupSensorMatch(
66 std::vector<sdbusplus::bus::match::match>& matches,
67 sdbusplus::bus::bus& connection, const std::string& type,
68 std::function<void(const double&, sdbusplus::message::message&)>&& callback)
69{
70
71 std::function<void(sdbusplus::message::message & message)> eventHandler =
72 [callback{std::move(callback)}](sdbusplus::message::message& message) {
73 std::string objectName;
James Feist3eb82622019-02-08 13:10:22 -080074 boost::container::flat_map<std::string,
75 std::variant<double, int64_t>>
James Feistb2eb3f52018-12-04 16:17:50 -080076 values;
77 message.read(objectName, values);
78 auto findValue = values.find("Value");
79 if (findValue == values.end())
80 {
81 return;
82 }
James Feist3eb82622019-02-08 13:10:22 -080083 double value =
84 std::visit(VariantToDoubleVisitor(), findValue->second);
James Feist9566bfa2019-01-29 15:31:23 -080085 if (std::isnan(value))
86 {
87 return;
88 }
89
James Feistb2eb3f52018-12-04 16:17:50 -080090 callback(value, message);
91 };
92 matches.emplace_back(connection,
93 "type='signal',"
94 "member='PropertiesChanged',interface='org."
95 "freedesktop.DBus.Properties',path_"
96 "namespace='/xyz/openbmc_project/sensors/" +
97 std::string(type) +
98 "',arg0='xyz.openbmc_project.Sensor.Value'",
99 std::move(eventHandler));
100}
101
James Feist13452092019-03-07 16:38:12 -0800102static void setMaxPWM(const std::shared_ptr<sdbusplus::asio::connection>& conn,
103 double value)
104{
105 using GetSubTreeType = std::vector<std::pair<
106 std::string,
107 std::vector<std::pair<std::string, std::vector<std::string>>>>>;
108
109 conn->async_method_call(
110 [conn, value](const boost::system::error_code ec,
111 const GetSubTreeType& ret) {
112 if (ec)
113 {
114 std::cerr << "Error calling mapper\n";
115 return;
116 }
117 for (const auto& [path, objDict] : ret)
118 {
119 if (objDict.empty())
120 {
121 return;
122 }
123 const std::string& owner = objDict.begin()->first;
124
125 conn->async_method_call(
126 [conn, value, owner,
Ed Tanous8a57ec02020-10-09 12:46:52 -0700127 path{path}](const boost::system::error_code ec,
128 const std::variant<std::string>& classType) {
James Feist13452092019-03-07 16:38:12 -0800129 if (ec)
130 {
131 std::cerr << "Error getting pid class\n";
132 return;
133 }
134 auto classStr = std::get_if<std::string>(&classType);
135 if (classStr == nullptr || *classStr != "fan")
136 {
137 return;
138 }
139 conn->async_method_call(
140 [](boost::system::error_code& ec) {
141 if (ec)
142 {
143 std::cerr << "Error setting pid class\n";
144 return;
145 }
146 },
147 owner, path, "org.freedesktop.DBus.Properties",
148 "Set", pidConfigurationType, "OutLimitMax",
149 std::variant<double>(value));
150 },
151 owner, path, "org.freedesktop.DBus.Properties", "Get",
152 pidConfigurationType, "Class");
153 }
154 },
James Feista5e58722019-04-22 14:43:11 -0700155 mapper::busName, mapper::path, mapper::interface, mapper::subtree, "/",
156 0, std::array<std::string, 1>{pidConfigurationType});
James Feist13452092019-03-07 16:38:12 -0800157}
158
James Feistb2eb3f52018-12-04 16:17:50 -0800159CFMSensor::CFMSensor(std::shared_ptr<sdbusplus::asio::connection>& conn,
160 const std::string& sensorName,
161 const std::string& sensorConfiguration,
162 sdbusplus::asio::object_server& objectServer,
James Feistb839c052019-05-15 10:25:24 -0700163 std::vector<thresholds::Threshold>&& thresholdData,
James Feistb2eb3f52018-12-04 16:17:50 -0800164 std::shared_ptr<ExitAirTempSensor>& parent) :
165 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
James Feist930fcde2019-05-28 12:58:43 -0700166 std::move(thresholdData), sensorConfiguration,
Bruce Lee1263c3d2021-06-04 15:16:33 +0800167 "xyz.openbmc_project.Configuration.ExitAirTemp", false,
168 cfmMaxReading, cfmMinReading, conn, PowerState::on),
Brad Bishopfbb44ad2019-11-08 09:42:37 -0500169 std::enable_shared_from_this<CFMSensor>(), parent(parent),
James Feiste3338522020-09-15 15:40:30 -0700170 objServer(objectServer)
James Feistb2eb3f52018-12-04 16:17:50 -0800171{
172 sensorInterface =
173 objectServer.add_interface("/xyz/openbmc_project/sensors/cfm/" + name,
174 "xyz.openbmc_project.Sensor.Value");
175
176 if (thresholds::hasWarningInterface(thresholds))
177 {
178 thresholdInterfaceWarning = objectServer.add_interface(
179 "/xyz/openbmc_project/sensors/cfm/" + name,
180 "xyz.openbmc_project.Sensor.Threshold.Warning");
181 }
182 if (thresholds::hasCriticalInterface(thresholds))
183 {
184 thresholdInterfaceCritical = objectServer.add_interface(
185 "/xyz/openbmc_project/sensors/cfm/" + name,
186 "xyz.openbmc_project.Sensor.Threshold.Critical");
187 }
James Feist078f2322019-03-08 11:09:05 -0800188
189 association = objectServer.add_interface(
James Feist2adc95c2019-09-30 14:55:28 -0700190 "/xyz/openbmc_project/sensors/cfm/" + name, association::interface);
James Feist078f2322019-03-08 11:09:05 -0800191
Zev Weiss6b6891c2021-04-22 02:46:21 -0500192 setInitialProperties(conn, sensor_paths::unitCFM);
James Feist9a25ed42019-10-15 15:43:44 -0700193
James Feist13452092019-03-07 16:38:12 -0800194 pwmLimitIface =
195 objectServer.add_interface("/xyz/openbmc_project/control/pwm_limit",
196 "xyz.openbmc_project.Control.PWMLimit");
197 cfmLimitIface =
198 objectServer.add_interface("/xyz/openbmc_project/control/MaxCFM",
199 "xyz.openbmc_project.Control.CFMLimit");
James Feist9a25ed42019-10-15 15:43:44 -0700200}
James Feist13452092019-03-07 16:38:12 -0800201
James Feist9a25ed42019-10-15 15:43:44 -0700202void CFMSensor::setupMatches()
203{
204
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700205 std::weak_ptr<CFMSensor> weakRef = weak_from_this();
James Feist9a25ed42019-10-15 15:43:44 -0700206 setupSensorMatch(matches, *dbusConnection, "fan_tach",
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700207 std::move([weakRef](const double& value,
208 sdbusplus::message::message& message) {
209 auto self = weakRef.lock();
210 if (!self)
211 {
212 return;
213 }
James Feist9a25ed42019-10-15 15:43:44 -0700214 self->tachReadings[message.get_path()] = value;
215 if (self->tachRanges.find(message.get_path()) ==
216 self->tachRanges.end())
217 {
218 // calls update reading after updating ranges
219 self->addTachRanges(message.get_sender(),
220 message.get_path());
221 }
222 else
223 {
224 self->updateReading();
225 }
226 }));
227
228 dbusConnection->async_method_call(
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700229 [weakRef](const boost::system::error_code ec,
230 const std::variant<double> cfmVariant) {
231 auto self = weakRef.lock();
232 if (!self)
233 {
234 return;
235 }
236
James Feist13452092019-03-07 16:38:12 -0800237 uint64_t maxRpm = 100;
238 if (!ec)
239 {
240
241 auto cfm = std::get_if<double>(&cfmVariant);
Josh Lehanff336992020-02-26 11:13:19 -0800242 if (cfm != nullptr && *cfm >= minSystemCfm)
James Feist13452092019-03-07 16:38:12 -0800243 {
James Feist9a25ed42019-10-15 15:43:44 -0700244 maxRpm = self->getMaxRpm(*cfm);
James Feist13452092019-03-07 16:38:12 -0800245 }
246 }
James Feist9a25ed42019-10-15 15:43:44 -0700247 self->pwmLimitIface->register_property("Limit", maxRpm);
248 self->pwmLimitIface->initialize();
249 setMaxPWM(self->dbusConnection, maxRpm);
James Feist13452092019-03-07 16:38:12 -0800250 },
251 settingsDaemon, cfmSettingPath, "org.freedesktop.DBus.Properties",
252 "Get", cfmSettingIface, "Limit");
253
254 matches.emplace_back(
James Feist9a25ed42019-10-15 15:43:44 -0700255 *dbusConnection,
James Feist13452092019-03-07 16:38:12 -0800256 "type='signal',"
257 "member='PropertiesChanged',interface='org."
258 "freedesktop.DBus.Properties',path='" +
259 std::string(cfmSettingPath) + "',arg0='" +
260 std::string(cfmSettingIface) + "'",
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700261 [weakRef](sdbusplus::message::message& message) {
262 auto self = weakRef.lock();
263 if (!self)
264 {
265 return;
266 }
James Feist13452092019-03-07 16:38:12 -0800267 boost::container::flat_map<std::string, std::variant<double>>
268 values;
269 std::string objectName;
270 message.read(objectName, values);
271 const auto findValue = values.find("Limit");
272 if (findValue == values.end())
273 {
274 return;
275 }
276 const auto reading = std::get_if<double>(&(findValue->second));
277 if (reading == nullptr)
278 {
279 std::cerr << "Got CFM Limit of wrong type\n";
280 return;
281 }
282 if (*reading < minSystemCfm && *reading != 0)
283 {
284 std::cerr << "Illegal CFM setting detected\n";
285 return;
286 }
James Feist9a25ed42019-10-15 15:43:44 -0700287 uint64_t maxRpm = self->getMaxRpm(*reading);
288 self->pwmLimitIface->set_property("Limit", maxRpm);
289 setMaxPWM(self->dbusConnection, maxRpm);
James Feist13452092019-03-07 16:38:12 -0800290 });
James Feistb2eb3f52018-12-04 16:17:50 -0800291}
292
James Feist9566bfa2019-01-29 15:31:23 -0800293CFMSensor::~CFMSensor()
294{
295 objServer.remove_interface(thresholdInterfaceWarning);
296 objServer.remove_interface(thresholdInterfaceCritical);
297 objServer.remove_interface(sensorInterface);
James Feist078f2322019-03-08 11:09:05 -0800298 objServer.remove_interface(association);
James Feist13452092019-03-07 16:38:12 -0800299 objServer.remove_interface(cfmLimitIface);
300 objServer.remove_interface(pwmLimitIface);
301}
302
303void CFMSensor::createMaxCFMIface(void)
304{
James Feistb6c0b912019-07-09 12:21:44 -0700305 cfmLimitIface->register_property("Limit", c2 * maxCFM * tachs.size());
James Feist13452092019-03-07 16:38:12 -0800306 cfmLimitIface->initialize();
James Feist9566bfa2019-01-29 15:31:23 -0800307}
308
James Feistb2eb3f52018-12-04 16:17:50 -0800309void CFMSensor::addTachRanges(const std::string& serviceName,
310 const std::string& path)
311{
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700312 std::weak_ptr<CFMSensor> weakRef = weak_from_this();
James Feistb2eb3f52018-12-04 16:17:50 -0800313 dbusConnection->async_method_call(
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700314 [weakRef,
315 path](const boost::system::error_code ec,
316 const boost::container::flat_map<std::string, BasicVariantType>&
317 data) {
James Feistb2eb3f52018-12-04 16:17:50 -0800318 if (ec)
319 {
320 std::cerr << "Error getting properties from " << path << "\n";
James Feist1ccdb5e2019-01-24 09:44:01 -0800321 return;
James Feistb2eb3f52018-12-04 16:17:50 -0800322 }
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700323 auto self = weakRef.lock();
324 if (!self)
325 {
326 return;
327 }
James Feistb2eb3f52018-12-04 16:17:50 -0800328 double max = loadVariant<double>(data, "MaxValue");
329 double min = loadVariant<double>(data, "MinValue");
James Feist9a25ed42019-10-15 15:43:44 -0700330 self->tachRanges[path] = std::make_pair(min, max);
331 self->updateReading();
James Feistb2eb3f52018-12-04 16:17:50 -0800332 },
333 serviceName, path, "org.freedesktop.DBus.Properties", "GetAll",
334 "xyz.openbmc_project.Sensor.Value");
335}
336
337void CFMSensor::checkThresholds(void)
338{
339 thresholds::checkThresholds(this);
340}
341
342void CFMSensor::updateReading(void)
343{
344 double val = 0.0;
345 if (calculate(val))
346 {
347 if (value != val && parent)
348 {
349 parent->updateReading();
350 }
351 updateValue(val);
352 }
353 else
354 {
355 updateValue(std::numeric_limits<double>::quiet_NaN());
356 }
357}
358
James Feist13452092019-03-07 16:38:12 -0800359uint64_t CFMSensor::getMaxRpm(uint64_t cfmMaxSetting)
360{
361 uint64_t pwmPercent = 100;
362 double totalCFM = std::numeric_limits<double>::max();
363 if (cfmMaxSetting == 0)
364 {
365 return pwmPercent;
366 }
367
James Feist52427952019-04-05 14:23:35 -0700368 bool firstLoop = true;
James Feist13452092019-03-07 16:38:12 -0800369 while (totalCFM > cfmMaxSetting)
370 {
James Feist52427952019-04-05 14:23:35 -0700371 if (firstLoop)
372 {
373 firstLoop = false;
374 }
375 else
376 {
377 pwmPercent--;
378 }
379
James Feist13452092019-03-07 16:38:12 -0800380 double ci = 0;
381 if (pwmPercent == 0)
382 {
383 ci = 0;
384 }
385 else if (pwmPercent < tachMinPercent)
386 {
387 ci = c1;
388 }
389 else if (pwmPercent > tachMaxPercent)
390 {
391 ci = c2;
392 }
393 else
394 {
395 ci = c1 + (((c2 - c1) * (pwmPercent - tachMinPercent)) /
396 (tachMaxPercent - tachMinPercent));
397 }
398
399 // Now calculate the CFM for this tach
400 // CFMi = Ci * Qmaxi * TACHi
401 totalCFM = ci * maxCFM * pwmPercent;
402 totalCFM *= tachs.size();
403 // divide by 100 since pwm is in percent
404 totalCFM /= 100;
405
James Feist13452092019-03-07 16:38:12 -0800406 if (pwmPercent <= 0)
407 {
408 break;
409 }
410 }
James Feist52427952019-04-05 14:23:35 -0700411
James Feist13452092019-03-07 16:38:12 -0800412 return pwmPercent;
413}
414
James Feistb2eb3f52018-12-04 16:17:50 -0800415bool CFMSensor::calculate(double& value)
416{
417 double totalCFM = 0;
418 for (const std::string& tachName : tachs)
419 {
James Feist9566bfa2019-01-29 15:31:23 -0800420
James Feistb2eb3f52018-12-04 16:17:50 -0800421 auto findReading = std::find_if(
422 tachReadings.begin(), tachReadings.end(), [&](const auto& item) {
423 return boost::ends_with(item.first, tachName);
424 });
425 auto findRange = std::find_if(
426 tachRanges.begin(), tachRanges.end(), [&](const auto& item) {
427 return boost::ends_with(item.first, tachName);
428 });
429 if (findReading == tachReadings.end())
430 {
Ed Tanous8a57ec02020-10-09 12:46:52 -0700431 if constexpr (debug)
James Feista96329f2019-01-24 10:08:27 -0800432 {
433 std::cerr << "Can't find " << tachName << "in readings\n";
434 }
James Feist9566bfa2019-01-29 15:31:23 -0800435 continue; // haven't gotten a reading
James Feistb2eb3f52018-12-04 16:17:50 -0800436 }
437
438 if (findRange == tachRanges.end())
439 {
James Feist523828e2019-03-04 14:38:37 -0800440 std::cerr << "Can't find " << tachName << " in ranges\n";
James Feistb2eb3f52018-12-04 16:17:50 -0800441 return false; // haven't gotten a max / min
442 }
443
444 // avoid divide by 0
445 if (findRange->second.second == 0)
446 {
447 std::cerr << "Tach Max Set to 0 " << tachName << "\n";
448 return false;
449 }
450
451 double rpm = findReading->second;
452
453 // for now assume the min for a fan is always 0, divide by max to get
454 // percent and mult by 100
455 rpm /= findRange->second.second;
456 rpm *= 100;
457
Ed Tanous8a57ec02020-10-09 12:46:52 -0700458 if constexpr (debug)
James Feistb2eb3f52018-12-04 16:17:50 -0800459 {
460 std::cout << "Tach " << tachName << "at " << rpm << "\n";
461 }
462
463 // Do a linear interpolation to get Ci
464 // Ci = C1 + (C2 - C1)/(RPM2 - RPM1) * (TACHi - TACH1)
465
466 double ci = 0;
467 if (rpm == 0)
468 {
469 ci = 0;
470 }
471 else if (rpm < tachMinPercent)
472 {
473 ci = c1;
474 }
475 else if (rpm > tachMaxPercent)
476 {
477 ci = c2;
478 }
479 else
480 {
481 ci = c1 + (((c2 - c1) * (rpm - tachMinPercent)) /
482 (tachMaxPercent - tachMinPercent));
483 }
484
485 // Now calculate the CFM for this tach
486 // CFMi = Ci * Qmaxi * TACHi
487 totalCFM += ci * maxCFM * rpm;
Ed Tanous8a57ec02020-10-09 12:46:52 -0700488 if constexpr (debug)
James Feista5e58722019-04-22 14:43:11 -0700489 {
490 std::cerr << "totalCFM = " << totalCFM << "\n";
491 std::cerr << "Ci " << ci << " MaxCFM " << maxCFM << " rpm " << rpm
492 << "\n";
493 std::cerr << "c1 " << c1 << " c2 " << c2 << " max "
494 << tachMaxPercent << " min " << tachMinPercent << "\n";
495 }
James Feistb2eb3f52018-12-04 16:17:50 -0800496 }
497
498 // divide by 100 since rpm is in percent
499 value = totalCFM / 100;
Ed Tanous8a57ec02020-10-09 12:46:52 -0700500 if constexpr (debug)
James Feista5e58722019-04-22 14:43:11 -0700501 {
502 std::cerr << "cfm value = " << value << "\n";
503 }
James Feist9566bfa2019-01-29 15:31:23 -0800504 return true;
James Feistb2eb3f52018-12-04 16:17:50 -0800505}
506
507static constexpr double exitAirMaxReading = 127;
508static constexpr double exitAirMinReading = -128;
James Feistbc896df2018-11-26 16:28:17 -0800509ExitAirTempSensor::ExitAirTempSensor(
510 std::shared_ptr<sdbusplus::asio::connection>& conn,
James Feistb2eb3f52018-12-04 16:17:50 -0800511 const std::string& sensorName, const std::string& sensorConfiguration,
James Feistbc896df2018-11-26 16:28:17 -0800512 sdbusplus::asio::object_server& objectServer,
James Feistb839c052019-05-15 10:25:24 -0700513 std::vector<thresholds::Threshold>&& thresholdData) :
James Feistb2eb3f52018-12-04 16:17:50 -0800514 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
James Feist930fcde2019-05-28 12:58:43 -0700515 std::move(thresholdData), sensorConfiguration,
Bruce Lee1263c3d2021-06-04 15:16:33 +0800516 "xyz.openbmc_project.Configuration.ExitAirTemp", false,
517 exitAirMaxReading, exitAirMinReading, conn, PowerState::on),
James Feiste3338522020-09-15 15:40:30 -0700518 std::enable_shared_from_this<ExitAirTempSensor>(), objServer(objectServer)
James Feistbc896df2018-11-26 16:28:17 -0800519{
520 sensorInterface = objectServer.add_interface(
521 "/xyz/openbmc_project/sensors/temperature/" + name,
522 "xyz.openbmc_project.Sensor.Value");
523
524 if (thresholds::hasWarningInterface(thresholds))
525 {
526 thresholdInterfaceWarning = objectServer.add_interface(
527 "/xyz/openbmc_project/sensors/temperature/" + name,
528 "xyz.openbmc_project.Sensor.Threshold.Warning");
529 }
530 if (thresholds::hasCriticalInterface(thresholds))
531 {
532 thresholdInterfaceCritical = objectServer.add_interface(
533 "/xyz/openbmc_project/sensors/temperature/" + name,
534 "xyz.openbmc_project.Sensor.Threshold.Critical");
535 }
James Feist078f2322019-03-08 11:09:05 -0800536 association = objectServer.add_interface(
537 "/xyz/openbmc_project/sensors/temperature/" + name,
James Feist2adc95c2019-09-30 14:55:28 -0700538 association::interface);
Zev Weiss6b6891c2021-04-22 02:46:21 -0500539 setInitialProperties(conn, sensor_paths::unitDegreesC);
James Feistbc896df2018-11-26 16:28:17 -0800540}
541
542ExitAirTempSensor::~ExitAirTempSensor()
543{
James Feist523828e2019-03-04 14:38:37 -0800544 objServer.remove_interface(thresholdInterfaceWarning);
545 objServer.remove_interface(thresholdInterfaceCritical);
546 objServer.remove_interface(sensorInterface);
James Feist078f2322019-03-08 11:09:05 -0800547 objServer.remove_interface(association);
James Feistbc896df2018-11-26 16:28:17 -0800548}
549
550void ExitAirTempSensor::setupMatches(void)
551{
James Feistb2eb3f52018-12-04 16:17:50 -0800552 constexpr const std::array<const char*, 2> matchTypes = {
553 "power", inletTemperatureSensor};
James Feistbc896df2018-11-26 16:28:17 -0800554
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700555 std::weak_ptr<ExitAirTempSensor> weakRef = weak_from_this();
Ed Tanous13b63f82021-05-11 16:12:52 -0700556 for (const std::string type : matchTypes)
James Feistbc896df2018-11-26 16:28:17 -0800557 {
James Feistb2eb3f52018-12-04 16:17:50 -0800558 setupSensorMatch(matches, *dbusConnection, type,
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700559 [weakRef, type](const double& value,
560 sdbusplus::message::message& message) {
561 auto self = weakRef.lock();
562 if (!self)
563 {
564 return;
565 }
James Feistb2eb3f52018-12-04 16:17:50 -0800566 if (type == "power")
567 {
James Feista5e58722019-04-22 14:43:11 -0700568 std::string path = message.get_path();
569 if (path.find("PS") != std::string::npos &&
570 boost::ends_with(path, "Input_Power"))
571 {
James Feist9a25ed42019-10-15 15:43:44 -0700572 self->powerReadings[message.get_path()] =
573 value;
James Feista5e58722019-04-22 14:43:11 -0700574 }
James Feistb2eb3f52018-12-04 16:17:50 -0800575 }
576 else if (type == inletTemperatureSensor)
577 {
James Feist9a25ed42019-10-15 15:43:44 -0700578 self->inletTemp = value;
James Feistb2eb3f52018-12-04 16:17:50 -0800579 }
James Feist9a25ed42019-10-15 15:43:44 -0700580 self->updateReading();
James Feistb2eb3f52018-12-04 16:17:50 -0800581 });
James Feistbc896df2018-11-26 16:28:17 -0800582 }
James Feist9566bfa2019-01-29 15:31:23 -0800583 dbusConnection->async_method_call(
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700584 [weakRef](boost::system::error_code ec,
585 const std::variant<double>& value) {
James Feist9566bfa2019-01-29 15:31:23 -0800586 if (ec)
587 {
588 // sensor not ready yet
589 return;
590 }
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700591 auto self = weakRef.lock();
592 if (!self)
593 {
594 return;
595 }
James Feist9a25ed42019-10-15 15:43:44 -0700596 self->inletTemp = std::visit(VariantToDoubleVisitor(), value);
James Feist9566bfa2019-01-29 15:31:23 -0800597 },
598 "xyz.openbmc_project.HwmonTempSensor",
599 std::string("/xyz/openbmc_project/sensors/") + inletTemperatureSensor,
James Feista5e58722019-04-22 14:43:11 -0700600 properties::interface, properties::get, sensorValueInterface, "Value");
601 dbusConnection->async_method_call(
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700602 [weakRef](boost::system::error_code ec, const GetSubTreeType& subtree) {
James Feista5e58722019-04-22 14:43:11 -0700603 if (ec)
604 {
605 std::cerr << "Error contacting mapper\n";
606 return;
607 }
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700608 auto self = weakRef.lock();
609 if (!self)
610 {
611 return;
612 }
James Feista5e58722019-04-22 14:43:11 -0700613 for (const auto& item : subtree)
614 {
615 size_t lastSlash = item.first.rfind("/");
616 if (lastSlash == std::string::npos ||
617 lastSlash == item.first.size() || !item.second.size())
618 {
619 continue;
620 }
621 std::string sensorName = item.first.substr(lastSlash + 1);
622 if (boost::starts_with(sensorName, "PS") &&
623 boost::ends_with(sensorName, "Input_Power"))
624 {
625 const std::string& path = item.first;
James Feist9a25ed42019-10-15 15:43:44 -0700626 self->dbusConnection->async_method_call(
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700627 [weakRef, path](boost::system::error_code ec,
628 const std::variant<double>& value) {
James Feista5e58722019-04-22 14:43:11 -0700629 if (ec)
630 {
631 std::cerr << "Error getting value from " << path
632 << "\n";
633 }
Zhikui Rendbb73aa2021-04-02 13:39:04 -0700634 auto self = weakRef.lock();
635 if (!self)
636 {
637 return;
638 }
James Feista5e58722019-04-22 14:43:11 -0700639 double reading =
640 std::visit(VariantToDoubleVisitor(), value);
Ed Tanous8a57ec02020-10-09 12:46:52 -0700641 if constexpr (debug)
James Feista5e58722019-04-22 14:43:11 -0700642 {
643 std::cerr << path << "Reading " << reading
644 << "\n";
645 }
James Feist9a25ed42019-10-15 15:43:44 -0700646 self->powerReadings[path] = reading;
James Feista5e58722019-04-22 14:43:11 -0700647 },
648 item.second[0].first, item.first, properties::interface,
649 properties::get, sensorValueInterface, "Value");
650 }
651 }
652 },
653 mapper::busName, mapper::path, mapper::interface, mapper::subtree,
654 "/xyz/openbmc_project/sensors/power", 0,
655 std::array<const char*, 1>{sensorValueInterface});
James Feistbc896df2018-11-26 16:28:17 -0800656}
657
658void ExitAirTempSensor::updateReading(void)
659{
660
661 double val = 0.0;
662 if (calculate(val))
663 {
James Feist18af4232019-03-13 11:14:00 -0700664 val = std::floor(val + 0.5);
James Feistbc896df2018-11-26 16:28:17 -0800665 updateValue(val);
666 }
667 else
668 {
669 updateValue(std::numeric_limits<double>::quiet_NaN());
670 }
671}
672
James Feistb2eb3f52018-12-04 16:17:50 -0800673double ExitAirTempSensor::getTotalCFM(void)
James Feistbc896df2018-11-26 16:28:17 -0800674{
James Feistb2eb3f52018-12-04 16:17:50 -0800675 double sum = 0;
676 for (auto& sensor : cfmSensors)
James Feistbc896df2018-11-26 16:28:17 -0800677 {
James Feistb2eb3f52018-12-04 16:17:50 -0800678 double reading = 0;
679 if (!sensor->calculate(reading))
James Feistbc896df2018-11-26 16:28:17 -0800680 {
James Feistbc896df2018-11-26 16:28:17 -0800681 return -1;
682 }
James Feistb2eb3f52018-12-04 16:17:50 -0800683 sum += reading;
James Feistbc896df2018-11-26 16:28:17 -0800684 }
James Feistb2eb3f52018-12-04 16:17:50 -0800685
686 return sum;
James Feistbc896df2018-11-26 16:28:17 -0800687}
688
689bool ExitAirTempSensor::calculate(double& val)
690{
Zhikui Ren12e3d672020-12-03 15:14:49 -0800691 constexpr size_t maxErrorPrint = 5;
James Feistbc896df2018-11-26 16:28:17 -0800692 static bool firstRead = false;
James Feistae11cfc2019-05-07 15:01:20 -0700693 static size_t errorPrint = maxErrorPrint;
694
James Feistbc896df2018-11-26 16:28:17 -0800695 double cfm = getTotalCFM();
696 if (cfm <= 0)
697 {
698 std::cerr << "Error getting cfm\n";
699 return false;
700 }
701
Zhikui Ren12e3d672020-12-03 15:14:49 -0800702 // Though cfm is not expected to be less than qMin normally,
703 // it is not a hard limit for exit air temp calculation.
704 // 50% qMin is chosen as a generic limit between providing
705 // a valid derived exit air temp and reporting exit air temp not available.
706 constexpr const double cfmLimitFactor = 0.5;
707 if (cfm < (qMin * cfmLimitFactor))
708 {
709 if (errorPrint > 0)
710 {
711 errorPrint--;
712 std::cerr << "cfm " << cfm << " is too low, expected qMin " << qMin
713 << "\n";
714 }
715 val = 0;
716 return false;
717 }
718
James Feistbc896df2018-11-26 16:28:17 -0800719 // if there is an error getting inlet temp, return error
720 if (std::isnan(inletTemp))
721 {
James Feistae11cfc2019-05-07 15:01:20 -0700722 if (errorPrint > 0)
723 {
724 errorPrint--;
725 std::cerr << "Cannot get inlet temp\n";
726 }
James Feistbc896df2018-11-26 16:28:17 -0800727 val = 0;
728 return false;
729 }
730
731 // if fans are off, just make the exit temp equal to inlet
James Feist71d31b22019-01-02 16:57:54 -0800732 if (!isPowerOn())
James Feistbc896df2018-11-26 16:28:17 -0800733 {
734 val = inletTemp;
735 return true;
736 }
737
738 double totalPower = 0;
739 for (const auto& reading : powerReadings)
740 {
741 if (std::isnan(reading.second))
742 {
743 continue;
744 }
745 totalPower += reading.second;
746 }
747
748 // Calculate power correction factor
749 // Ci = CL + (CH - CL)/(QMax - QMin) * (CFM - QMin)
Ed Tanous8a57ec02020-10-09 12:46:52 -0700750 double powerFactor = 0.0;
James Feistbc896df2018-11-26 16:28:17 -0800751 if (cfm <= qMin)
752 {
753 powerFactor = powerFactorMin;
754 }
755 else if (cfm >= qMax)
756 {
757 powerFactor = powerFactorMax;
758 }
759 else
760 {
761 powerFactor = powerFactorMin + ((powerFactorMax - powerFactorMin) /
762 (qMax - qMin) * (cfm - qMin));
763 }
764
Ed Tanous8a57ec02020-10-09 12:46:52 -0700765 totalPower *= powerFactor;
James Feistbc896df2018-11-26 16:28:17 -0800766 totalPower += pOffset;
767
768 if (totalPower == 0)
769 {
James Feistae11cfc2019-05-07 15:01:20 -0700770 if (errorPrint > 0)
771 {
772 errorPrint--;
773 std::cerr << "total power 0\n";
774 }
James Feistbc896df2018-11-26 16:28:17 -0800775 val = 0;
776 return false;
777 }
778
Ed Tanous8a57ec02020-10-09 12:46:52 -0700779 if constexpr (debug)
James Feistbc896df2018-11-26 16:28:17 -0800780 {
781 std::cout << "Power Factor " << powerFactor << "\n";
782 std::cout << "Inlet Temp " << inletTemp << "\n";
783 std::cout << "Total Power" << totalPower << "\n";
784 }
785
786 // Calculate the exit air temp
787 // Texit = Tfp + (1.76 * TotalPower / CFM * Faltitude)
Ed Tanous8a57ec02020-10-09 12:46:52 -0700788 double reading = 1.76 * totalPower * altitudeFactor;
James Feistbc896df2018-11-26 16:28:17 -0800789 reading /= cfm;
790 reading += inletTemp;
791
Ed Tanous8a57ec02020-10-09 12:46:52 -0700792 if constexpr (debug)
James Feistbc896df2018-11-26 16:28:17 -0800793 {
794 std::cout << "Reading 1: " << reading << "\n";
795 }
796
797 // Now perform the exponential average
798 // Calculate alpha based on SDR values and CFM
799 // Ai = As + (Af - As)/(QMax - QMin) * (CFM - QMin)
800
801 double alpha = 0.0;
802 if (cfm < qMin)
803 {
804 alpha = alphaS;
805 }
806 else if (cfm >= qMax)
807 {
808 alpha = alphaF;
809 }
810 else
811 {
812 alpha = alphaS + ((alphaF - alphaS) * (cfm - qMin) / (qMax - qMin));
813 }
814
Zhikui Ren12e3d672020-12-03 15:14:49 -0800815 auto time = std::chrono::steady_clock::now();
James Feistbc896df2018-11-26 16:28:17 -0800816 if (!firstRead)
817 {
818 firstRead = true;
819 lastTime = time;
820 lastReading = reading;
821 }
822 double alphaDT =
823 std::chrono::duration_cast<std::chrono::seconds>(time - lastTime)
824 .count() *
825 alpha;
826
827 // cap at 1.0 or the below fails
828 if (alphaDT > 1.0)
829 {
830 alphaDT = 1.0;
831 }
832
Ed Tanous8a57ec02020-10-09 12:46:52 -0700833 if constexpr (debug)
James Feistbc896df2018-11-26 16:28:17 -0800834 {
835 std::cout << "AlphaDT: " << alphaDT << "\n";
836 }
837
838 reading = ((reading * alphaDT) + (lastReading * (1.0 - alphaDT)));
839
Ed Tanous8a57ec02020-10-09 12:46:52 -0700840 if constexpr (debug)
James Feistbc896df2018-11-26 16:28:17 -0800841 {
842 std::cout << "Reading 2: " << reading << "\n";
843 }
844
845 val = reading;
846 lastReading = reading;
847 lastTime = time;
James Feistae11cfc2019-05-07 15:01:20 -0700848 errorPrint = maxErrorPrint;
James Feistbc896df2018-11-26 16:28:17 -0800849 return true;
850}
851
852void ExitAirTempSensor::checkThresholds(void)
853{
854 thresholds::checkThresholds(this);
855}
856
James Feistbc896df2018-11-26 16:28:17 -0800857static void loadVariantPathArray(
858 const boost::container::flat_map<std::string, BasicVariantType>& data,
859 const std::string& key, std::vector<std::string>& resp)
860{
861 auto it = data.find(key);
862 if (it == data.end())
863 {
864 std::cerr << "Configuration missing " << key << "\n";
865 throw std::invalid_argument("Key Missing");
866 }
867 BasicVariantType copy = it->second;
James Feist3eb82622019-02-08 13:10:22 -0800868 std::vector<std::string> config = std::get<std::vector<std::string>>(copy);
James Feistbc896df2018-11-26 16:28:17 -0800869 for (auto& str : config)
870 {
871 boost::replace_all(str, " ", "_");
872 }
873 resp = std::move(config);
874}
875
876void createSensor(sdbusplus::asio::object_server& objectServer,
James Feistb2eb3f52018-12-04 16:17:50 -0800877 std::shared_ptr<ExitAirTempSensor>& exitAirSensor,
James Feistbc896df2018-11-26 16:28:17 -0800878 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
879{
880 if (!dbusConnection)
881 {
882 std::cerr << "Connection not created\n";
883 return;
884 }
James Feist655f3762020-10-05 15:28:15 -0700885 auto getter = std::make_shared<GetSensorConfiguration>(
886 dbusConnection,
887 std::move([&objectServer, &dbusConnection,
888 &exitAirSensor](const ManagedObjectType& resp) {
James Feist9a25ed42019-10-15 15:43:44 -0700889 cfmSensors.clear();
James Feistbc896df2018-11-26 16:28:17 -0800890 for (const auto& pathPair : resp)
891 {
892 for (const auto& entry : pathPair.second)
893 {
894 if (entry.first == exitAirIface)
895 {
James Feistbc896df2018-11-26 16:28:17 -0800896 // thresholds should be under the same path
897 std::vector<thresholds::Threshold> sensorThresholds;
898 parseThresholdsFromConfig(pathPair.second,
899 sensorThresholds);
James Feistbc896df2018-11-26 16:28:17 -0800900
James Feist523828e2019-03-04 14:38:37 -0800901 std::string name =
902 loadVariant<std::string>(entry.second, "Name");
903 exitAirSensor = std::make_shared<ExitAirTempSensor>(
904 dbusConnection, name, pathPair.first.str,
905 objectServer, std::move(sensorThresholds));
James Feistb2eb3f52018-12-04 16:17:50 -0800906 exitAirSensor->powerFactorMin =
907 loadVariant<double>(entry.second, "PowerFactorMin");
908 exitAirSensor->powerFactorMax =
909 loadVariant<double>(entry.second, "PowerFactorMax");
910 exitAirSensor->qMin =
911 loadVariant<double>(entry.second, "QMin");
912 exitAirSensor->qMax =
913 loadVariant<double>(entry.second, "QMax");
914 exitAirSensor->alphaS =
915 loadVariant<double>(entry.second, "AlphaS");
916 exitAirSensor->alphaF =
917 loadVariant<double>(entry.second, "AlphaF");
James Feistbc896df2018-11-26 16:28:17 -0800918 }
919 else if (entry.first == cfmIface)
920
921 {
James Feistb2eb3f52018-12-04 16:17:50 -0800922 // thresholds should be under the same path
923 std::vector<thresholds::Threshold> sensorThresholds;
924 parseThresholdsFromConfig(pathPair.second,
925 sensorThresholds);
926 std::string name =
927 loadVariant<std::string>(entry.second, "Name");
James Feist9a25ed42019-10-15 15:43:44 -0700928 auto sensor = std::make_shared<CFMSensor>(
James Feistb2eb3f52018-12-04 16:17:50 -0800929 dbusConnection, name, pathPair.first.str,
930 objectServer, std::move(sensorThresholds),
931 exitAirSensor);
932 loadVariantPathArray(entry.second, "Tachs",
933 sensor->tachs);
934 sensor->maxCFM =
935 loadVariant<double>(entry.second, "MaxCFM");
James Feistbc896df2018-11-26 16:28:17 -0800936
937 // change these into percent upon getting the data
James Feistb2eb3f52018-12-04 16:17:50 -0800938 sensor->c1 =
939 loadVariant<double>(entry.second, "C1") / 100;
940 sensor->c2 =
941 loadVariant<double>(entry.second, "C2") / 100;
942 sensor->tachMinPercent =
Zhikui Ren12e3d672020-12-03 15:14:49 -0800943 loadVariant<double>(entry.second, "TachMinPercent");
James Feistb2eb3f52018-12-04 16:17:50 -0800944 sensor->tachMaxPercent =
Zhikui Ren12e3d672020-12-03 15:14:49 -0800945 loadVariant<double>(entry.second, "TachMaxPercent");
James Feist13452092019-03-07 16:38:12 -0800946 sensor->createMaxCFMIface();
James Feist9a25ed42019-10-15 15:43:44 -0700947 sensor->setupMatches();
James Feistbc896df2018-11-26 16:28:17 -0800948
James Feistb2eb3f52018-12-04 16:17:50 -0800949 cfmSensors.emplace_back(std::move(sensor));
James Feistbc896df2018-11-26 16:28:17 -0800950 }
951 }
952 }
James Feistb2eb3f52018-12-04 16:17:50 -0800953 if (exitAirSensor)
James Feistbc896df2018-11-26 16:28:17 -0800954 {
James Feist9a25ed42019-10-15 15:43:44 -0700955 exitAirSensor->setupMatches();
James Feistb2eb3f52018-12-04 16:17:50 -0800956 exitAirSensor->updateReading();
James Feistbc896df2018-11-26 16:28:17 -0800957 }
James Feist655f3762020-10-05 15:28:15 -0700958 }));
959 getter->getConfiguration(
960 std::vector<std::string>(monitorIfaces.begin(), monitorIfaces.end()));
James Feistbc896df2018-11-26 16:28:17 -0800961}
962
James Feistb6c0b912019-07-09 12:21:44 -0700963int main()
James Feistbc896df2018-11-26 16:28:17 -0800964{
965
966 boost::asio::io_service io;
967 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
968 systemBus->request_name("xyz.openbmc_project.ExitAirTempSensor");
969 sdbusplus::asio::object_server objectServer(systemBus);
970 std::shared_ptr<ExitAirTempSensor> sensor =
971 nullptr; // wait until we find the config
972 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
973
974 io.post([&]() { createSensor(objectServer, sensor, systemBus); });
975
976 boost::asio::deadline_timer configTimer(io);
977
978 std::function<void(sdbusplus::message::message&)> eventHandler =
James Feistb6c0b912019-07-09 12:21:44 -0700979 [&](sdbusplus::message::message&) {
James Feistbc896df2018-11-26 16:28:17 -0800980 configTimer.expires_from_now(boost::posix_time::seconds(1));
981 // create a timer because normally multiple properties change
982 configTimer.async_wait([&](const boost::system::error_code& ec) {
983 if (ec == boost::asio::error::operation_aborted)
984 {
985 return; // we're being canceled
986 }
987 createSensor(objectServer, sensor, systemBus);
988 if (!sensor)
989 {
990 std::cout << "Configuration not detected\n";
991 }
992 });
993 };
James Feistbc896df2018-11-26 16:28:17 -0800994 for (const char* type : monitorIfaces)
995 {
996 auto match = std::make_unique<sdbusplus::bus::match::match>(
997 static_cast<sdbusplus::bus::bus&>(*systemBus),
998 "type='signal',member='PropertiesChanged',path_namespace='" +
999 std::string(inventoryPath) + "',arg0namespace='" + type + "'",
1000 eventHandler);
1001 matches.emplace_back(std::move(match));
1002 }
1003
1004 io.run();
1005}