xref: /openbmc/dbus-sensors/src/PSUSensor.cpp (revision eacbfdd1)
1 /*
2 // Copyright (c) 2019 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 "PSUSensor.hpp"
18 
19 #include "DeviceMgmt.hpp"
20 #include "SensorPaths.hpp"
21 #include "Thresholds.hpp"
22 #include "Utils.hpp"
23 #include "sensor.hpp"
24 
25 #include <boost/asio/buffer.hpp>
26 #include <boost/asio/error.hpp>
27 #include <boost/asio/io_context.hpp>
28 #include <boost/asio/random_access_file.hpp>
29 #include <sdbusplus/asio/connection.hpp>
30 #include <sdbusplus/asio/object_server.hpp>
31 
32 #include <array>
33 #include <chrono>
34 #include <cstddef>
35 #include <iostream>
36 #include <limits>
37 #include <memory>
38 #include <stdexcept>
39 #include <string>
40 #include <utility>
41 #include <vector>
42 
43 static constexpr const char* sensorPathPrefix = "/xyz/openbmc_project/sensors/";
44 
45 static constexpr bool debug = false;
46 
PSUSensor(const std::string & path,const std::string & objectType,sdbusplus::asio::object_server & objectServer,std::shared_ptr<sdbusplus::asio::connection> & conn,boost::asio::io_context & io,const std::string & sensorName,std::vector<thresholds::Threshold> && thresholdsIn,const std::string & sensorConfiguration,const PowerState & powerState,const std::string & sensorUnits,unsigned int factor,double max,double min,double offset,const std::string & label,size_t tSize,double pollRate,const std::shared_ptr<I2CDevice> & i2cDevice)47 PSUSensor::PSUSensor(const std::string& path, const std::string& objectType,
48                      sdbusplus::asio::object_server& objectServer,
49                      std::shared_ptr<sdbusplus::asio::connection>& conn,
50                      boost::asio::io_context& io, const std::string& sensorName,
51                      std::vector<thresholds::Threshold>&& thresholdsIn,
52                      const std::string& sensorConfiguration,
53                      const PowerState& powerState,
54                      const std::string& sensorUnits, unsigned int factor,
55                      double max, double min, double offset,
56                      const std::string& label, size_t tSize, double pollRate,
57                      const std::shared_ptr<I2CDevice>& i2cDevice) :
58     Sensor(escapeName(sensorName), std::move(thresholdsIn), sensorConfiguration,
59            objectType, false, false, max, min, conn, powerState),
60     i2cDevice(i2cDevice), objServer(objectServer),
61     inputDev(io, path, boost::asio::random_access_file::read_only),
62     waitTimer(io), path(path), sensorFactor(factor), sensorOffset(offset),
63     thresholdTimer(io)
64 {
65     buffer = std::make_shared<std::array<char, 128>>();
66     std::string unitPath = sensor_paths::getPathForUnits(sensorUnits);
67     if constexpr (debug)
68     {
69         std::cerr << "Constructed sensor: path " << path << " type "
70                   << objectType << " config " << sensorConfiguration
71                   << " typename " << unitPath << " factor " << factor << " min "
72                   << min << " max " << max << " offset " << offset << " name \""
73                   << sensorName << "\"\n";
74     }
75     if (pollRate > 0.0)
76     {
77         sensorPollMs = static_cast<unsigned int>(pollRate * 1000);
78     }
79 
80     std::string dbusPath = sensorPathPrefix + unitPath + "/" + name;
81 
82     sensorInterface = objectServer.add_interface(
83         dbusPath, "xyz.openbmc_project.Sensor.Value");
84 
85     for (const auto& threshold : thresholds)
86     {
87         std::string interface = thresholds::getInterface(threshold.level);
88         thresholdInterfaces[static_cast<size_t>(threshold.level)] =
89             objectServer.add_interface(dbusPath, interface);
90     }
91 
92     // This should be called before initializing association.
93     // createInventoryAssoc() does add more associations before doing
94     // register and initialize "Associations" property.
95     if (label.empty() || tSize == thresholds.size())
96     {
97         setInitialProperties(sensorUnits);
98     }
99     else
100     {
101         setInitialProperties(sensorUnits, label, tSize);
102     }
103 
104     association = objectServer.add_interface(dbusPath, association::interface);
105 
106     createInventoryAssoc(conn, association, configurationPath);
107 }
108 
~PSUSensor()109 PSUSensor::~PSUSensor()
110 {
111     deactivate();
112 
113     objServer.remove_interface(sensorInterface);
114     for (const auto& iface : thresholdInterfaces)
115     {
116         objServer.remove_interface(iface);
117     }
118     objServer.remove_interface(association);
119 }
120 
isActive()121 bool PSUSensor::isActive()
122 {
123     return inputDev.is_open();
124 }
125 
activate(const std::string & newPath,const std::shared_ptr<I2CDevice> & newI2CDevice)126 void PSUSensor::activate(const std::string& newPath,
127                          const std::shared_ptr<I2CDevice>& newI2CDevice)
128 {
129     path = newPath;
130     i2cDevice = newI2CDevice;
131     inputDev.open(path, boost::asio::random_access_file::read_only);
132     markAvailable(true);
133     setupRead();
134 }
135 
deactivate()136 void PSUSensor::deactivate()
137 {
138     markAvailable(false);
139     // close the input dev to cancel async operations
140     inputDev.close();
141     waitTimer.cancel();
142     i2cDevice = nullptr;
143     path = "";
144 }
145 
setupRead()146 void PSUSensor::setupRead()
147 {
148     if (!readingStateGood())
149     {
150         markAvailable(false);
151         updateValue(std::numeric_limits<double>::quiet_NaN());
152         restartRead();
153         return;
154     }
155 
156     if (buffer == nullptr)
157     {
158         std::cerr << "Buffer was invalid?";
159         return;
160     }
161 
162     std::weak_ptr<PSUSensor> weak = weak_from_this();
163     // Note, we are building a asio buffer that is one char smaller than
164     // the actual data structure, so that we can always append the null
165     // terminator.  This can go away once std::from_chars<double> is available
166     // in the standard
167     inputDev.async_read_some_at(
168         0, boost::asio::buffer(buffer->data(), buffer->size() - 1),
169         [weak, buffer{buffer}](const boost::system::error_code& ec,
170                                size_t bytesRead) {
171         std::shared_ptr<PSUSensor> self = weak.lock();
172         if (!self)
173         {
174             return;
175         }
176 
177         self->handleResponse(ec, bytesRead);
178     });
179 }
180 
restartRead()181 void PSUSensor::restartRead()
182 {
183     std::weak_ptr<PSUSensor> weakRef = weak_from_this();
184     waitTimer.expires_after(std::chrono::milliseconds(sensorPollMs));
185     waitTimer.async_wait([weakRef](const boost::system::error_code& ec) {
186         if (ec == boost::asio::error::operation_aborted)
187         {
188             std::cerr << "Failed to reschedule\n";
189             return;
190         }
191         std::shared_ptr<PSUSensor> self = weakRef.lock();
192         if (self)
193         {
194             self->setupRead();
195         }
196     });
197 }
198 
199 // Create a buffer expected to be able to hold more characters than will be
200 // present in the input file.
handleResponse(const boost::system::error_code & err,size_t bytesRead)201 void PSUSensor::handleResponse(const boost::system::error_code& err,
202                                size_t bytesRead)
203 {
204     if (err == boost::asio::error::operation_aborted)
205     {
206         std::cerr << "Read aborted\n";
207         return;
208     }
209     if ((err == boost::system::errc::bad_file_descriptor) ||
210         (err == boost::asio::error::misc_errors::not_found))
211     {
212         std::cerr << "Bad file descriptor for " << path << "\n";
213         return;
214     }
215     if (err || bytesRead == 0)
216     {
217         if (readingStateGood())
218         {
219             std::cerr << name << " read failed\n";
220         }
221         restartRead();
222         return;
223     }
224 
225     // null terminate the string so we don't walk off the end
226     std::array<char, 128>& bufferRef = *buffer;
227     bufferRef[bytesRead] = '\0';
228 
229     try
230     {
231         rawValue = std::stod(bufferRef.data());
232         updateValue((rawValue / sensorFactor) + sensorOffset);
233     }
234     catch (const std::invalid_argument&)
235     {
236         std::cerr << "Could not parse  input from " << path << "\n";
237         incrementError();
238     }
239 
240     restartRead();
241 }
242 
checkThresholds()243 void PSUSensor::checkThresholds()
244 {
245     if (!readingStateGood())
246     {
247         return;
248     }
249 
250     thresholds::checkThresholdsPowerDelay(weak_from_this(), thresholdTimer);
251 }
252