blob: c7e6e8ed73dee8b999dadf9214137fbf253180ca [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 Feistbc896df2018-11-26 16:28:17 -080041
42static constexpr bool DEBUG = false;
43
James Feistb2eb3f52018-12-04 16:17:50 -080044static constexpr double cfmMaxReading = 255;
45static constexpr double cfmMinReading = 0;
46
47static void setupSensorMatch(
48 std::vector<sdbusplus::bus::match::match>& matches,
49 sdbusplus::bus::bus& connection, const std::string& type,
50 std::function<void(const double&, sdbusplus::message::message&)>&& callback)
51{
52
53 std::function<void(sdbusplus::message::message & message)> eventHandler =
54 [callback{std::move(callback)}](sdbusplus::message::message& message) {
55 std::string objectName;
56 boost::container::flat_map<
57 std::string, sdbusplus::message::variant<double, int64_t>>
58 values;
59 message.read(objectName, values);
60 auto findValue = values.find("Value");
61 if (findValue == values.end())
62 {
63 return;
64 }
65 double value = sdbusplus::message::variant_ns::visit(
66 VariantToDoubleVisitor(), findValue->second);
67 callback(value, message);
68 };
69 matches.emplace_back(connection,
70 "type='signal',"
71 "member='PropertiesChanged',interface='org."
72 "freedesktop.DBus.Properties',path_"
73 "namespace='/xyz/openbmc_project/sensors/" +
74 std::string(type) +
75 "',arg0='xyz.openbmc_project.Sensor.Value'",
76 std::move(eventHandler));
77}
78
James Feistb2eb3f52018-12-04 16:17:50 -080079CFMSensor::CFMSensor(std::shared_ptr<sdbusplus::asio::connection>& conn,
80 const std::string& sensorName,
81 const std::string& sensorConfiguration,
82 sdbusplus::asio::object_server& objectServer,
83 std::vector<thresholds::Threshold>&& thresholds,
84 std::shared_ptr<ExitAirTempSensor>& parent) :
85 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
86 "" /* todo: remove arg from base*/, std::move(thresholds),
87 sensorConfiguration, "xyz.openbmc_project.Configuration.ExitAirTemp",
88 cfmMaxReading, cfmMinReading),
89 dbusConnection(conn), parent(parent)
90{
91 sensorInterface =
92 objectServer.add_interface("/xyz/openbmc_project/sensors/cfm/" + name,
93 "xyz.openbmc_project.Sensor.Value");
94
95 if (thresholds::hasWarningInterface(thresholds))
96 {
97 thresholdInterfaceWarning = objectServer.add_interface(
98 "/xyz/openbmc_project/sensors/cfm/" + name,
99 "xyz.openbmc_project.Sensor.Threshold.Warning");
100 }
101 if (thresholds::hasCriticalInterface(thresholds))
102 {
103 thresholdInterfaceCritical = objectServer.add_interface(
104 "/xyz/openbmc_project/sensors/cfm/" + name,
105 "xyz.openbmc_project.Sensor.Threshold.Critical");
106 }
107 setInitialProperties(conn);
108 setupSensorMatch(
109 matches, *dbusConnection, "fan_tach",
110 std::move(
111 [this](const double& value, sdbusplus::message::message& message) {
112 tachReadings[message.get_path()] = value;
113 if (tachRanges.find(message.get_path()) == tachRanges.end())
114 {
115 // calls update reading after updating ranges
116 addTachRanges(message.get_sender(), message.get_path());
117 }
118 else
119 {
120 updateReading();
121 }
122 }));
123}
124
125void CFMSensor::addTachRanges(const std::string& serviceName,
126 const std::string& path)
127{
128 dbusConnection->async_method_call(
129 [this, path](const boost::system::error_code ec,
130 const boost::container::flat_map<std::string,
131 BasicVariantType>& data) {
132 if (ec)
133 {
134 std::cerr << "Error getting properties from " << path << "\n";
135 }
136
137 double max = loadVariant<double>(data, "MaxValue");
138 double min = loadVariant<double>(data, "MinValue");
139 tachRanges[path] = std::make_pair(min, max);
140 updateReading();
141 },
142 serviceName, path, "org.freedesktop.DBus.Properties", "GetAll",
143 "xyz.openbmc_project.Sensor.Value");
144}
145
146void CFMSensor::checkThresholds(void)
147{
148 thresholds::checkThresholds(this);
149}
150
151void CFMSensor::updateReading(void)
152{
153 double val = 0.0;
154 if (calculate(val))
155 {
156 if (value != val && parent)
157 {
158 parent->updateReading();
159 }
160 updateValue(val);
161 }
162 else
163 {
164 updateValue(std::numeric_limits<double>::quiet_NaN());
165 }
166}
167
168bool CFMSensor::calculate(double& value)
169{
170 double totalCFM = 0;
171 for (const std::string& tachName : tachs)
172 {
173 auto findReading = std::find_if(
174 tachReadings.begin(), tachReadings.end(), [&](const auto& item) {
175 return boost::ends_with(item.first, tachName);
176 });
177 auto findRange = std::find_if(
178 tachRanges.begin(), tachRanges.end(), [&](const auto& item) {
179 return boost::ends_with(item.first, tachName);
180 });
181 if (findReading == tachReadings.end())
182 {
183 std::cerr << "Can't find " << tachName << "in readings\n";
184 return false; // haven't gotten a reading
185 }
186
187 if (findRange == tachRanges.end())
188 {
189 std::cerr << "Can't find " << tachName << "in ranges\n";
190 return false; // haven't gotten a max / min
191 }
192
193 // avoid divide by 0
194 if (findRange->second.second == 0)
195 {
196 std::cerr << "Tach Max Set to 0 " << tachName << "\n";
197 return false;
198 }
199
200 double rpm = findReading->second;
201
202 // for now assume the min for a fan is always 0, divide by max to get
203 // percent and mult by 100
204 rpm /= findRange->second.second;
205 rpm *= 100;
206
207 if constexpr (DEBUG)
208 {
209 std::cout << "Tach " << tachName << "at " << rpm << "\n";
210 }
211
212 // Do a linear interpolation to get Ci
213 // Ci = C1 + (C2 - C1)/(RPM2 - RPM1) * (TACHi - TACH1)
214
215 double ci = 0;
216 if (rpm == 0)
217 {
218 ci = 0;
219 }
220 else if (rpm < tachMinPercent)
221 {
222 ci = c1;
223 }
224 else if (rpm > tachMaxPercent)
225 {
226 ci = c2;
227 }
228 else
229 {
230 ci = c1 + (((c2 - c1) * (rpm - tachMinPercent)) /
231 (tachMaxPercent - tachMinPercent));
232 }
233
234 // Now calculate the CFM for this tach
235 // CFMi = Ci * Qmaxi * TACHi
236 totalCFM += ci * maxCFM * rpm;
237 }
238
239 // divide by 100 since rpm is in percent
240 value = totalCFM / 100;
241}
242
243static constexpr double exitAirMaxReading = 127;
244static constexpr double exitAirMinReading = -128;
James Feistbc896df2018-11-26 16:28:17 -0800245ExitAirTempSensor::ExitAirTempSensor(
246 std::shared_ptr<sdbusplus::asio::connection>& conn,
James Feistb2eb3f52018-12-04 16:17:50 -0800247 const std::string& sensorName, const std::string& sensorConfiguration,
James Feistbc896df2018-11-26 16:28:17 -0800248 sdbusplus::asio::object_server& objectServer,
249 std::vector<thresholds::Threshold>&& thresholds) :
James Feistb2eb3f52018-12-04 16:17:50 -0800250 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
251 "" /* todo: remove arg from base*/, std::move(thresholds),
252 sensorConfiguration, "xyz.openbmc_project.Configuration.ExitAirTemp",
253 exitAirMaxReading, exitAirMinReading),
James Feistbc896df2018-11-26 16:28:17 -0800254 dbusConnection(conn)
255{
256 sensorInterface = objectServer.add_interface(
257 "/xyz/openbmc_project/sensors/temperature/" + name,
258 "xyz.openbmc_project.Sensor.Value");
259
260 if (thresholds::hasWarningInterface(thresholds))
261 {
262 thresholdInterfaceWarning = objectServer.add_interface(
263 "/xyz/openbmc_project/sensors/temperature/" + name,
264 "xyz.openbmc_project.Sensor.Threshold.Warning");
265 }
266 if (thresholds::hasCriticalInterface(thresholds))
267 {
268 thresholdInterfaceCritical = objectServer.add_interface(
269 "/xyz/openbmc_project/sensors/temperature/" + name,
270 "xyz.openbmc_project.Sensor.Threshold.Critical");
271 }
272 setInitialProperties(conn);
273 setupMatches();
James Feist71d31b22019-01-02 16:57:54 -0800274 setupPowerMatch(conn);
James Feistbc896df2018-11-26 16:28:17 -0800275}
276
277ExitAirTempSensor::~ExitAirTempSensor()
278{
279 // this sensor currently isn't destroyed so we don't care
280}
281
282void ExitAirTempSensor::setupMatches(void)
283{
284
James Feistb2eb3f52018-12-04 16:17:50 -0800285 constexpr const std::array<const char*, 2> matchTypes = {
286 "power", inletTemperatureSensor};
James Feistbc896df2018-11-26 16:28:17 -0800287
James Feistb2eb3f52018-12-04 16:17:50 -0800288 for (const std::string& type : matchTypes)
James Feistbc896df2018-11-26 16:28:17 -0800289 {
James Feistb2eb3f52018-12-04 16:17:50 -0800290 setupSensorMatch(matches, *dbusConnection, type,
291 [this, type](const double& value,
292 sdbusplus::message::message& message) {
293 if (type == "power")
294 {
295 powerReadings[message.get_path()] = value;
296 }
297 else if (type == inletTemperatureSensor)
298 {
299 inletTemp = value;
300 }
301 updateReading();
302 });
James Feistbc896df2018-11-26 16:28:17 -0800303 }
304}
305
306void ExitAirTempSensor::updateReading(void)
307{
308
309 double val = 0.0;
310 if (calculate(val))
311 {
312 updateValue(val);
313 }
314 else
315 {
316 updateValue(std::numeric_limits<double>::quiet_NaN());
317 }
318}
319
James Feistb2eb3f52018-12-04 16:17:50 -0800320double ExitAirTempSensor::getTotalCFM(void)
James Feistbc896df2018-11-26 16:28:17 -0800321{
James Feistb2eb3f52018-12-04 16:17:50 -0800322 double sum = 0;
323 for (auto& sensor : cfmSensors)
James Feistbc896df2018-11-26 16:28:17 -0800324 {
James Feistb2eb3f52018-12-04 16:17:50 -0800325 double reading = 0;
326 if (!sensor->calculate(reading))
James Feistbc896df2018-11-26 16:28:17 -0800327 {
James Feistbc896df2018-11-26 16:28:17 -0800328 return -1;
329 }
James Feistb2eb3f52018-12-04 16:17:50 -0800330 sum += reading;
James Feistbc896df2018-11-26 16:28:17 -0800331 }
James Feistb2eb3f52018-12-04 16:17:50 -0800332
333 return sum;
James Feistbc896df2018-11-26 16:28:17 -0800334}
335
336bool ExitAirTempSensor::calculate(double& val)
337{
338 static bool firstRead = false;
339 double cfm = getTotalCFM();
340 if (cfm <= 0)
341 {
342 std::cerr << "Error getting cfm\n";
343 return false;
344 }
345
346 // if there is an error getting inlet temp, return error
347 if (std::isnan(inletTemp))
348 {
349 std::cerr << "Cannot get inlet temp\n";
350 val = 0;
351 return false;
352 }
353
354 // if fans are off, just make the exit temp equal to inlet
James Feist71d31b22019-01-02 16:57:54 -0800355 if (!isPowerOn())
James Feistbc896df2018-11-26 16:28:17 -0800356 {
357 val = inletTemp;
358 return true;
359 }
360
361 double totalPower = 0;
362 for (const auto& reading : powerReadings)
363 {
364 if (std::isnan(reading.second))
365 {
366 continue;
367 }
368 totalPower += reading.second;
369 }
370
371 // Calculate power correction factor
372 // Ci = CL + (CH - CL)/(QMax - QMin) * (CFM - QMin)
373 float powerFactor = 0.0;
374 if (cfm <= qMin)
375 {
376 powerFactor = powerFactorMin;
377 }
378 else if (cfm >= qMax)
379 {
380 powerFactor = powerFactorMax;
381 }
382 else
383 {
384 powerFactor = powerFactorMin + ((powerFactorMax - powerFactorMin) /
385 (qMax - qMin) * (cfm - qMin));
386 }
387
388 totalPower *= powerFactor;
389 totalPower += pOffset;
390
391 if (totalPower == 0)
392 {
393 std::cerr << "total power 0\n";
394 val = 0;
395 return false;
396 }
397
398 if constexpr (DEBUG)
399 {
400 std::cout << "Power Factor " << powerFactor << "\n";
401 std::cout << "Inlet Temp " << inletTemp << "\n";
402 std::cout << "Total Power" << totalPower << "\n";
403 }
404
405 // Calculate the exit air temp
406 // Texit = Tfp + (1.76 * TotalPower / CFM * Faltitude)
407 double reading = 1.76 * totalPower * altitudeFactor;
408 reading /= cfm;
409 reading += inletTemp;
410
411 if constexpr (DEBUG)
412 {
413 std::cout << "Reading 1: " << reading << "\n";
414 }
415
416 // Now perform the exponential average
417 // Calculate alpha based on SDR values and CFM
418 // Ai = As + (Af - As)/(QMax - QMin) * (CFM - QMin)
419
420 double alpha = 0.0;
421 if (cfm < qMin)
422 {
423 alpha = alphaS;
424 }
425 else if (cfm >= qMax)
426 {
427 alpha = alphaF;
428 }
429 else
430 {
431 alpha = alphaS + ((alphaF - alphaS) * (cfm - qMin) / (qMax - qMin));
432 }
433
434 auto time = std::chrono::system_clock::now();
435 if (!firstRead)
436 {
437 firstRead = true;
438 lastTime = time;
439 lastReading = reading;
440 }
441 double alphaDT =
442 std::chrono::duration_cast<std::chrono::seconds>(time - lastTime)
443 .count() *
444 alpha;
445
446 // cap at 1.0 or the below fails
447 if (alphaDT > 1.0)
448 {
449 alphaDT = 1.0;
450 }
451
452 if constexpr (DEBUG)
453 {
454 std::cout << "AlphaDT: " << alphaDT << "\n";
455 }
456
457 reading = ((reading * alphaDT) + (lastReading * (1.0 - alphaDT)));
458
459 if constexpr (DEBUG)
460 {
461 std::cout << "Reading 2: " << reading << "\n";
462 }
463
464 val = reading;
465 lastReading = reading;
466 lastTime = time;
467 return true;
468}
469
470void ExitAirTempSensor::checkThresholds(void)
471{
472 thresholds::checkThresholds(this);
473}
474
James Feistbc896df2018-11-26 16:28:17 -0800475static void loadVariantPathArray(
476 const boost::container::flat_map<std::string, BasicVariantType>& data,
477 const std::string& key, std::vector<std::string>& resp)
478{
479 auto it = data.find(key);
480 if (it == data.end())
481 {
482 std::cerr << "Configuration missing " << key << "\n";
483 throw std::invalid_argument("Key Missing");
484 }
485 BasicVariantType copy = it->second;
486 std::vector<std::string> config =
487 sdbusplus::message::variant_ns::get<std::vector<std::string>>(copy);
488 for (auto& str : config)
489 {
490 boost::replace_all(str, " ", "_");
491 }
492 resp = std::move(config);
493}
494
495void createSensor(sdbusplus::asio::object_server& objectServer,
James Feistb2eb3f52018-12-04 16:17:50 -0800496 std::shared_ptr<ExitAirTempSensor>& exitAirSensor,
James Feistbc896df2018-11-26 16:28:17 -0800497 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
498{
499 if (!dbusConnection)
500 {
501 std::cerr << "Connection not created\n";
502 return;
503 }
504 dbusConnection->async_method_call(
505 [&](boost::system::error_code ec, const ManagedObjectType& resp) {
506 if (ec)
507 {
508 std::cerr << "Error contacting entity manager\n";
509 return;
510 }
James Feistb2eb3f52018-12-04 16:17:50 -0800511 std::vector<std::unique_ptr<CFMSensor>> cfmSensors;
James Feistbc896df2018-11-26 16:28:17 -0800512 for (const auto& pathPair : resp)
513 {
514 for (const auto& entry : pathPair.second)
515 {
516 if (entry.first == exitAirIface)
517 {
James Feistbc896df2018-11-26 16:28:17 -0800518 // thresholds should be under the same path
519 std::vector<thresholds::Threshold> sensorThresholds;
520 parseThresholdsFromConfig(pathPair.second,
521 sensorThresholds);
James Feistb2eb3f52018-12-04 16:17:50 -0800522 if (!exitAirSensor)
James Feistbc896df2018-11-26 16:28:17 -0800523 {
James Feistb2eb3f52018-12-04 16:17:50 -0800524 std::string name =
525 loadVariant<std::string>(entry.second, "Name");
526 exitAirSensor = std::make_shared<ExitAirTempSensor>(
527 dbusConnection, name, pathPair.first.str,
James Feistbc896df2018-11-26 16:28:17 -0800528 objectServer, std::move(sensorThresholds));
529 }
530 else
531 {
James Feistb2eb3f52018-12-04 16:17:50 -0800532 exitAirSensor->thresholds = sensorThresholds;
James Feistbc896df2018-11-26 16:28:17 -0800533 }
534
James Feistb2eb3f52018-12-04 16:17:50 -0800535 exitAirSensor->powerFactorMin =
536 loadVariant<double>(entry.second, "PowerFactorMin");
537 exitAirSensor->powerFactorMax =
538 loadVariant<double>(entry.second, "PowerFactorMax");
539 exitAirSensor->qMin =
540 loadVariant<double>(entry.second, "QMin");
541 exitAirSensor->qMax =
542 loadVariant<double>(entry.second, "QMax");
543 exitAirSensor->alphaS =
544 loadVariant<double>(entry.second, "AlphaS");
545 exitAirSensor->alphaF =
546 loadVariant<double>(entry.second, "AlphaF");
James Feistbc896df2018-11-26 16:28:17 -0800547 }
548 else if (entry.first == cfmIface)
549
550 {
James Feistb2eb3f52018-12-04 16:17:50 -0800551 // thresholds should be under the same path
552 std::vector<thresholds::Threshold> sensorThresholds;
553 parseThresholdsFromConfig(pathPair.second,
554 sensorThresholds);
555 std::string name =
556 loadVariant<std::string>(entry.second, "Name");
557 auto sensor = std::make_unique<CFMSensor>(
558 dbusConnection, name, pathPair.first.str,
559 objectServer, std::move(sensorThresholds),
560 exitAirSensor);
561 loadVariantPathArray(entry.second, "Tachs",
562 sensor->tachs);
563 sensor->maxCFM =
564 loadVariant<double>(entry.second, "MaxCFM");
James Feistbc896df2018-11-26 16:28:17 -0800565
566 // change these into percent upon getting the data
James Feistb2eb3f52018-12-04 16:17:50 -0800567 sensor->c1 =
568 loadVariant<double>(entry.second, "C1") / 100;
569 sensor->c2 =
570 loadVariant<double>(entry.second, "C2") / 100;
571 sensor->tachMinPercent =
572 loadVariant<double>(entry.second,
573 "TachMinPercent") /
James Feistbc896df2018-11-26 16:28:17 -0800574 100;
James Feistb2eb3f52018-12-04 16:17:50 -0800575 sensor->tachMaxPercent =
576 loadVariant<double>(entry.second,
577 "TachMaxPercent") /
James Feistbc896df2018-11-26 16:28:17 -0800578 100;
579
James Feistb2eb3f52018-12-04 16:17:50 -0800580 cfmSensors.emplace_back(std::move(sensor));
James Feistbc896df2018-11-26 16:28:17 -0800581 }
582 }
583 }
James Feistb2eb3f52018-12-04 16:17:50 -0800584 if (exitAirSensor)
James Feistbc896df2018-11-26 16:28:17 -0800585 {
James Feistb2eb3f52018-12-04 16:17:50 -0800586 exitAirSensor->cfmSensors = std::move(cfmSensors);
James Feistbc896df2018-11-26 16:28:17 -0800587
James Feistb2eb3f52018-12-04 16:17:50 -0800588 // todo: when power sensors are done delete this fake
589 // reading
590 exitAirSensor->powerReadings["foo"] = 144.0;
James Feistbc896df2018-11-26 16:28:17 -0800591
James Feistb2eb3f52018-12-04 16:17:50 -0800592 exitAirSensor->updateReading();
James Feistbc896df2018-11-26 16:28:17 -0800593 }
594 },
595 entityManagerName, "/", "org.freedesktop.DBus.ObjectManager",
596 "GetManagedObjects");
597}
598
599int main(int argc, char** argv)
600{
601
602 boost::asio::io_service io;
603 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
604 systemBus->request_name("xyz.openbmc_project.ExitAirTempSensor");
605 sdbusplus::asio::object_server objectServer(systemBus);
606 std::shared_ptr<ExitAirTempSensor> sensor =
607 nullptr; // wait until we find the config
608 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
609
610 io.post([&]() { createSensor(objectServer, sensor, systemBus); });
611
612 boost::asio::deadline_timer configTimer(io);
613
614 std::function<void(sdbusplus::message::message&)> eventHandler =
615 [&](sdbusplus::message::message& message) {
616 configTimer.expires_from_now(boost::posix_time::seconds(1));
617 // create a timer because normally multiple properties change
618 configTimer.async_wait([&](const boost::system::error_code& ec) {
619 if (ec == boost::asio::error::operation_aborted)
620 {
621 return; // we're being canceled
622 }
623 createSensor(objectServer, sensor, systemBus);
624 if (!sensor)
625 {
626 std::cout << "Configuration not detected\n";
627 }
628 });
629 };
630 constexpr const std::array<const char*, 2> monitorIfaces = {exitAirIface,
631 cfmIface};
632 for (const char* type : monitorIfaces)
633 {
634 auto match = std::make_unique<sdbusplus::bus::match::match>(
635 static_cast<sdbusplus::bus::bus&>(*systemBus),
636 "type='signal',member='PropertiesChanged',path_namespace='" +
637 std::string(inventoryPath) + "',arg0namespace='" + type + "'",
638 eventHandler);
639 matches.emplace_back(std::move(match));
640 }
641
642 io.run();
643}