xref: /openbmc/phosphor-dbus-monitor/src/sdbusplus.hpp (revision fac1b1035ad5a0339fc1af600866343452dd77d3)
1 #pragma once
2 
3 #include <sdbusplus/bus.hpp>
4 #include <sdbusplus/message.hpp>
5 #include <sdbusplus/bus/match.hpp>
6 
7 namespace phosphor
8 {
9 namespace dbus
10 {
11 namespace monitoring
12 {
13 
14 /** @class SDBusPlus
15  *  @brief DBus access delegate implementation for sdbusplus.
16  */
17 class SDBusPlus
18 {
19     private:
20         static auto& getBus()
21         {
22             static auto bus = sdbusplus::bus::new_default();
23             return bus;
24         }
25 
26         static auto& getWatches()
27         {
28             static std::vector<sdbusplus::bus::match::match> watches;
29             return watches;
30         }
31 
32     public:
33         /** @brief Invoke a method. */
34         template <typename ...Args>
35         static auto callMethod(
36             const std::string& busName,
37             const std::string& path,
38             const std::string& interface,
39             const std::string& method,
40             Args&& ... args)
41         {
42             auto reqMsg = getBus().new_method_call(
43                               busName.c_str(),
44                               path.c_str(),
45                               interface.c_str(),
46                               method.c_str());
47             reqMsg.append(std::forward<Args>(args)...);
48             return getBus().call(reqMsg);
49         }
50 
51         /** @brief Invoke a method and read the response. */
52         template <typename Ret, typename ...Args>
53         static auto callMethodAndRead(
54             const std::string& busName,
55             const std::string& path,
56             const std::string& interface,
57             const std::string& method,
58             Args&& ... args)
59         {
60             Ret resp;
61             sdbusplus::message::message respMsg =
62                 callMethod<Args...>(
63                     busName,
64                     path,
65                     interface,
66                     method,
67                     std::forward<Args>(args)...);
68             respMsg.read(resp);
69             return resp;
70         }
71 
72         /** @brief Register a DBus signal callback. */
73         static auto addMatch(
74             const std::string& match,
75             const sdbusplus::bus::match::match::callback_t& callback)
76         {
77             getWatches().emplace_back(
78                     getBus(),
79                     match,
80                     callback);
81         }
82 };
83 
84 } // namespace monitoring
85 } // namespace dbus
86 } // namespace phosphor
87