Sensor Objects

This includes all the sensor objects including a few
implementations, including dbus and sysfs sensors.

Change-Id: I9897c79f9fd463f00f0e02aeb6c32ffa89635dbe
Signed-off-by: Patrick Venture <venture@google.com>
diff --git a/sensors/README b/sensors/README
new file mode 100644
index 0000000..d2c2f34
--- /dev/null
+++ b/sensors/README
@@ -0,0 +1,20 @@
+# HostSensor
+
+A HostSensor object is one whose value is received from the host over IPMI (or
+some other mechanism).  These sensors create dbus objects in the following
+namespace:
+        /xyz/openbmc_projects/extsensors/{namespace}/{sensorname}
+
+You can update them by setting the Value in Sensor.Value as a set or update
+property dbus call.
+
+# SensorManager
+
+There is a SensorManager object whose job is to hold all the sensors.
+
+# PluggableSensor
+
+The PluggableSensor is an object that receives a reader and writer and is
+therefore meant to be used for a variety of sensor types that aren't
+HostSensors.
+
diff --git a/sensors/host.cpp b/sensors/host.cpp
new file mode 100644
index 0000000..44e83d8
--- /dev/null
+++ b/sensors/host.cpp
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2017 Google Inc.
+ *
+ * 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 <cmath>
+#include <iostream>
+#include <memory>
+#include <mutex>
+
+#include "host.hpp"
+
+std::unique_ptr<Sensor> HostSensor::CreateTemp(
+    const std::string& name,
+    int64_t timeout,
+    sdbusplus::bus::bus& bus,
+    const char* objPath,
+    bool defer)
+{
+    auto sensor = std::make_unique<HostSensor>(name, timeout, bus, objPath, defer);
+    sensor->value(0);
+
+    // TODO(venture): Need to not hard-code that this is DegreesC and scale
+    // 10x-3 unless it is! :D
+    sensor->unit(ValueInterface::Unit::DegreesC);
+    sensor->scale(-3);
+    sensor->emit_object_added();
+
+    /* TODO(venture): Need to set that _updated is set to epoch or something
+     * else.  what is the default value?
+     */
+    return sensor;
+}
+
+int64_t HostSensor::value(int64_t value)
+{
+    std::lock_guard<std::mutex> guard(_lock);
+
+    _updated = std::chrono::high_resolution_clock::now();
+    _value = value * pow(10, scale()); /* scale value */
+
+    return ValueObject::value(value);
+}
+
+ReadReturn HostSensor::read(void)
+{
+    std::lock_guard<std::mutex> guard(_lock);
+
+    /* This doesn't sanity check anything, that's the caller's job. */
+    struct ReadReturn r = {
+        _value,
+        _updated
+    };
+
+    return r;
+}
+
+void HostSensor::write(double value)
+{
+    throw std::runtime_error("Not Implemented.");
+}
+
diff --git a/sensors/host.hpp b/sensors/host.hpp
new file mode 100644
index 0000000..5d25aa0
--- /dev/null
+++ b/sensors/host.hpp
@@ -0,0 +1,56 @@
+#pragma once
+
+#include <memory>
+#include <mutex>
+
+#include <sdbusplus/bus.hpp>
+#include <sdbusplus/server.hpp>
+#include "xyz/openbmc_project/Sensor/Value/server.hpp"
+
+#include "sensor.hpp"
+
+template <typename... T>
+using ServerObject = typename sdbusplus::server::object::object<T...>;
+
+using ValueInterface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;
+using ValueObject = ServerObject<ValueInterface>;
+
+/*
+ * HostSensor object is a Sensor derivative that also implements a ValueObject,
+ * which comes from the dbus as an object that implements Sensor.Value.
+ */
+class HostSensor : public Sensor, public ValueObject
+{
+    public:
+        static std::unique_ptr<Sensor> CreateTemp(
+            const std::string& name,
+            int64_t timeout,
+            sdbusplus::bus::bus& bus,
+            const char* objPath,
+            bool defer);
+
+        HostSensor(const std::string& name,
+                   int64_t timeout,
+                   sdbusplus::bus::bus& bus,
+                   const char* objPath,
+                   bool defer)
+            : Sensor(name, timeout),
+              ValueObject(bus, objPath, defer)
+        { }
+
+        /* Note: This must be int64_t because it's from ValueObject */
+        int64_t value(int64_t value) override;
+
+        ReadReturn read(void) override;
+        void write(double value) override;
+
+    private:
+        /*
+         * _lock will be used to make sure _updated & _value are updated
+         * together.
+         */
+        std::mutex _lock;
+        std::chrono::high_resolution_clock::time_point _updated;
+        double _value = 0;
+};
+
diff --git a/sensors/manager.cpp b/sensors/manager.cpp
new file mode 100644
index 0000000..590ca80
--- /dev/null
+++ b/sensors/manager.cpp
@@ -0,0 +1,248 @@
+/**
+ * Copyright 2017 Google Inc.
+ *
+ * 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 <cstring>
+#include <iostream>
+#include <libconfig.h++>
+#include <map>
+#include <memory>
+
+/* Configuration. */
+#include "conf.hpp"
+
+#include "interfaces.hpp"
+#include "manager.hpp"
+#include "util.hpp"
+
+#include "dbus/dbuspassive.hpp"
+#include "notimpl/readonly.hpp"
+#include "notimpl/writeonly.hpp"
+#include "sysfs/sysfsread.hpp"
+#include "sensors/manager.hpp"
+#include "sensors/host.hpp"
+#include "sensors/pluggable.hpp"
+#include "sysfs/sysfswrite.hpp"
+
+
+static constexpr bool deferSignals = true;
+
+std::shared_ptr<SensorManager> BuildSensors(
+    std::map<std::string, struct sensor>& Config)
+{
+    auto mgmr = std::make_shared<SensorManager>();
+    auto& HostSensorBus = mgmr->getHostBus();
+    auto& PassiveListeningBus = mgmr->getPassiveBus();
+
+    for (auto& it : Config)
+    {
+        std::unique_ptr<ReadInterface> ri;
+        std::unique_ptr<WriteInterface> wi;
+
+        std::string name = it.first;
+        struct sensor* info = &it.second;
+
+        std::cerr << "Sensor: " << name << " " << info->type << " ";
+        std::cerr << info->readpath << " " << info->writepath << "\n";
+
+        IOInterfaceType rtype = GetReadInterfaceType(info->readpath);
+        IOInterfaceType wtype = GetWriteInterfaceType(info->writepath);
+
+        // fan sensors can be ready any way and written others.
+        // fan sensors are the only sensors this is designed to write.
+        // Nothing here should be write-only, although, in theory a fan could be.
+        // I'm just not sure how that would fit together.
+        // TODO(venture): It should check with the ObjectMapper to check if
+        // that sensor exists on the Dbus.
+        switch (rtype)
+        {
+            case IOInterfaceType::DBUSPASSIVE:
+                ri = std::make_unique<DbusPassive>(
+                         PassiveListeningBus,
+                         info->type,
+                         name);
+                break;
+            case IOInterfaceType::EXTERNAL:
+                // These are a special case for read-only.
+                break;
+            case IOInterfaceType::SYSFS:
+                ri = std::make_unique<SysFsRead>(info->readpath);
+                break;
+            default:
+                ri = std::make_unique<WriteOnly>();
+                break;
+        }
+
+        if (info->type == "fan")
+        {
+            switch (wtype)
+            {
+                case IOInterfaceType::SYSFS:
+                    if (info->max > 0)
+                    {
+                        wi = std::make_unique<SysFsWritePercent>(
+                                 info->writepath,
+                                 info->min,
+                                 info->max);
+                    }
+                    else
+                    {
+                        wi = std::make_unique<SysFsWrite>(
+                                 info->writepath,
+                                 info->min,
+                                 info->max);
+                    }
+
+                    break;
+                default:
+                    wi = std::make_unique<ReadOnlyNoExcept>();
+                    break;
+            }
+
+            auto sensor = std::make_unique<PluggableSensor>(
+                              name,
+                              info->timeout,
+                              std::move(ri),
+                              std::move(wi));
+            mgmr->addSensor(info->type, name, std::move(sensor));
+        }
+        else if (info->type == "temp" || info->type == "margin")
+        {
+            // These sensors are read-only, but only for this application
+            // which only writes to fan sensors.
+            std::cerr << info->type << " readpath: " << info->readpath << "\n";
+
+            if (IOInterfaceType::EXTERNAL == rtype)
+            {
+                std::cerr << "Creating HostSensor: " << name
+                          << " path: " << info->readpath << "\n";
+
+                /*
+                 * The reason we handle this as a HostSensor is because it's
+                 * not quite pluggable; but maybe it could be.
+                 */
+                auto sensor = HostSensor::CreateTemp(
+                                  name,
+                                  info->timeout,
+                                  HostSensorBus,
+                                  info->readpath.c_str(),
+                                  deferSignals);
+                mgmr->addSensor(info->type, name, std::move(sensor));
+            }
+            else
+            {
+                wi = std::make_unique<ReadOnlyNoExcept>();
+                auto sensor = std::make_unique<PluggableSensor>(
+                                  name,
+                                  info->timeout,
+                                  std::move(ri),
+                                  std::move(wi));
+                mgmr->addSensor(info->type, name, std::move(sensor));
+            }
+        }
+    }
+
+    return mgmr;
+}
+
+/*
+ * If there's a configuration file, we build from that, and it requires special
+ * parsing.  I should just ditch the compile-time version to reduce the
+ * probability of sync bugs.
+ */
+std::shared_ptr<SensorManager> BuildSensorsFromConfig(std::string& path)
+{
+    using namespace libconfig;
+
+    std::map<std::string, struct sensor> config;
+    Config cfg;
+
+    std::cerr << "entered BuildSensorsFromConfig\n";
+
+    /* The load was modeled after the example source provided. */
+    try
+    {
+        cfg.readFile(path.c_str());
+    }
+    catch (const FileIOException& fioex)
+    {
+        std::cerr << "I/O error while reading file: " << fioex.what() << std::endl;
+        throw;
+    }
+    catch (const ParseException& pex)
+    {
+        std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
+                  << " - " << pex.getError() << std::endl;
+        throw;
+    }
+
+    try
+    {
+        const Setting& root = cfg.getRoot();
+
+        /* Grab the list of sensors and create them all */
+        const Setting& sensors = root["sensors"];
+        int count = sensors.getLength();
+
+        for (int i = 0; i < count; ++i)
+        {
+            const Setting& sensor = sensors[i];
+
+            std::string name;
+            struct sensor thisOne;
+
+            /* Not a super fan of using this library for run-time configuration. */
+            name = sensor.lookup("name").c_str();
+            thisOne.type = sensor.lookup("type").c_str();
+            thisOne.readpath = sensor.lookup("readpath").c_str();
+            thisOne.writepath = sensor.lookup("writepath").c_str();
+
+            /* TODO: Document why this is wonky.  The library probably doesn't
+             * like int64_t
+             */
+            int min = sensor.lookup("min");
+            thisOne.min = static_cast<int64_t>(min);
+            int max = sensor.lookup("max");
+            thisOne.max = static_cast<int64_t>(max);
+            int timeout = sensor.lookup("timeout");
+            thisOne.timeout = static_cast<int64_t>(timeout);
+
+            // leaving for verification for now.  and yea the above is
+            // necessary.
+            std::cerr << "min: " << min
+                    << " max: " << max
+                    << " savedmin: " << thisOne.min
+                    << " savedmax: " << thisOne.max
+                    << " timeout: " << thisOne.timeout
+                    << std::endl;
+
+            config[name] = thisOne;
+        }
+    }
+    catch (const SettingTypeException &setex)
+    {
+        std::cerr << "Setting '" << setex.getPath()
+                  << "' type exception!" << std::endl;
+        throw;
+    }
+    catch (const SettingNotFoundException& snex)
+    {
+        std::cerr << "Setting not found!" << std::endl;
+        throw;
+    }
+
+    return BuildSensors(config);
+}
+
diff --git a/sensors/manager.hpp b/sensors/manager.hpp
new file mode 100644
index 0000000..5de058e
--- /dev/null
+++ b/sensors/manager.hpp
@@ -0,0 +1,75 @@
+#pragma once
+
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <sdbusplus/bus.hpp>
+#include <sdbusplus/server.hpp>
+
+#include "sensors/sensor.hpp"
+
+
+/*
+ * The SensorManager holds all sensors across all zones.
+ */
+class SensorManager
+{
+    public:
+        SensorManager()
+            : _passiveListeningBus(std::move(sdbusplus::bus::new_default())),
+              _hostSensorBus(std::move(sdbusplus::bus::new_default()))
+        {
+            // Create a manger for the sensor root because we own it.
+            static constexpr auto SensorRoot = "/xyz/openbmc_project/extsensors";
+            sdbusplus::server::manager::manager(_hostSensorBus, SensorRoot);
+        }
+
+        /*
+         * Add a Sensor to the Manager.
+         */
+        void addSensor(
+            std::string type,
+            std::string name,
+            std::unique_ptr<Sensor> sensor)
+        {
+            _sensorMap[name] = std::move(sensor);
+
+            auto entry = _sensorTypeList.find(type);
+            if (entry == _sensorTypeList.end())
+            {
+                _sensorTypeList[type] = {};
+            }
+
+            _sensorTypeList[type].push_back(name);
+        }
+
+        // TODO(venture): Should implement read/write by name.
+        std::unique_ptr<Sensor>& getSensor(std::string name)
+        {
+            return _sensorMap.at(name);
+        }
+
+        sdbusplus::bus::bus& getPassiveBus(void)
+        {
+            return _passiveListeningBus;
+        }
+
+        sdbusplus::bus::bus& getHostBus(void)
+        {
+            return _hostSensorBus;
+        }
+
+    private:
+        std::map<std::string, std::unique_ptr<Sensor>> _sensorMap;
+        std::map<std::string, std::vector<std::string>> _sensorTypeList;
+
+        sdbusplus::bus::bus _passiveListeningBus;
+        sdbusplus::bus::bus _hostSensorBus;
+};
+
+std::shared_ptr<SensorManager> BuildSensors(
+    std::map<std::string, struct sensor>& Config);
+
+std::shared_ptr<SensorManager> BuildSensorsFromConfig(std::string& path);
diff --git a/sensors/pluggable.cpp b/sensors/pluggable.cpp
new file mode 100644
index 0000000..8039aea
--- /dev/null
+++ b/sensors/pluggable.cpp
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2017 Google Inc.
+ *
+ * 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 "pluggable.hpp"
+
+#include <iostream>
+#include <memory>
+#include <string>
+
+#include "sysfs/sysfswrite.hpp"
+#include "dbus/dbuspassive.hpp"
+
+
+ReadReturn PluggableSensor::read(void)
+{
+    return _reader->read();
+}
+
+void PluggableSensor::write(double value)
+{
+    _writer->write(value);
+}
+
diff --git a/sensors/pluggable.hpp b/sensors/pluggable.hpp
new file mode 100644
index 0000000..1eb6571
--- /dev/null
+++ b/sensors/pluggable.hpp
@@ -0,0 +1,33 @@
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include <sdbusplus/bus.hpp>
+
+#include "interfaces.hpp"
+#include "sensor.hpp"
+
+
+/*
+ * A Sensor that can use any reader or writer you provide.
+ */
+class PluggableSensor : public Sensor
+{
+    public:
+        PluggableSensor(const std::string& name,
+                        int64_t timeout,
+                        std::unique_ptr<ReadInterface> reader,
+                        std::unique_ptr<WriteInterface> writer)
+            : Sensor(name, timeout),
+              _reader(std::move(reader)),
+              _writer(std::move(writer))
+        { }
+
+        ReadReturn read(void) override;
+        void write(double value) override;
+
+    private:
+        std::unique_ptr<ReadInterface> _reader;
+        std::unique_ptr<WriteInterface> _writer;
+};
diff --git a/sensors/sensor.hpp b/sensors/sensor.hpp
new file mode 100644
index 0000000..dc5f3e0
--- /dev/null
+++ b/sensors/sensor.hpp
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <chrono>
+#include <string>
+
+#include "interfaces.hpp"
+
+
+/**
+ * Abstract base class for all sensors.
+ */
+class Sensor
+{
+    public:
+        Sensor(std::string name, int64_t timeout)
+            : _name(name), _timeout(timeout)
+        { }
+
+        virtual ~Sensor() { }
+
+        virtual ReadReturn read(void) = 0;
+        virtual void write(double value) = 0;
+
+        std::string GetName(void) const
+        {
+            return _name;
+        }
+
+        /* Returns the configurable timeout period
+         * for this sensor in seconds (undecorated).
+         */
+        int64_t GetTimeout(void) const
+        {
+            return _timeout;
+        }
+
+    private:
+        std::string _name;
+        int64_t _timeout;
+};
+