sched-host-tran: code refactor

Move setProperty() and getService() to utils.cpp as public functions
which can be reused.

Change-Id: If62b67978349a80f8bd2026b5a749d5dedc556de
Signed-off-by: Carol Wang <wangkair@cn.ibm.com>
diff --git a/utils.cpp b/utils.cpp
new file mode 100644
index 0000000..a7a7384
--- /dev/null
+++ b/utils.cpp
@@ -0,0 +1,76 @@
+#include "utils.hpp"
+
+#include <phosphor-logging/log.hpp>
+
+namespace phosphor
+{
+namespace state
+{
+namespace manager
+{
+namespace utils
+{
+
+using namespace phosphor::logging;
+using sdbusplus::exception::SdBusError;
+
+constexpr auto MAPPER_BUSNAME = "xyz.openbmc_project.ObjectMapper";
+constexpr auto MAPPER_PATH = "/xyz/openbmc_project/object_mapper";
+constexpr auto MAPPER_INTERFACE = "xyz.openbmc_project.ObjectMapper";
+constexpr auto PROPERTY_INTERFACE = "org.freedesktop.DBus.Properties";
+
+std::string getService(sdbusplus::bus::bus& bus, std::string path,
+                       std::string interface)
+{
+    auto mapper = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH,
+                                      MAPPER_INTERFACE, "GetObject");
+
+    mapper.append(path, std::vector<std::string>({interface}));
+
+    std::vector<std::pair<std::string, std::vector<std::string>>>
+        mapperResponse;
+
+    try
+    {
+        auto mapperResponseMsg = bus.call(mapper);
+
+        mapperResponseMsg.read(mapperResponse);
+        if (mapperResponse.empty())
+        {
+            log<level::ERR>("Error no matching service",
+                            entry("PATH=%s", path.c_str()),
+                            entry("INTERFACE=%s", interface.c_str()));
+            throw std::runtime_error("Error no matching service");
+        }
+    }
+    catch (const SdBusError& e)
+    {
+        log<level::ERR>("Error in mapper call", entry("ERROR=%s", e.what()),
+                        entry("PATH=%s", path.c_str()),
+                        entry("INTERFACE=%s", interface.c_str()));
+        throw;
+    }
+
+    return mapperResponse.begin()->first;
+}
+
+void setProperty(sdbusplus::bus::bus& bus, const std::string& path,
+                 const std::string& interface, const std::string& property,
+                 const std::string& value)
+{
+    sdbusplus::message::variant<std::string> variantValue = value;
+    std::string service = getService(bus, path, interface);
+
+    auto method = bus.new_method_call(service.c_str(), path.c_str(),
+                                      PROPERTY_INTERFACE, "Set");
+
+    method.append(interface, property, variantValue);
+    bus.call_noreply(method);
+
+    return;
+}
+
+} // namespace utils
+} // namespace manager
+} // namespace state
+} // namespace phosphor