Lei YU | 7f4fca5 | 2017-02-23 15:15:51 +0800 | [diff] [blame] | 1 | #pragma once |
| 2 | |
Lei YU | a741713 | 2017-02-23 15:24:05 +0800 | [diff] [blame] | 3 | #include <phosphor-logging/log.hpp> |
| 4 | |
Lei YU | 7f4fca5 | 2017-02-23 15:15:51 +0800 | [diff] [blame] | 5 | #include <fstream> |
| 6 | |
| 7 | namespace phosphor |
| 8 | { |
| 9 | namespace time |
| 10 | { |
| 11 | namespace utils |
| 12 | { |
| 13 | |
Lei YU | a741713 | 2017-02-23 15:24:05 +0800 | [diff] [blame] | 14 | using namespace phosphor::logging; |
| 15 | |
Lei YU | 7f4fca5 | 2017-02-23 15:15:51 +0800 | [diff] [blame] | 16 | /** @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 | */ |
| 22 | template <typename T> |
| 23 | T 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 | */ |
| 39 | template <typename T> |
| 40 | void 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 YU | a741713 | 2017-02-23 15:24:05 +0800 | [diff] [blame] | 49 | /** @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 | */ |
| 59 | template <typename T> |
| 60 | T 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 YU | 7f4fca5 | 2017-02-23 15:15:51 +0800 | [diff] [blame] | 89 | } |
| 90 | } |
| 91 | } |