blob: a4aba4b9c122e5ada297a2028c2a5344da09bbca [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
17#include "ExitAirTempSensor.hpp"
18
19#include "Utils.hpp"
20#include "VariantVisitors.hpp"
21
22#include <math.h>
23
24#include <boost/algorithm/string/predicate.hpp>
25#include <boost/algorithm/string/replace.hpp>
26#include <chrono>
27#include <iostream>
28#include <limits>
29#include <numeric>
30#include <sdbusplus/asio/connection.hpp>
31#include <sdbusplus/asio/object_server.hpp>
32#include <vector>
33
34constexpr const float altitudeFactor = 1.14;
35constexpr const char* exitAirIface =
36 "xyz.openbmc_project.Configuration.ExitAirTempSensor";
37constexpr const char* cfmIface = "xyz.openbmc_project.Configuration.CFMSensor";
38
39// todo: this *might* need to be configurable
40constexpr const char* inletTemperatureSensor = "temperature/Front_Panel_Temp";
James Feist13452092019-03-07 16:38:12 -080041constexpr const char* pidConfigurationType =
42 "xyz.openbmc_project.Configuration.Pid";
43constexpr const char* settingsDaemon = "xyz.openbmc_project.Settings";
44constexpr const char* cfmSettingPath = "/xyz/openbmc_project/control/cfm_limit";
45constexpr const char* cfmSettingIface = "xyz.openbmc_project.Control.CFMLimit";
James Feistbc896df2018-11-26 16:28:17 -080046
47static constexpr bool DEBUG = false;
48
James Feistb2eb3f52018-12-04 16:17:50 -080049static constexpr double cfmMaxReading = 255;
50static constexpr double cfmMinReading = 0;
51
James Feist13452092019-03-07 16:38:12 -080052static constexpr size_t minSystemCfm = 50;
53
James Feistb2eb3f52018-12-04 16:17:50 -080054static void setupSensorMatch(
55 std::vector<sdbusplus::bus::match::match>& matches,
56 sdbusplus::bus::bus& connection, const std::string& type,
57 std::function<void(const double&, sdbusplus::message::message&)>&& callback)
58{
59
60 std::function<void(sdbusplus::message::message & message)> eventHandler =
61 [callback{std::move(callback)}](sdbusplus::message::message& message) {
62 std::string objectName;
James Feist3eb82622019-02-08 13:10:22 -080063 boost::container::flat_map<std::string,
64 std::variant<double, int64_t>>
James Feistb2eb3f52018-12-04 16:17:50 -080065 values;
66 message.read(objectName, values);
67 auto findValue = values.find("Value");
68 if (findValue == values.end())
69 {
70 return;
71 }
James Feist3eb82622019-02-08 13:10:22 -080072 double value =
73 std::visit(VariantToDoubleVisitor(), findValue->second);
James Feist9566bfa2019-01-29 15:31:23 -080074 if (std::isnan(value))
75 {
76 return;
77 }
78
James Feistb2eb3f52018-12-04 16:17:50 -080079 callback(value, message);
80 };
81 matches.emplace_back(connection,
82 "type='signal',"
83 "member='PropertiesChanged',interface='org."
84 "freedesktop.DBus.Properties',path_"
85 "namespace='/xyz/openbmc_project/sensors/" +
86 std::string(type) +
87 "',arg0='xyz.openbmc_project.Sensor.Value'",
88 std::move(eventHandler));
89}
90
James Feist13452092019-03-07 16:38:12 -080091static void setMaxPWM(const std::shared_ptr<sdbusplus::asio::connection>& conn,
92 double value)
93{
94 using GetSubTreeType = std::vector<std::pair<
95 std::string,
96 std::vector<std::pair<std::string, std::vector<std::string>>>>>;
97
98 conn->async_method_call(
99 [conn, value](const boost::system::error_code ec,
100 const GetSubTreeType& ret) {
101 if (ec)
102 {
103 std::cerr << "Error calling mapper\n";
104 return;
105 }
106 for (const auto& [path, objDict] : ret)
107 {
108 if (objDict.empty())
109 {
110 return;
111 }
112 const std::string& owner = objDict.begin()->first;
113
114 conn->async_method_call(
115 [conn, value, owner,
116 path](const boost::system::error_code ec,
117 const std::variant<std::string>& classType) {
118 if (ec)
119 {
120 std::cerr << "Error getting pid class\n";
121 return;
122 }
123 auto classStr = std::get_if<std::string>(&classType);
124 if (classStr == nullptr || *classStr != "fan")
125 {
126 return;
127 }
128 conn->async_method_call(
129 [](boost::system::error_code& ec) {
130 if (ec)
131 {
132 std::cerr << "Error setting pid class\n";
133 return;
134 }
135 },
136 owner, path, "org.freedesktop.DBus.Properties",
137 "Set", pidConfigurationType, "OutLimitMax",
138 std::variant<double>(value));
139 },
140 owner, path, "org.freedesktop.DBus.Properties", "Get",
141 pidConfigurationType, "Class");
142 }
143 },
James Feista5e58722019-04-22 14:43:11 -0700144 mapper::busName, mapper::path, mapper::interface, mapper::subtree, "/",
145 0, std::array<std::string, 1>{pidConfigurationType});
James Feist13452092019-03-07 16:38:12 -0800146}
147
James Feistb2eb3f52018-12-04 16:17:50 -0800148CFMSensor::CFMSensor(std::shared_ptr<sdbusplus::asio::connection>& conn,
149 const std::string& sensorName,
150 const std::string& sensorConfiguration,
151 sdbusplus::asio::object_server& objectServer,
James Feistb839c052019-05-15 10:25:24 -0700152 std::vector<thresholds::Threshold>&& thresholdData,
James Feistb2eb3f52018-12-04 16:17:50 -0800153 std::shared_ptr<ExitAirTempSensor>& parent) :
154 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
James Feist930fcde2019-05-28 12:58:43 -0700155 std::move(thresholdData), sensorConfiguration,
156 "xyz.openbmc_project.Configuration.ExitAirTemp", cfmMaxReading,
157 cfmMinReading),
James Feist9566bfa2019-01-29 15:31:23 -0800158 dbusConnection(conn), parent(parent), objServer(objectServer)
James Feistb2eb3f52018-12-04 16:17:50 -0800159{
160 sensorInterface =
161 objectServer.add_interface("/xyz/openbmc_project/sensors/cfm/" + name,
162 "xyz.openbmc_project.Sensor.Value");
163
164 if (thresholds::hasWarningInterface(thresholds))
165 {
166 thresholdInterfaceWarning = objectServer.add_interface(
167 "/xyz/openbmc_project/sensors/cfm/" + name,
168 "xyz.openbmc_project.Sensor.Threshold.Warning");
169 }
170 if (thresholds::hasCriticalInterface(thresholds))
171 {
172 thresholdInterfaceCritical = objectServer.add_interface(
173 "/xyz/openbmc_project/sensors/cfm/" + name,
174 "xyz.openbmc_project.Sensor.Threshold.Critical");
175 }
James Feist078f2322019-03-08 11:09:05 -0800176
177 association = objectServer.add_interface(
James Feista5e58722019-04-22 14:43:11 -0700178 "/xyz/openbmc_project/sensors/cfm/" + name, "org.openbmc.Associations");
James Feist078f2322019-03-08 11:09:05 -0800179
James Feistb2eb3f52018-12-04 16:17:50 -0800180 setInitialProperties(conn);
181 setupSensorMatch(
182 matches, *dbusConnection, "fan_tach",
183 std::move(
184 [this](const double& value, sdbusplus::message::message& message) {
185 tachReadings[message.get_path()] = value;
186 if (tachRanges.find(message.get_path()) == tachRanges.end())
187 {
188 // calls update reading after updating ranges
189 addTachRanges(message.get_sender(), message.get_path());
190 }
191 else
192 {
193 updateReading();
194 }
195 }));
James Feist13452092019-03-07 16:38:12 -0800196 pwmLimitIface =
197 objectServer.add_interface("/xyz/openbmc_project/control/pwm_limit",
198 "xyz.openbmc_project.Control.PWMLimit");
199 cfmLimitIface =
200 objectServer.add_interface("/xyz/openbmc_project/control/MaxCFM",
201 "xyz.openbmc_project.Control.CFMLimit");
202
203 conn->async_method_call(
204 [this, conn](const boost::system::error_code ec,
205 const std::variant<double> cfmVariant) {
206 uint64_t maxRpm = 100;
207 if (!ec)
208 {
209
210 auto cfm = std::get_if<double>(&cfmVariant);
211 if (cfm != nullptr || *cfm >= minSystemCfm)
212 {
213 maxRpm = getMaxRpm(*cfm);
214 }
215 }
216 pwmLimitIface->register_property("Limit", maxRpm);
217 pwmLimitIface->initialize();
218 setMaxPWM(conn, maxRpm);
219 },
220 settingsDaemon, cfmSettingPath, "org.freedesktop.DBus.Properties",
221 "Get", cfmSettingIface, "Limit");
222
223 matches.emplace_back(
224 *conn,
225 "type='signal',"
226 "member='PropertiesChanged',interface='org."
227 "freedesktop.DBus.Properties',path='" +
228 std::string(cfmSettingPath) + "',arg0='" +
229 std::string(cfmSettingIface) + "'",
230 [this, conn](sdbusplus::message::message& message) {
231 boost::container::flat_map<std::string, std::variant<double>>
232 values;
233 std::string objectName;
234 message.read(objectName, values);
235 const auto findValue = values.find("Limit");
236 if (findValue == values.end())
237 {
238 return;
239 }
240 const auto reading = std::get_if<double>(&(findValue->second));
241 if (reading == nullptr)
242 {
243 std::cerr << "Got CFM Limit of wrong type\n";
244 return;
245 }
246 if (*reading < minSystemCfm && *reading != 0)
247 {
248 std::cerr << "Illegal CFM setting detected\n";
249 return;
250 }
251 uint64_t maxRpm = getMaxRpm(*reading);
252 pwmLimitIface->set_property("Limit", maxRpm);
253 setMaxPWM(conn, maxRpm);
254 });
James Feistb2eb3f52018-12-04 16:17:50 -0800255}
256
James Feist9566bfa2019-01-29 15:31:23 -0800257CFMSensor::~CFMSensor()
258{
259 objServer.remove_interface(thresholdInterfaceWarning);
260 objServer.remove_interface(thresholdInterfaceCritical);
261 objServer.remove_interface(sensorInterface);
James Feist078f2322019-03-08 11:09:05 -0800262 objServer.remove_interface(association);
James Feist13452092019-03-07 16:38:12 -0800263 objServer.remove_interface(cfmLimitIface);
264 objServer.remove_interface(pwmLimitIface);
265}
266
267void CFMSensor::createMaxCFMIface(void)
268{
269 cfmLimitIface->register_property("Limit", static_cast<double>(c2) * maxCFM *
270 tachs.size());
271 cfmLimitIface->initialize();
James Feist9566bfa2019-01-29 15:31:23 -0800272}
273
James Feistb2eb3f52018-12-04 16:17:50 -0800274void CFMSensor::addTachRanges(const std::string& serviceName,
275 const std::string& path)
276{
277 dbusConnection->async_method_call(
278 [this, path](const boost::system::error_code ec,
279 const boost::container::flat_map<std::string,
280 BasicVariantType>& data) {
281 if (ec)
282 {
283 std::cerr << "Error getting properties from " << path << "\n";
James Feist1ccdb5e2019-01-24 09:44:01 -0800284 return;
James Feistb2eb3f52018-12-04 16:17:50 -0800285 }
286
287 double max = loadVariant<double>(data, "MaxValue");
288 double min = loadVariant<double>(data, "MinValue");
289 tachRanges[path] = std::make_pair(min, max);
290 updateReading();
291 },
292 serviceName, path, "org.freedesktop.DBus.Properties", "GetAll",
293 "xyz.openbmc_project.Sensor.Value");
294}
295
296void CFMSensor::checkThresholds(void)
297{
298 thresholds::checkThresholds(this);
299}
300
301void CFMSensor::updateReading(void)
302{
303 double val = 0.0;
304 if (calculate(val))
305 {
306 if (value != val && parent)
307 {
308 parent->updateReading();
309 }
310 updateValue(val);
311 }
312 else
313 {
314 updateValue(std::numeric_limits<double>::quiet_NaN());
315 }
316}
317
James Feist13452092019-03-07 16:38:12 -0800318uint64_t CFMSensor::getMaxRpm(uint64_t cfmMaxSetting)
319{
320 uint64_t pwmPercent = 100;
321 double totalCFM = std::numeric_limits<double>::max();
322 if (cfmMaxSetting == 0)
323 {
324 return pwmPercent;
325 }
326
James Feist52427952019-04-05 14:23:35 -0700327 bool firstLoop = true;
James Feist13452092019-03-07 16:38:12 -0800328 while (totalCFM > cfmMaxSetting)
329 {
James Feist52427952019-04-05 14:23:35 -0700330 if (firstLoop)
331 {
332 firstLoop = false;
333 }
334 else
335 {
336 pwmPercent--;
337 }
338
James Feist13452092019-03-07 16:38:12 -0800339 double ci = 0;
340 if (pwmPercent == 0)
341 {
342 ci = 0;
343 }
344 else if (pwmPercent < tachMinPercent)
345 {
346 ci = c1;
347 }
348 else if (pwmPercent > tachMaxPercent)
349 {
350 ci = c2;
351 }
352 else
353 {
354 ci = c1 + (((c2 - c1) * (pwmPercent - tachMinPercent)) /
355 (tachMaxPercent - tachMinPercent));
356 }
357
358 // Now calculate the CFM for this tach
359 // CFMi = Ci * Qmaxi * TACHi
360 totalCFM = ci * maxCFM * pwmPercent;
361 totalCFM *= tachs.size();
362 // divide by 100 since pwm is in percent
363 totalCFM /= 100;
364
James Feist13452092019-03-07 16:38:12 -0800365 if (pwmPercent <= 0)
366 {
367 break;
368 }
369 }
James Feist52427952019-04-05 14:23:35 -0700370
James Feist13452092019-03-07 16:38:12 -0800371 return pwmPercent;
372}
373
James Feistb2eb3f52018-12-04 16:17:50 -0800374bool CFMSensor::calculate(double& value)
375{
376 double totalCFM = 0;
377 for (const std::string& tachName : tachs)
378 {
James Feist9566bfa2019-01-29 15:31:23 -0800379
James Feistb2eb3f52018-12-04 16:17:50 -0800380 auto findReading = std::find_if(
381 tachReadings.begin(), tachReadings.end(), [&](const auto& item) {
382 return boost::ends_with(item.first, tachName);
383 });
384 auto findRange = std::find_if(
385 tachRanges.begin(), tachRanges.end(), [&](const auto& item) {
386 return boost::ends_with(item.first, tachName);
387 });
388 if (findReading == tachReadings.end())
389 {
James Feista5e58722019-04-22 14:43:11 -0700390 if constexpr (DEBUG)
James Feista96329f2019-01-24 10:08:27 -0800391 {
392 std::cerr << "Can't find " << tachName << "in readings\n";
393 }
James Feist9566bfa2019-01-29 15:31:23 -0800394 continue; // haven't gotten a reading
James Feistb2eb3f52018-12-04 16:17:50 -0800395 }
396
397 if (findRange == tachRanges.end())
398 {
James Feist523828e2019-03-04 14:38:37 -0800399 std::cerr << "Can't find " << tachName << " in ranges\n";
James Feistb2eb3f52018-12-04 16:17:50 -0800400 return false; // haven't gotten a max / min
401 }
402
403 // avoid divide by 0
404 if (findRange->second.second == 0)
405 {
406 std::cerr << "Tach Max Set to 0 " << tachName << "\n";
407 return false;
408 }
409
410 double rpm = findReading->second;
411
412 // for now assume the min for a fan is always 0, divide by max to get
413 // percent and mult by 100
414 rpm /= findRange->second.second;
415 rpm *= 100;
416
417 if constexpr (DEBUG)
418 {
419 std::cout << "Tach " << tachName << "at " << rpm << "\n";
420 }
421
422 // Do a linear interpolation to get Ci
423 // Ci = C1 + (C2 - C1)/(RPM2 - RPM1) * (TACHi - TACH1)
424
425 double ci = 0;
426 if (rpm == 0)
427 {
428 ci = 0;
429 }
430 else if (rpm < tachMinPercent)
431 {
432 ci = c1;
433 }
434 else if (rpm > tachMaxPercent)
435 {
436 ci = c2;
437 }
438 else
439 {
440 ci = c1 + (((c2 - c1) * (rpm - tachMinPercent)) /
441 (tachMaxPercent - tachMinPercent));
442 }
443
444 // Now calculate the CFM for this tach
445 // CFMi = Ci * Qmaxi * TACHi
446 totalCFM += ci * maxCFM * rpm;
James Feista5e58722019-04-22 14:43:11 -0700447 if constexpr (DEBUG)
448 {
449 std::cerr << "totalCFM = " << totalCFM << "\n";
450 std::cerr << "Ci " << ci << " MaxCFM " << maxCFM << " rpm " << rpm
451 << "\n";
452 std::cerr << "c1 " << c1 << " c2 " << c2 << " max "
453 << tachMaxPercent << " min " << tachMinPercent << "\n";
454 }
James Feistb2eb3f52018-12-04 16:17:50 -0800455 }
456
457 // divide by 100 since rpm is in percent
458 value = totalCFM / 100;
James Feista5e58722019-04-22 14:43:11 -0700459 if constexpr (DEBUG)
460 {
461 std::cerr << "cfm value = " << value << "\n";
462 }
James Feist9566bfa2019-01-29 15:31:23 -0800463 return true;
James Feistb2eb3f52018-12-04 16:17:50 -0800464}
465
466static constexpr double exitAirMaxReading = 127;
467static constexpr double exitAirMinReading = -128;
James Feistbc896df2018-11-26 16:28:17 -0800468ExitAirTempSensor::ExitAirTempSensor(
469 std::shared_ptr<sdbusplus::asio::connection>& conn,
James Feistb2eb3f52018-12-04 16:17:50 -0800470 const std::string& sensorName, const std::string& sensorConfiguration,
James Feistbc896df2018-11-26 16:28:17 -0800471 sdbusplus::asio::object_server& objectServer,
James Feistb839c052019-05-15 10:25:24 -0700472 std::vector<thresholds::Threshold>&& thresholdData) :
James Feistb2eb3f52018-12-04 16:17:50 -0800473 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
James Feist930fcde2019-05-28 12:58:43 -0700474 std::move(thresholdData), sensorConfiguration,
475 "xyz.openbmc_project.Configuration.ExitAirTemp", exitAirMaxReading,
476 exitAirMinReading),
James Feist523828e2019-03-04 14:38:37 -0800477 dbusConnection(conn), objServer(objectServer)
James Feistbc896df2018-11-26 16:28:17 -0800478{
479 sensorInterface = objectServer.add_interface(
480 "/xyz/openbmc_project/sensors/temperature/" + name,
481 "xyz.openbmc_project.Sensor.Value");
482
483 if (thresholds::hasWarningInterface(thresholds))
484 {
485 thresholdInterfaceWarning = objectServer.add_interface(
486 "/xyz/openbmc_project/sensors/temperature/" + name,
487 "xyz.openbmc_project.Sensor.Threshold.Warning");
488 }
489 if (thresholds::hasCriticalInterface(thresholds))
490 {
491 thresholdInterfaceCritical = objectServer.add_interface(
492 "/xyz/openbmc_project/sensors/temperature/" + name,
493 "xyz.openbmc_project.Sensor.Threshold.Critical");
494 }
James Feist078f2322019-03-08 11:09:05 -0800495 association = objectServer.add_interface(
496 "/xyz/openbmc_project/sensors/temperature/" + name,
497 "org.openbmc.Associations");
James Feistbc896df2018-11-26 16:28:17 -0800498 setInitialProperties(conn);
499 setupMatches();
James Feist71d31b22019-01-02 16:57:54 -0800500 setupPowerMatch(conn);
James Feistbc896df2018-11-26 16:28:17 -0800501}
502
503ExitAirTempSensor::~ExitAirTempSensor()
504{
James Feist523828e2019-03-04 14:38:37 -0800505 objServer.remove_interface(thresholdInterfaceWarning);
506 objServer.remove_interface(thresholdInterfaceCritical);
507 objServer.remove_interface(sensorInterface);
James Feist078f2322019-03-08 11:09:05 -0800508 objServer.remove_interface(association);
James Feistbc896df2018-11-26 16:28:17 -0800509}
510
511void ExitAirTempSensor::setupMatches(void)
512{
James Feistb2eb3f52018-12-04 16:17:50 -0800513 constexpr const std::array<const char*, 2> matchTypes = {
514 "power", inletTemperatureSensor};
James Feistbc896df2018-11-26 16:28:17 -0800515
James Feistb2eb3f52018-12-04 16:17:50 -0800516 for (const std::string& type : matchTypes)
James Feistbc896df2018-11-26 16:28:17 -0800517 {
James Feistb2eb3f52018-12-04 16:17:50 -0800518 setupSensorMatch(matches, *dbusConnection, type,
519 [this, type](const double& value,
520 sdbusplus::message::message& message) {
521 if (type == "power")
522 {
James Feista5e58722019-04-22 14:43:11 -0700523 std::string path = message.get_path();
524 if (path.find("PS") != std::string::npos &&
525 boost::ends_with(path, "Input_Power"))
526 {
527 powerReadings[message.get_path()] = value;
528 }
James Feistb2eb3f52018-12-04 16:17:50 -0800529 }
530 else if (type == inletTemperatureSensor)
531 {
532 inletTemp = value;
533 }
534 updateReading();
535 });
James Feistbc896df2018-11-26 16:28:17 -0800536 }
James Feist9566bfa2019-01-29 15:31:23 -0800537 dbusConnection->async_method_call(
538 [this](boost::system::error_code ec,
539 const std::variant<double>& value) {
540 if (ec)
541 {
542 // sensor not ready yet
543 return;
544 }
545
James Feist3eb82622019-02-08 13:10:22 -0800546 inletTemp = std::visit(VariantToDoubleVisitor(), value);
James Feist9566bfa2019-01-29 15:31:23 -0800547 },
548 "xyz.openbmc_project.HwmonTempSensor",
549 std::string("/xyz/openbmc_project/sensors/") + inletTemperatureSensor,
James Feista5e58722019-04-22 14:43:11 -0700550 properties::interface, properties::get, sensorValueInterface, "Value");
551 dbusConnection->async_method_call(
552 [this](boost::system::error_code ec, const GetSubTreeType& subtree) {
553 if (ec)
554 {
555 std::cerr << "Error contacting mapper\n";
556 return;
557 }
558 for (const auto& item : subtree)
559 {
560 size_t lastSlash = item.first.rfind("/");
561 if (lastSlash == std::string::npos ||
562 lastSlash == item.first.size() || !item.second.size())
563 {
564 continue;
565 }
566 std::string sensorName = item.first.substr(lastSlash + 1);
567 if (boost::starts_with(sensorName, "PS") &&
568 boost::ends_with(sensorName, "Input_Power"))
569 {
570 const std::string& path = item.first;
571 dbusConnection->async_method_call(
572 [this, path](boost::system::error_code ec,
573 const std::variant<double>& value) {
574 if (ec)
575 {
576 std::cerr << "Error getting value from " << path
577 << "\n";
578 }
579
580 double reading =
581 std::visit(VariantToDoubleVisitor(), value);
582 if constexpr (DEBUG)
583 {
584 std::cerr << path << "Reading " << reading
585 << "\n";
586 }
587 powerReadings[path] = reading;
588 },
589 item.second[0].first, item.first, properties::interface,
590 properties::get, sensorValueInterface, "Value");
591 }
592 }
593 },
594 mapper::busName, mapper::path, mapper::interface, mapper::subtree,
595 "/xyz/openbmc_project/sensors/power", 0,
596 std::array<const char*, 1>{sensorValueInterface});
James Feistbc896df2018-11-26 16:28:17 -0800597}
598
599void ExitAirTempSensor::updateReading(void)
600{
601
602 double val = 0.0;
603 if (calculate(val))
604 {
James Feist18af4232019-03-13 11:14:00 -0700605 val = std::floor(val + 0.5);
James Feistbc896df2018-11-26 16:28:17 -0800606 updateValue(val);
607 }
608 else
609 {
610 updateValue(std::numeric_limits<double>::quiet_NaN());
611 }
612}
613
James Feistb2eb3f52018-12-04 16:17:50 -0800614double ExitAirTempSensor::getTotalCFM(void)
James Feistbc896df2018-11-26 16:28:17 -0800615{
James Feistb2eb3f52018-12-04 16:17:50 -0800616 double sum = 0;
617 for (auto& sensor : cfmSensors)
James Feistbc896df2018-11-26 16:28:17 -0800618 {
James Feistb2eb3f52018-12-04 16:17:50 -0800619 double reading = 0;
620 if (!sensor->calculate(reading))
James Feistbc896df2018-11-26 16:28:17 -0800621 {
James Feistbc896df2018-11-26 16:28:17 -0800622 return -1;
623 }
James Feistb2eb3f52018-12-04 16:17:50 -0800624 sum += reading;
James Feistbc896df2018-11-26 16:28:17 -0800625 }
James Feistb2eb3f52018-12-04 16:17:50 -0800626
627 return sum;
James Feistbc896df2018-11-26 16:28:17 -0800628}
629
630bool ExitAirTempSensor::calculate(double& val)
631{
James Feistae11cfc2019-05-07 15:01:20 -0700632 constexpr size_t maxErrorPrint = 1;
James Feistbc896df2018-11-26 16:28:17 -0800633 static bool firstRead = false;
James Feistae11cfc2019-05-07 15:01:20 -0700634 static size_t errorPrint = maxErrorPrint;
635
James Feistbc896df2018-11-26 16:28:17 -0800636 double cfm = getTotalCFM();
637 if (cfm <= 0)
638 {
639 std::cerr << "Error getting cfm\n";
640 return false;
641 }
642
643 // if there is an error getting inlet temp, return error
644 if (std::isnan(inletTemp))
645 {
James Feistae11cfc2019-05-07 15:01:20 -0700646 if (errorPrint > 0)
647 {
648 errorPrint--;
649 std::cerr << "Cannot get inlet temp\n";
650 }
James Feistbc896df2018-11-26 16:28:17 -0800651 val = 0;
652 return false;
653 }
654
655 // if fans are off, just make the exit temp equal to inlet
James Feist71d31b22019-01-02 16:57:54 -0800656 if (!isPowerOn())
James Feistbc896df2018-11-26 16:28:17 -0800657 {
658 val = inletTemp;
659 return true;
660 }
661
662 double totalPower = 0;
663 for (const auto& reading : powerReadings)
664 {
665 if (std::isnan(reading.second))
666 {
667 continue;
668 }
669 totalPower += reading.second;
670 }
671
672 // Calculate power correction factor
673 // Ci = CL + (CH - CL)/(QMax - QMin) * (CFM - QMin)
674 float powerFactor = 0.0;
675 if (cfm <= qMin)
676 {
677 powerFactor = powerFactorMin;
678 }
679 else if (cfm >= qMax)
680 {
681 powerFactor = powerFactorMax;
682 }
683 else
684 {
685 powerFactor = powerFactorMin + ((powerFactorMax - powerFactorMin) /
686 (qMax - qMin) * (cfm - qMin));
687 }
688
689 totalPower *= powerFactor;
690 totalPower += pOffset;
691
692 if (totalPower == 0)
693 {
James Feistae11cfc2019-05-07 15:01:20 -0700694 if (errorPrint > 0)
695 {
696 errorPrint--;
697 std::cerr << "total power 0\n";
698 }
James Feistbc896df2018-11-26 16:28:17 -0800699 val = 0;
700 return false;
701 }
702
703 if constexpr (DEBUG)
704 {
705 std::cout << "Power Factor " << powerFactor << "\n";
706 std::cout << "Inlet Temp " << inletTemp << "\n";
707 std::cout << "Total Power" << totalPower << "\n";
708 }
709
710 // Calculate the exit air temp
711 // Texit = Tfp + (1.76 * TotalPower / CFM * Faltitude)
712 double reading = 1.76 * totalPower * altitudeFactor;
713 reading /= cfm;
714 reading += inletTemp;
715
716 if constexpr (DEBUG)
717 {
718 std::cout << "Reading 1: " << reading << "\n";
719 }
720
721 // Now perform the exponential average
722 // Calculate alpha based on SDR values and CFM
723 // Ai = As + (Af - As)/(QMax - QMin) * (CFM - QMin)
724
725 double alpha = 0.0;
726 if (cfm < qMin)
727 {
728 alpha = alphaS;
729 }
730 else if (cfm >= qMax)
731 {
732 alpha = alphaF;
733 }
734 else
735 {
736 alpha = alphaS + ((alphaF - alphaS) * (cfm - qMin) / (qMax - qMin));
737 }
738
739 auto time = std::chrono::system_clock::now();
740 if (!firstRead)
741 {
742 firstRead = true;
743 lastTime = time;
744 lastReading = reading;
745 }
746 double alphaDT =
747 std::chrono::duration_cast<std::chrono::seconds>(time - lastTime)
748 .count() *
749 alpha;
750
751 // cap at 1.0 or the below fails
752 if (alphaDT > 1.0)
753 {
754 alphaDT = 1.0;
755 }
756
757 if constexpr (DEBUG)
758 {
759 std::cout << "AlphaDT: " << alphaDT << "\n";
760 }
761
762 reading = ((reading * alphaDT) + (lastReading * (1.0 - alphaDT)));
763
764 if constexpr (DEBUG)
765 {
766 std::cout << "Reading 2: " << reading << "\n";
767 }
768
769 val = reading;
770 lastReading = reading;
771 lastTime = time;
James Feistae11cfc2019-05-07 15:01:20 -0700772 errorPrint = maxErrorPrint;
James Feistbc896df2018-11-26 16:28:17 -0800773 return true;
774}
775
776void ExitAirTempSensor::checkThresholds(void)
777{
778 thresholds::checkThresholds(this);
779}
780
James Feistbc896df2018-11-26 16:28:17 -0800781static void loadVariantPathArray(
782 const boost::container::flat_map<std::string, BasicVariantType>& data,
783 const std::string& key, std::vector<std::string>& resp)
784{
785 auto it = data.find(key);
786 if (it == data.end())
787 {
788 std::cerr << "Configuration missing " << key << "\n";
789 throw std::invalid_argument("Key Missing");
790 }
791 BasicVariantType copy = it->second;
James Feist3eb82622019-02-08 13:10:22 -0800792 std::vector<std::string> config = std::get<std::vector<std::string>>(copy);
James Feistbc896df2018-11-26 16:28:17 -0800793 for (auto& str : config)
794 {
795 boost::replace_all(str, " ", "_");
796 }
797 resp = std::move(config);
798}
799
800void createSensor(sdbusplus::asio::object_server& objectServer,
James Feistb2eb3f52018-12-04 16:17:50 -0800801 std::shared_ptr<ExitAirTempSensor>& exitAirSensor,
James Feistbc896df2018-11-26 16:28:17 -0800802 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
803{
804 if (!dbusConnection)
805 {
806 std::cerr << "Connection not created\n";
807 return;
808 }
809 dbusConnection->async_method_call(
810 [&](boost::system::error_code ec, const ManagedObjectType& resp) {
811 if (ec)
812 {
813 std::cerr << "Error contacting entity manager\n";
814 return;
815 }
James Feistb2eb3f52018-12-04 16:17:50 -0800816 std::vector<std::unique_ptr<CFMSensor>> cfmSensors;
James Feistbc896df2018-11-26 16:28:17 -0800817 for (const auto& pathPair : resp)
818 {
819 for (const auto& entry : pathPair.second)
820 {
821 if (entry.first == exitAirIface)
822 {
James Feistbc896df2018-11-26 16:28:17 -0800823 // thresholds should be under the same path
824 std::vector<thresholds::Threshold> sensorThresholds;
825 parseThresholdsFromConfig(pathPair.second,
826 sensorThresholds);
James Feistbc896df2018-11-26 16:28:17 -0800827
James Feist523828e2019-03-04 14:38:37 -0800828 std::string name =
829 loadVariant<std::string>(entry.second, "Name");
830 exitAirSensor = std::make_shared<ExitAirTempSensor>(
831 dbusConnection, name, pathPair.first.str,
832 objectServer, std::move(sensorThresholds));
James Feistb2eb3f52018-12-04 16:17:50 -0800833 exitAirSensor->powerFactorMin =
834 loadVariant<double>(entry.second, "PowerFactorMin");
835 exitAirSensor->powerFactorMax =
836 loadVariant<double>(entry.second, "PowerFactorMax");
837 exitAirSensor->qMin =
838 loadVariant<double>(entry.second, "QMin");
839 exitAirSensor->qMax =
840 loadVariant<double>(entry.second, "QMax");
841 exitAirSensor->alphaS =
842 loadVariant<double>(entry.second, "AlphaS");
843 exitAirSensor->alphaF =
844 loadVariant<double>(entry.second, "AlphaF");
James Feistbc896df2018-11-26 16:28:17 -0800845 }
846 else if (entry.first == cfmIface)
847
848 {
James Feistb2eb3f52018-12-04 16:17:50 -0800849 // thresholds should be under the same path
850 std::vector<thresholds::Threshold> sensorThresholds;
851 parseThresholdsFromConfig(pathPair.second,
852 sensorThresholds);
853 std::string name =
854 loadVariant<std::string>(entry.second, "Name");
855 auto sensor = std::make_unique<CFMSensor>(
856 dbusConnection, name, pathPair.first.str,
857 objectServer, std::move(sensorThresholds),
858 exitAirSensor);
859 loadVariantPathArray(entry.second, "Tachs",
860 sensor->tachs);
861 sensor->maxCFM =
862 loadVariant<double>(entry.second, "MaxCFM");
James Feistbc896df2018-11-26 16:28:17 -0800863
864 // change these into percent upon getting the data
James Feistb2eb3f52018-12-04 16:17:50 -0800865 sensor->c1 =
866 loadVariant<double>(entry.second, "C1") / 100;
867 sensor->c2 =
868 loadVariant<double>(entry.second, "C2") / 100;
869 sensor->tachMinPercent =
870 loadVariant<double>(entry.second,
871 "TachMinPercent") /
James Feistbc896df2018-11-26 16:28:17 -0800872 100;
James Feistb2eb3f52018-12-04 16:17:50 -0800873 sensor->tachMaxPercent =
874 loadVariant<double>(entry.second,
875 "TachMaxPercent") /
James Feistbc896df2018-11-26 16:28:17 -0800876 100;
James Feist13452092019-03-07 16:38:12 -0800877 sensor->createMaxCFMIface();
James Feistbc896df2018-11-26 16:28:17 -0800878
James Feistb2eb3f52018-12-04 16:17:50 -0800879 cfmSensors.emplace_back(std::move(sensor));
James Feistbc896df2018-11-26 16:28:17 -0800880 }
881 }
882 }
James Feistb2eb3f52018-12-04 16:17:50 -0800883 if (exitAirSensor)
James Feistbc896df2018-11-26 16:28:17 -0800884 {
James Feistb2eb3f52018-12-04 16:17:50 -0800885 exitAirSensor->cfmSensors = std::move(cfmSensors);
James Feistb2eb3f52018-12-04 16:17:50 -0800886 exitAirSensor->updateReading();
James Feistbc896df2018-11-26 16:28:17 -0800887 }
888 },
889 entityManagerName, "/", "org.freedesktop.DBus.ObjectManager",
890 "GetManagedObjects");
891}
892
893int main(int argc, char** argv)
894{
895
896 boost::asio::io_service io;
897 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
898 systemBus->request_name("xyz.openbmc_project.ExitAirTempSensor");
899 sdbusplus::asio::object_server objectServer(systemBus);
900 std::shared_ptr<ExitAirTempSensor> sensor =
901 nullptr; // wait until we find the config
902 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
903
904 io.post([&]() { createSensor(objectServer, sensor, systemBus); });
905
906 boost::asio::deadline_timer configTimer(io);
907
908 std::function<void(sdbusplus::message::message&)> eventHandler =
909 [&](sdbusplus::message::message& message) {
910 configTimer.expires_from_now(boost::posix_time::seconds(1));
911 // create a timer because normally multiple properties change
912 configTimer.async_wait([&](const boost::system::error_code& ec) {
913 if (ec == boost::asio::error::operation_aborted)
914 {
915 return; // we're being canceled
916 }
917 createSensor(objectServer, sensor, systemBus);
918 if (!sensor)
919 {
920 std::cout << "Configuration not detected\n";
921 }
922 });
923 };
924 constexpr const std::array<const char*, 2> monitorIfaces = {exitAirIface,
925 cfmIface};
926 for (const char* type : monitorIfaces)
927 {
928 auto match = std::make_unique<sdbusplus::bus::match::match>(
929 static_cast<sdbusplus::bus::bus&>(*systemBus),
930 "type='signal',member='PropertiesChanged',path_namespace='" +
931 std::string(inventoryPath) + "',arg0namespace='" + type + "'",
932 eventHandler);
933 matches.emplace_back(std::move(match));
934 }
935
936 io.run();
937}