blob: 6844dfaf0675be758d8c04bc2a8ef9f0e4c5aa6e [file] [log] [blame]
Tony Lee89659212019-06-21 17:34:14 +08001#include <iostream>
2#include <phosphor-logging/elog-errors.hpp>
3#include <phosphor-logging/elog.hpp>
4#include <phosphor-logging/log.hpp>
5#include <sdbusplus/bus.hpp>
6#include <sdbusplus/bus/match.hpp>
7#include <sdbusplus/message.hpp>
8#include <xyz/openbmc_project/Common/error.hpp>
9
10namespace phosphor
11{
12namespace nvme
13{
14namespace util
15{
16
17using namespace phosphor::logging;
18
19class SDBusPlus
20{
21 public:
22 template <typename T>
23 static auto
24 setProperty(sdbusplus::bus::bus& bus, const std::string& busName,
25 const std::string& objPath, const std::string& interface,
26 const std::string& property, const T& value)
27 {
Patrick Williams05eedaa2020-05-13 17:58:42 -050028 std::variant<T> data = value;
Tony Lee89659212019-06-21 17:34:14 +080029
30 try
31 {
32 auto methodCall = bus.new_method_call(
33 busName.c_str(), objPath.c_str(), DBUS_PROPERTY_IFACE, "Set");
34
35 methodCall.append(interface.c_str());
36 methodCall.append(property);
37 methodCall.append(data);
38
39 auto reply = bus.call(methodCall);
40 }
41 catch (const std::exception& e)
42 {
43 log<level::ERR>("Set properties fail.",
44 entry("ERROR = %s", e.what()),
45 entry("Object path = %s", objPath.c_str()));
46 return;
47 }
48 }
49
50 template <typename Property>
51 static auto
52 getProperty(sdbusplus::bus::bus& bus, const std::string& busName,
53 const std::string& objPath, const std::string& interface,
54 const std::string& property)
55 {
56 auto methodCall = bus.new_method_call(busName.c_str(), objPath.c_str(),
57 DBUS_PROPERTY_IFACE, "Get");
58
59 methodCall.append(interface.c_str());
60 methodCall.append(property);
61
Patrick Williams05eedaa2020-05-13 17:58:42 -050062 std::variant<Property> value;
Tony Lee89659212019-06-21 17:34:14 +080063
64 try
65 {
66 auto reply = bus.call(methodCall);
67 reply.read(value);
68 }
69 catch (const std::exception& e)
70 {
71 log<level::ERR>("Get properties fail.",
72 entry("ERROR = %s", e.what()),
73 entry("Object path = %s", objPath.c_str()));
74 return false;
75 }
76
Patrick Williamsc80e6e22020-05-13 11:50:34 -050077 return std::get<Property>(value);
Tony Lee89659212019-06-21 17:34:14 +080078 }
79
80 template <typename... Args>
81 static auto CallMethod(sdbusplus::bus::bus& bus, const std::string& busName,
82 const std::string& objPath,
83 const std::string& interface,
84 const std::string& method, Args&&... args)
85 {
86 auto reqMsg = bus.new_method_call(busName.c_str(), objPath.c_str(),
87 interface.c_str(), method.c_str());
88 reqMsg.append(std::forward<Args>(args)...);
89 try
90 {
91 auto respMsg = bus.call(reqMsg);
92 }
93 catch (const std::exception& e)
94 {
95 log<level::ERR>("Call method fail.", entry("ERROR = %s", e.what()),
96 entry("Object path = %s", objPath.c_str()));
97 return;
98 }
99 }
100};
101
102} // namespace util
103} // namespace nvme
104} // namespace phosphor