pldm: Refactor DBusHandler interface
Add a static method to get the sdbusplus::bus in DBusHandler class and
instead of duplicate calls to sdbusplus::bus::new_default().
Signed-off-by: George Liu <liuxiwei@inspur.com>
Change-Id: I4a4ca84db7c301c9a82099de3b0361bbe9fa8c4c
diff --git a/utils.hpp b/utils.hpp
index bbdbc38..fecf12e 100644
--- a/utils.hpp
+++ b/utils.hpp
@@ -86,16 +86,6 @@
std::vector<set_effecter_state_field>& stateField);
/**
- * @brief Get the DBUS Service name for the input dbus path
- * @param[in] bus - DBUS Bus Object
- * @param[in] path - DBUS object path
- * @param[in] interface - DBUS Interface
- * @return std::string - the dbus service name
- */
-std::string getService(sdbusplus::bus::bus& bus, const std::string& path,
- const std::string& interface);
-
-/**
* @brief creates an error log
* @param[in] errorMsg - the error message
*/
@@ -138,6 +128,21 @@
class DBusHandler
{
public:
+ /** @brief Get the bus connection. */
+ static auto& getBus()
+ {
+ static auto bus = sdbusplus::bus::new_default();
+ return bus;
+ }
+
+ /**
+ * @brief Get the DBUS Service name for the input dbus path
+ * @param[in] path - DBUS object path
+ * @param[in] interface - DBUS Interface
+ * @return std::string - the dbus service name
+ */
+ std::string getService(const char* path, const char* interface) const;
+
/** @brief API to set a D-Bus property
*
* @param[in] objPath - Object path for the D-Bus object
@@ -151,8 +156,8 @@
const char* dbusInterface,
const std::variant<T>& value) const
{
- auto bus = sdbusplus::bus::new_default();
- auto service = getService(bus, objPath, dbusInterface);
+ auto& bus = DBusHandler::getBus();
+ auto service = getService(objPath, dbusInterface);
auto method = bus.new_method_call(service.c_str(), objPath,
dbusProperties, "Set");
method.append(dbusInterface, dbusProp, value);
@@ -164,23 +169,14 @@
const char* dbusInterface)
{
Variant value;
- auto bus = sdbusplus::bus::new_default();
- auto service = getService(bus, objPath, dbusInterface);
+ auto& bus = DBusHandler::getBus();
+ auto service = getService(objPath, dbusInterface);
auto method = bus.new_method_call(service.c_str(), objPath,
dbusProperties, "Get");
method.append(dbusInterface, dbusProp);
- try
- {
- auto reply = bus.call(method);
- reply.read(value);
- }
- catch (const sdbusplus::exception::SdBusError& e)
- {
- std::cerr << "dbus call exception, OBJPATH=" << objPath
- << " INTERFACE=" << dbusInterface
- << " PROPERTY=" << dbusProp << " EXCEPTION=" << e.what()
- << "\n";
- }
+ auto reply = bus.call(method);
+ reply.read(value);
+
return value;
}