Find hwmon instances from OF device paths

Provide a method that scans the hwmon subtree for a matching
open firmware device path.

Change-Id: Ic71dea90113c6894d9d2b61e03bd02f6b550e1e6
Signed-off-by: Brad Bishop <bradleyb@fuzziesquirrel.com>
diff --git a/Makefile.am b/Makefile.am
index 6325121..ab4d373 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -11,6 +11,7 @@
 	directory.cpp \
 	sensorset.cpp \
 	mainloop.cpp \
+	sysfs.cpp \
 	xyz.openbmc_project.Sensor.Value.cpp
 
 SUBDIRS = . test
diff --git a/sysfs.cpp b/sysfs.cpp
new file mode 100644
index 0000000..f1f46db
--- /dev/null
+++ b/sysfs.cpp
@@ -0,0 +1,54 @@
+/**
+ * Copyright © 2016 IBM Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <cstdlib>
+#include <memory>
+#include "sysfs.hpp"
+#include "util.hpp"
+#include "directory.hpp"
+
+std::string findHwmon(const std::string& ofNode)
+{
+    static constexpr auto hwmonRoot = "/sys/class/hwmon";
+
+    std::string fullOfPath{"/sys/firmware/devicetree/base"};
+    fullOfPath.append(ofNode);
+
+    std::string hwmonInst;
+    Directory d(hwmonRoot);
+
+    while (d.next(hwmonInst))
+    {
+        std::string hwmonPath{hwmonRoot};
+        hwmonPath.append(1, '/');
+        hwmonPath.append(hwmonInst);
+        std::string path{hwmonPath};
+        path.append(1, '/');
+        path.append("of_node");
+
+        auto real = std::unique_ptr<char, phosphor::utility::Free<char>>(realpath(
+                        path.c_str(), nullptr));
+        if (!real || real.get() != fullOfPath)
+        {
+            continue;
+        }
+
+        return hwmonPath;
+    }
+
+    return std::string();
+}
+
+// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
diff --git a/sysfs.hpp b/sysfs.hpp
index b9148da..690cf77 100644
--- a/sysfs.hpp
+++ b/sysfs.hpp
@@ -27,4 +27,17 @@
     return path + "/"s + type + id + "_"s + entry;
 }
 
+
+/** @brief Find hwmon instances
+ *
+ *  Look for a matching hwmon instance given an
+ *  open firmware device path.
+ *
+ *  @param[in] ofNode- The open firmware device path.
+ *
+ *  @returns[in] - The hwmon instance path or an empty
+ *                 string if no match is found.
+ */
+std::string findHwmon(const std::string& ofNode);
+
 // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4