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