Lei YU | 0ab90ca | 2017-07-13 17:02:23 +0800 | [diff] [blame] | 1 | #include <algorithm> |
| 2 | #include <fstream> |
| 3 | |
| 4 | #include "config.h" |
| 5 | #include "i2c_occ.hpp" |
| 6 | |
| 7 | #ifdef I2C_OCC |
| 8 | |
| 9 | namespace i2c_occ |
| 10 | { |
| 11 | |
| 12 | namespace fs = std::experimental::filesystem; |
| 13 | |
| 14 | // The device name's length, e.g. "p8-occ-hwmon" |
| 15 | constexpr auto DEVICE_NAME_LENGTH = 12; |
| 16 | |
| 17 | // static assert to make sure the i2c occ device name is expected |
| 18 | static_assert(sizeof(I2C_OCC_DEVICE_NAME) -1 == DEVICE_NAME_LENGTH); |
| 19 | |
| 20 | std::string getFileContent(const fs::path& f) |
| 21 | { |
| 22 | std::string ret(DEVICE_NAME_LENGTH, 0); |
| 23 | std::ifstream ifs(f.c_str(), std::ios::binary); |
| 24 | if (ifs.is_open()) |
| 25 | { |
| 26 | ifs.read(&ret[0], DEVICE_NAME_LENGTH); |
| 27 | ret.resize(ifs.gcount()); |
| 28 | } |
| 29 | return ret; |
| 30 | } |
| 31 | |
| 32 | std::vector<std::string> getOccHwmonDevices(const char* path) |
| 33 | { |
| 34 | std::vector<std::string> result{}; |
| 35 | |
| 36 | if (fs::is_directory(path)) |
| 37 | { |
| 38 | for (auto & p : fs::directory_iterator(path)) |
| 39 | { |
| 40 | // Check if a device's name is "p8-occ-hwmon" |
| 41 | auto f = p / "name"; |
| 42 | auto str = getFileContent(f); |
| 43 | if (str == I2C_OCC_DEVICE_NAME) |
| 44 | { |
| 45 | result.emplace_back(p.path().filename()); |
| 46 | } |
| 47 | } |
| 48 | std::sort(result.begin(), result.end()); |
| 49 | } |
| 50 | return result; |
| 51 | } |
| 52 | |
| 53 | void i2cToDbus(std::string& path) |
| 54 | { |
| 55 | std::replace(path.begin(), path.end(), '-', '_'); |
| 56 | } |
| 57 | |
| 58 | void dbusToI2c(std::string& path) |
| 59 | { |
| 60 | std::replace(path.begin(), path.end(), '_', '-'); |
| 61 | } |
| 62 | |
| 63 | std::string getI2cDeviceName(const std::string& dbusPath) |
| 64 | { |
| 65 | auto name = fs::path(dbusPath).filename().string(); |
| 66 | dbusToI2c(name); |
| 67 | return name; |
| 68 | } |
| 69 | |
| 70 | } // namespace i2c_occ |
| 71 | |
| 72 | #endif |
| 73 | |