blob: 97b26e70c0a8603f0ad2548d7b62b743f2cb1604 [file] [log] [blame]
Lei YU7f4fca52017-02-23 15:15:51 +08001#pragma once
2
Lei YUa7417132017-02-23 15:24:05 +08003#include <phosphor-logging/log.hpp>
4
Lei YU7f4fca52017-02-23 15:15:51 +08005#include <fstream>
6
7namespace phosphor
8{
9namespace time
10{
11namespace utils
12{
13
Lei YUa7417132017-02-23 15:24:05 +080014using namespace phosphor::logging;
15
Lei YU7f4fca52017-02-23 15:15:51 +080016/** @brief Read data with type T from file
17 *
18 * @param[in] fileName - The name of file to read from
19 *
20 * @return The data with type T
21 */
22template <typename T>
23T readData(const char* fileName)
24{
25 T data{};
26 std::ifstream fs(fileName);
27 if (fs.is_open())
28 {
29 fs >> data;
30 }
31 return data;
32}
33
34/** @brief Write data with type T to file
35 *
36 * @param[in] fileName - The name of file to write to
37 * @param[in] data - The data with type T to write to file
38 */
39template <typename T>
40void writeData(const char* fileName, T&& data)
41{
42 std::ofstream fs(fileName, std::ios::out);
43 if (fs.is_open())
44 {
45 fs << std::forward<T>(data);
46 }
47}
48
Lei YUa7417132017-02-23 15:24:05 +080049/** @brief The template function to get property from the requested dbus path
50 *
51 * @param[in] bus - The Dbus bus object
52 * @param[in] service - The Dbus service name
53 * @param[in] path - The Dbus object path
54 * @param[in] interface - The Dbus interface
55 * @param[in] propertyName - The property name to get
56 *
57 * @return The value of the property
58 */
59template <typename T>
60T getProperty(sdbusplus::bus::bus& bus,
61 const char* service,
62 const char* path,
63 const char* interface,
64 const char* propertyName)
65{
66 sdbusplus::message::variant<T> value{};
67 auto method = bus.new_method_call(service,
68 path,
69 "org.freedesktop.DBus.Properties",
70 "Get");
71 method.append(interface, propertyName);
72 auto reply = bus.call(method);
73 if (reply)
74 {
75 reply.read(value);
76 }
77 else
78 {
79 // TODO: use elog to throw exception
80 log<level::ERR>("Failed to get property",
81 entry("SERVICE=%s", service),
82 entry("PATH=%s", path),
83 entry("INTERFACE=%s", interface),
84 entry("PROPERTY=%s", propertyName));
85 }
86 return value.template get<T>();
87}
88
Lei YU7f4fca52017-02-23 15:15:51 +080089}
90}
91}