blob: 4983f52c35f19ccf73b1818f9ea43ab2fd40da42 [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";
James Feist1ccdb5e2019-01-24 09:44:01 -0800135 return;
James Feistb2eb3f52018-12-04 16:17:50 -0800136 }
137
138 double max = loadVariant<double>(data, "MaxValue");
139 double min = loadVariant<double>(data, "MinValue");
140 tachRanges[path] = std::make_pair(min, max);
141 updateReading();
142 },
143 serviceName, path, "org.freedesktop.DBus.Properties", "GetAll",
144 "xyz.openbmc_project.Sensor.Value");
145}
146
147void CFMSensor::checkThresholds(void)
148{
149 thresholds::checkThresholds(this);
150}
151
152void CFMSensor::updateReading(void)
153{
154 double val = 0.0;
155 if (calculate(val))
156 {
157 if (value != val && parent)
158 {
159 parent->updateReading();
160 }
161 updateValue(val);
162 }
163 else
164 {
165 updateValue(std::numeric_limits<double>::quiet_NaN());
166 }
167}
168
169bool CFMSensor::calculate(double& value)
170{
171 double totalCFM = 0;
172 for (const std::string& tachName : tachs)
173 {
174 auto findReading = std::find_if(
175 tachReadings.begin(), tachReadings.end(), [&](const auto& item) {
176 return boost::ends_with(item.first, tachName);
177 });
178 auto findRange = std::find_if(
179 tachRanges.begin(), tachRanges.end(), [&](const auto& item) {
180 return boost::ends_with(item.first, tachName);
181 });
182 if (findReading == tachReadings.end())
183 {
James Feista96329f2019-01-24 10:08:27 -0800184 if (DEBUG)
185 {
186 std::cerr << "Can't find " << tachName << "in readings\n";
187 }
James Feistb2eb3f52018-12-04 16:17:50 -0800188 return false; // haven't gotten a reading
189 }
190
191 if (findRange == tachRanges.end())
192 {
193 std::cerr << "Can't find " << tachName << "in ranges\n";
194 return false; // haven't gotten a max / min
195 }
196
197 // avoid divide by 0
198 if (findRange->second.second == 0)
199 {
200 std::cerr << "Tach Max Set to 0 " << tachName << "\n";
201 return false;
202 }
203
204 double rpm = findReading->second;
205
206 // for now assume the min for a fan is always 0, divide by max to get
207 // percent and mult by 100
208 rpm /= findRange->second.second;
209 rpm *= 100;
210
211 if constexpr (DEBUG)
212 {
213 std::cout << "Tach " << tachName << "at " << rpm << "\n";
214 }
215
216 // Do a linear interpolation to get Ci
217 // Ci = C1 + (C2 - C1)/(RPM2 - RPM1) * (TACHi - TACH1)
218
219 double ci = 0;
220 if (rpm == 0)
221 {
222 ci = 0;
223 }
224 else if (rpm < tachMinPercent)
225 {
226 ci = c1;
227 }
228 else if (rpm > tachMaxPercent)
229 {
230 ci = c2;
231 }
232 else
233 {
234 ci = c1 + (((c2 - c1) * (rpm - tachMinPercent)) /
235 (tachMaxPercent - tachMinPercent));
236 }
237
238 // Now calculate the CFM for this tach
239 // CFMi = Ci * Qmaxi * TACHi
240 totalCFM += ci * maxCFM * rpm;
241 }
242
243 // divide by 100 since rpm is in percent
244 value = totalCFM / 100;
245}
246
247static constexpr double exitAirMaxReading = 127;
248static constexpr double exitAirMinReading = -128;
James Feistbc896df2018-11-26 16:28:17 -0800249ExitAirTempSensor::ExitAirTempSensor(
250 std::shared_ptr<sdbusplus::asio::connection>& conn,
James Feistb2eb3f52018-12-04 16:17:50 -0800251 const std::string& sensorName, const std::string& sensorConfiguration,
James Feistbc896df2018-11-26 16:28:17 -0800252 sdbusplus::asio::object_server& objectServer,
253 std::vector<thresholds::Threshold>&& thresholds) :
James Feistb2eb3f52018-12-04 16:17:50 -0800254 Sensor(boost::replace_all_copy(sensorName, " ", "_"),
255 "" /* todo: remove arg from base*/, std::move(thresholds),
256 sensorConfiguration, "xyz.openbmc_project.Configuration.ExitAirTemp",
257 exitAirMaxReading, exitAirMinReading),
James Feistbc896df2018-11-26 16:28:17 -0800258 dbusConnection(conn)
259{
260 sensorInterface = objectServer.add_interface(
261 "/xyz/openbmc_project/sensors/temperature/" + name,
262 "xyz.openbmc_project.Sensor.Value");
263
264 if (thresholds::hasWarningInterface(thresholds))
265 {
266 thresholdInterfaceWarning = objectServer.add_interface(
267 "/xyz/openbmc_project/sensors/temperature/" + name,
268 "xyz.openbmc_project.Sensor.Threshold.Warning");
269 }
270 if (thresholds::hasCriticalInterface(thresholds))
271 {
272 thresholdInterfaceCritical = objectServer.add_interface(
273 "/xyz/openbmc_project/sensors/temperature/" + name,
274 "xyz.openbmc_project.Sensor.Threshold.Critical");
275 }
276 setInitialProperties(conn);
277 setupMatches();
James Feist71d31b22019-01-02 16:57:54 -0800278 setupPowerMatch(conn);
James Feistbc896df2018-11-26 16:28:17 -0800279}
280
281ExitAirTempSensor::~ExitAirTempSensor()
282{
283 // this sensor currently isn't destroyed so we don't care
284}
285
286void ExitAirTempSensor::setupMatches(void)
287{
288
James Feistb2eb3f52018-12-04 16:17:50 -0800289 constexpr const std::array<const char*, 2> matchTypes = {
290 "power", inletTemperatureSensor};
James Feistbc896df2018-11-26 16:28:17 -0800291
James Feistb2eb3f52018-12-04 16:17:50 -0800292 for (const std::string& type : matchTypes)
James Feistbc896df2018-11-26 16:28:17 -0800293 {
James Feistb2eb3f52018-12-04 16:17:50 -0800294 setupSensorMatch(matches, *dbusConnection, type,
295 [this, type](const double& value,
296 sdbusplus::message::message& message) {
297 if (type == "power")
298 {
299 powerReadings[message.get_path()] = value;
300 }
301 else if (type == inletTemperatureSensor)
302 {
303 inletTemp = value;
304 }
305 updateReading();
306 });
James Feistbc896df2018-11-26 16:28:17 -0800307 }
308}
309
310void ExitAirTempSensor::updateReading(void)
311{
312
313 double val = 0.0;
314 if (calculate(val))
315 {
316 updateValue(val);
317 }
318 else
319 {
320 updateValue(std::numeric_limits<double>::quiet_NaN());
321 }
322}
323
James Feistb2eb3f52018-12-04 16:17:50 -0800324double ExitAirTempSensor::getTotalCFM(void)
James Feistbc896df2018-11-26 16:28:17 -0800325{
James Feistb2eb3f52018-12-04 16:17:50 -0800326 double sum = 0;
327 for (auto& sensor : cfmSensors)
James Feistbc896df2018-11-26 16:28:17 -0800328 {
James Feistb2eb3f52018-12-04 16:17:50 -0800329 double reading = 0;
330 if (!sensor->calculate(reading))
James Feistbc896df2018-11-26 16:28:17 -0800331 {
James Feistbc896df2018-11-26 16:28:17 -0800332 return -1;
333 }
James Feistb2eb3f52018-12-04 16:17:50 -0800334 sum += reading;
James Feistbc896df2018-11-26 16:28:17 -0800335 }
James Feistb2eb3f52018-12-04 16:17:50 -0800336
337 return sum;
James Feistbc896df2018-11-26 16:28:17 -0800338}
339
340bool ExitAirTempSensor::calculate(double& val)
341{
342 static bool firstRead = false;
343 double cfm = getTotalCFM();
344 if (cfm <= 0)
345 {
346 std::cerr << "Error getting cfm\n";
347 return false;
348 }
349
350 // if there is an error getting inlet temp, return error
351 if (std::isnan(inletTemp))
352 {
353 std::cerr << "Cannot get inlet temp\n";
354 val = 0;
355 return false;
356 }
357
358 // if fans are off, just make the exit temp equal to inlet
James Feist71d31b22019-01-02 16:57:54 -0800359 if (!isPowerOn())
James Feistbc896df2018-11-26 16:28:17 -0800360 {
361 val = inletTemp;
362 return true;
363 }
364
365 double totalPower = 0;
366 for (const auto& reading : powerReadings)
367 {
368 if (std::isnan(reading.second))
369 {
370 continue;
371 }
372 totalPower += reading.second;
373 }
374
375 // Calculate power correction factor
376 // Ci = CL + (CH - CL)/(QMax - QMin) * (CFM - QMin)
377 float powerFactor = 0.0;
378 if (cfm <= qMin)
379 {
380 powerFactor = powerFactorMin;
381 }
382 else if (cfm >= qMax)
383 {
384 powerFactor = powerFactorMax;
385 }
386 else
387 {
388 powerFactor = powerFactorMin + ((powerFactorMax - powerFactorMin) /
389 (qMax - qMin) * (cfm - qMin));
390 }
391
392 totalPower *= powerFactor;
393 totalPower += pOffset;
394
395 if (totalPower == 0)
396 {
397 std::cerr << "total power 0\n";
398 val = 0;
399 return false;
400 }
401
402 if constexpr (DEBUG)
403 {
404 std::cout << "Power Factor " << powerFactor << "\n";
405 std::cout << "Inlet Temp " << inletTemp << "\n";
406 std::cout << "Total Power" << totalPower << "\n";
407 }
408
409 // Calculate the exit air temp
410 // Texit = Tfp + (1.76 * TotalPower / CFM * Faltitude)
411 double reading = 1.76 * totalPower * altitudeFactor;
412 reading /= cfm;
413 reading += inletTemp;
414
415 if constexpr (DEBUG)
416 {
417 std::cout << "Reading 1: " << reading << "\n";
418 }
419
420 // Now perform the exponential average
421 // Calculate alpha based on SDR values and CFM
422 // Ai = As + (Af - As)/(QMax - QMin) * (CFM - QMin)
423
424 double alpha = 0.0;
425 if (cfm < qMin)
426 {
427 alpha = alphaS;
428 }
429 else if (cfm >= qMax)
430 {
431 alpha = alphaF;
432 }
433 else
434 {
435 alpha = alphaS + ((alphaF - alphaS) * (cfm - qMin) / (qMax - qMin));
436 }
437
438 auto time = std::chrono::system_clock::now();
439 if (!firstRead)
440 {
441 firstRead = true;
442 lastTime = time;
443 lastReading = reading;
444 }
445 double alphaDT =
446 std::chrono::duration_cast<std::chrono::seconds>(time - lastTime)
447 .count() *
448 alpha;
449
450 // cap at 1.0 or the below fails
451 if (alphaDT > 1.0)
452 {
453 alphaDT = 1.0;
454 }
455
456 if constexpr (DEBUG)
457 {
458 std::cout << "AlphaDT: " << alphaDT << "\n";
459 }
460
461 reading = ((reading * alphaDT) + (lastReading * (1.0 - alphaDT)));
462
463 if constexpr (DEBUG)
464 {
465 std::cout << "Reading 2: " << reading << "\n";
466 }
467
468 val = reading;
469 lastReading = reading;
470 lastTime = time;
471 return true;
472}
473
474void ExitAirTempSensor::checkThresholds(void)
475{
476 thresholds::checkThresholds(this);
477}
478
James Feistbc896df2018-11-26 16:28:17 -0800479static void loadVariantPathArray(
480 const boost::container::flat_map<std::string, BasicVariantType>& data,
481 const std::string& key, std::vector<std::string>& resp)
482{
483 auto it = data.find(key);
484 if (it == data.end())
485 {
486 std::cerr << "Configuration missing " << key << "\n";
487 throw std::invalid_argument("Key Missing");
488 }
489 BasicVariantType copy = it->second;
490 std::vector<std::string> config =
491 sdbusplus::message::variant_ns::get<std::vector<std::string>>(copy);
492 for (auto& str : config)
493 {
494 boost::replace_all(str, " ", "_");
495 }
496 resp = std::move(config);
497}
498
499void createSensor(sdbusplus::asio::object_server& objectServer,
James Feistb2eb3f52018-12-04 16:17:50 -0800500 std::shared_ptr<ExitAirTempSensor>& exitAirSensor,
James Feistbc896df2018-11-26 16:28:17 -0800501 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
502{
503 if (!dbusConnection)
504 {
505 std::cerr << "Connection not created\n";
506 return;
507 }
508 dbusConnection->async_method_call(
509 [&](boost::system::error_code ec, const ManagedObjectType& resp) {
510 if (ec)
511 {
512 std::cerr << "Error contacting entity manager\n";
513 return;
514 }
James Feistb2eb3f52018-12-04 16:17:50 -0800515 std::vector<std::unique_ptr<CFMSensor>> cfmSensors;
James Feistbc896df2018-11-26 16:28:17 -0800516 for (const auto& pathPair : resp)
517 {
518 for (const auto& entry : pathPair.second)
519 {
520 if (entry.first == exitAirIface)
521 {
James Feistbc896df2018-11-26 16:28:17 -0800522 // thresholds should be under the same path
523 std::vector<thresholds::Threshold> sensorThresholds;
524 parseThresholdsFromConfig(pathPair.second,
525 sensorThresholds);
James Feistb2eb3f52018-12-04 16:17:50 -0800526 if (!exitAirSensor)
James Feistbc896df2018-11-26 16:28:17 -0800527 {
James Feistb2eb3f52018-12-04 16:17:50 -0800528 std::string name =
529 loadVariant<std::string>(entry.second, "Name");
530 exitAirSensor = std::make_shared<ExitAirTempSensor>(
531 dbusConnection, name, pathPair.first.str,
James Feistbc896df2018-11-26 16:28:17 -0800532 objectServer, std::move(sensorThresholds));
533 }
534 else
535 {
James Feistb2eb3f52018-12-04 16:17:50 -0800536 exitAirSensor->thresholds = sensorThresholds;
James Feistbc896df2018-11-26 16:28:17 -0800537 }
538
James Feistb2eb3f52018-12-04 16:17:50 -0800539 exitAirSensor->powerFactorMin =
540 loadVariant<double>(entry.second, "PowerFactorMin");
541 exitAirSensor->powerFactorMax =
542 loadVariant<double>(entry.second, "PowerFactorMax");
543 exitAirSensor->qMin =
544 loadVariant<double>(entry.second, "QMin");
545 exitAirSensor->qMax =
546 loadVariant<double>(entry.second, "QMax");
547 exitAirSensor->alphaS =
548 loadVariant<double>(entry.second, "AlphaS");
549 exitAirSensor->alphaF =
550 loadVariant<double>(entry.second, "AlphaF");
James Feistbc896df2018-11-26 16:28:17 -0800551 }
552 else if (entry.first == cfmIface)
553
554 {
James Feistb2eb3f52018-12-04 16:17:50 -0800555 // thresholds should be under the same path
556 std::vector<thresholds::Threshold> sensorThresholds;
557 parseThresholdsFromConfig(pathPair.second,
558 sensorThresholds);
559 std::string name =
560 loadVariant<std::string>(entry.second, "Name");
561 auto sensor = std::make_unique<CFMSensor>(
562 dbusConnection, name, pathPair.first.str,
563 objectServer, std::move(sensorThresholds),
564 exitAirSensor);
565 loadVariantPathArray(entry.second, "Tachs",
566 sensor->tachs);
567 sensor->maxCFM =
568 loadVariant<double>(entry.second, "MaxCFM");
James Feistbc896df2018-11-26 16:28:17 -0800569
570 // change these into percent upon getting the data
James Feistb2eb3f52018-12-04 16:17:50 -0800571 sensor->c1 =
572 loadVariant<double>(entry.second, "C1") / 100;
573 sensor->c2 =
574 loadVariant<double>(entry.second, "C2") / 100;
575 sensor->tachMinPercent =
576 loadVariant<double>(entry.second,
577 "TachMinPercent") /
James Feistbc896df2018-11-26 16:28:17 -0800578 100;
James Feistb2eb3f52018-12-04 16:17:50 -0800579 sensor->tachMaxPercent =
580 loadVariant<double>(entry.second,
581 "TachMaxPercent") /
James Feistbc896df2018-11-26 16:28:17 -0800582 100;
583
James Feistb2eb3f52018-12-04 16:17:50 -0800584 cfmSensors.emplace_back(std::move(sensor));
James Feistbc896df2018-11-26 16:28:17 -0800585 }
586 }
587 }
James Feistb2eb3f52018-12-04 16:17:50 -0800588 if (exitAirSensor)
James Feistbc896df2018-11-26 16:28:17 -0800589 {
James Feistb2eb3f52018-12-04 16:17:50 -0800590 exitAirSensor->cfmSensors = std::move(cfmSensors);
James Feistbc896df2018-11-26 16:28:17 -0800591
James Feistb2eb3f52018-12-04 16:17:50 -0800592 // todo: when power sensors are done delete this fake
593 // reading
594 exitAirSensor->powerReadings["foo"] = 144.0;
James Feistbc896df2018-11-26 16:28:17 -0800595
James Feistb2eb3f52018-12-04 16:17:50 -0800596 exitAirSensor->updateReading();
James Feistbc896df2018-11-26 16:28:17 -0800597 }
598 },
599 entityManagerName, "/", "org.freedesktop.DBus.ObjectManager",
600 "GetManagedObjects");
601}
602
603int main(int argc, char** argv)
604{
605
606 boost::asio::io_service io;
607 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
608 systemBus->request_name("xyz.openbmc_project.ExitAirTempSensor");
609 sdbusplus::asio::object_server objectServer(systemBus);
610 std::shared_ptr<ExitAirTempSensor> sensor =
611 nullptr; // wait until we find the config
612 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
613
614 io.post([&]() { createSensor(objectServer, sensor, systemBus); });
615
616 boost::asio::deadline_timer configTimer(io);
617
618 std::function<void(sdbusplus::message::message&)> eventHandler =
619 [&](sdbusplus::message::message& message) {
620 configTimer.expires_from_now(boost::posix_time::seconds(1));
621 // create a timer because normally multiple properties change
622 configTimer.async_wait([&](const boost::system::error_code& ec) {
623 if (ec == boost::asio::error::operation_aborted)
624 {
625 return; // we're being canceled
626 }
627 createSensor(objectServer, sensor, systemBus);
628 if (!sensor)
629 {
630 std::cout << "Configuration not detected\n";
631 }
632 });
633 };
634 constexpr const std::array<const char*, 2> monitorIfaces = {exitAirIface,
635 cfmIface};
636 for (const char* type : monitorIfaces)
637 {
638 auto match = std::make_unique<sdbusplus::bus::match::match>(
639 static_cast<sdbusplus::bus::bus&>(*systemBus),
640 "type='signal',member='PropertiesChanged',path_namespace='" +
641 std::string(inventoryPath) + "',arg0namespace='" + type + "'",
642 eventHandler);
643 matches.emplace_back(std::move(match));
644 }
645
646 io.run();
647}