presence: Switch to new framework

Switch the main application logic to the output produced by
the new parser previously.
Remove unused code.

Signed-off-by: Brad Bishop <bradleyb@fuzziesquirrel.com>
Change-Id: If8b262bd80fd0f0135aeea55e578fb3c7f44339a
diff --git a/.gitignore b/.gitignore
index c5f7114..1872c14 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,7 +17,6 @@
 *.la

 *.lo

 *.o

-fan_detect_defs.cpp

 phosphor-fan-presence-tach

 phosphor-fan-control

 fan_zone_defs.cpp

diff --git a/configure.ac b/configure.ac
index e6ba9d2..5cd3a2a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -89,8 +89,6 @@
        AC_DEFINE_UNQUOTED([PRESENCE_CONFIG], ["$PRESENCE_CONFIG"],
                           [The fan presence config file.])
 
-       AC_SUBST([GEN_FAN_DETECT_DEFS],
-                ["$PYTHON \${top_srcdir}/presence/gen-fan-detect-defs.py -y $FAN_DETECT_YAML_FILE"])
        AC_SUBST([PFPGEN],
                 ["$PYTHON \${top_srcdir}/presence/pfpgen.py generate-cpp -i $PRESENCE_CONFIG"])
 
diff --git a/presence/Makefile.am b/presence/Makefile.am
index 134ee3c..db7e459 100644
--- a/presence/Makefile.am
+++ b/presence/Makefile.am
@@ -9,11 +9,7 @@
 	fan.cpp \
 	gpio.cpp \
 	tach.cpp \
-	fan_enclosure.cpp \
-	tach_sensor.cpp \
 	tach_detect.cpp
-nodist_phosphor_fan_presence_tach_SOURCES = \
-	fan_detect_defs.cpp
 
 phosphor_fan_presence_tach_LDADD = \
 	$(top_builddir)/libfan.la \
@@ -27,12 +23,9 @@
 	${PHOSPHOR_DBUS_INTERFACES_CFLAGS} \
 	$(LIBEVDEV_CFLAGS)
 
-BUILT_SOURCES = fan_detect_defs.cpp generated.hpp
+BUILT_SOURCES = generated.hpp
 TEMPLATES = \
 	templates/generated.mako.hpp
 
-fan_detect_defs.cpp: ${srcdir}/gen-fan-detect-defs.py $(FAN_DETECT_YAML_FILE)
-	$(AM_V_GEN)$(GEN_FAN_DETECT_DEFS) > $(builddir)/$@
-
 generated.hpp: $(TEMPLATES) ${srcdir}/pfpgen.py $(PRESENCE_CONFIG)
 	$(AM_V_GEN)$(PFPGEN) > $(builddir)/$@
diff --git a/presence/example/fan-detect.yaml b/presence/example/fan-detect.yaml
deleted file mode 100644
index 5a9e1bd..0000000
--- a/presence/example/fan-detect.yaml
+++ /dev/null
@@ -1,24 +0,0 @@
-# Example fan presence detection definitions

-

-# List each fan requiring presence detection and creation of an inventory object

-# within a system with the following parameters. The 'Detection' method must

-# have an associated fan presence detection application to properly handle

-# detecting fans using that type.

-

-#- [Detection method]:

-#  - PrettyName: [pretty name of the fan]

-#    Sensors: [List of sensors associated with this fan enclosure]

-#        - i.e) For tach feedback detection:

-#                   The hwmon name for a detected fan rotor's tach feedback

-#               For gpio detection:

-#                   The gpio pin name for the fan's presence line

-#  Inventory: [The system inventory location for the fan]

-#  Description: (Optional)

-

-# Example entry for a single fan's presence detected by 'Tach' feedback

-#- Tach:

-#  - PrettyName: fan0

-#    Sensors:

-#        - fan0

-#    Inventory: /system/chassis/fan0

-#    Description: Chassis location A1

diff --git a/presence/fan_detect_defs.hpp b/presence/fan_detect_defs.hpp
deleted file mode 100644
index 6c49366..0000000
--- a/presence/fan_detect_defs.hpp
+++ /dev/null
@@ -1,9 +0,0 @@
-#pragma once
-
-#include <map>
-#include <set>
-#include <tuple>
-#include "fan_properties.hpp"
-
-extern const std::map<std::string,
-                      std::set<phosphor::fan::Properties>> fanDetectMap;
diff --git a/presence/fan_enclosure.cpp b/presence/fan_enclosure.cpp
deleted file mode 100644
index 0d19e60..0000000
--- a/presence/fan_enclosure.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * Copyright © 2017 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 <algorithm>
-#include <phosphor-logging/log.hpp>
-#include "fan_enclosure.hpp"
-#include "sdbusplus.hpp"
-#include "utility.hpp"
-
-namespace phosphor
-{
-namespace fan
-{
-namespace presence
-{
-
-using namespace phosphor::logging;
-using namespace std::literals::string_literals;
-
-//TODO Should get these from phosphor-inventory-manager config.h
-const auto INVENTORY_PATH = "/xyz/openbmc_project/inventory"s;
-const auto INVENTORY_INTF = "xyz.openbmc_project.Inventory.Manager"s;
-
-presenceState FanEnclosure::getCurPresState()
-{
-    auto presPred = [](auto const& s) {return s->isPresent();};
-    // Determine if all sensors show fan is not present
-    auto isPresent = std::any_of(sensors.begin(),
-                                 sensors.end(),
-                                 presPred);
-
-    return (isPresent) ? PRESENT : NOT_PRESENT;
-}
-
-FanEnclosure::ObjectMap FanEnclosure::getObjectMap(const bool curPresState)
-{
-    ObjectMap invObj;
-    InterfaceMap invIntf;
-    PropertyMap invProp;
-
-    invProp.emplace("Present", curPresState);
-    invProp.emplace("PrettyName", fanDesc);
-    invIntf.emplace("xyz.openbmc_project.Inventory.Item", std::move(invProp));
-    Object fanInvPath = invPath;
-    invObj.emplace(std::move(fanInvPath), std::move(invIntf));
-
-    return invObj;
-}
-
-void FanEnclosure::updInventory()
-{
-    auto curPresState = getCurPresState();
-    // Only update inventory when presence state changed
-    if (presState != curPresState)
-    {
-        // Update inventory for this fan
-        util::SDBusPlus::lookupAndCallMethod(
-                INVENTORY_PATH,
-                INVENTORY_INTF,
-                "Notify"s,
-                getObjectMap(curPresState));
-        // Inventory updated, set presence state to current
-        presState = curPresState;
-    }
-}
-
-void FanEnclosure::addSensor(
-    std::unique_ptr<Sensor>&& sensor)
-{
-    FanEnclosure::sensors.push_back(std::move(sensor));
-}
-
-} // namespace presence
-} // namespace fan
-} // namespace phosphor
diff --git a/presence/fan_enclosure.hpp b/presence/fan_enclosure.hpp
deleted file mode 100644
index 30bd235..0000000
--- a/presence/fan_enclosure.hpp
+++ /dev/null
@@ -1,110 +0,0 @@
-#pragma once
-
-#include "fan_properties.hpp"
-#include "sdbusplus.hpp"
-#include "sensor_base.hpp"
-
-
-namespace phosphor
-{
-namespace fan
-{
-namespace presence
-{
-
-/**
- * @brief Specifies the defined presence states of a fan enclosure
- */
-typedef enum presenceState
-{
-    NOT_PRESENT,
-    PRESENT,
-    UNKNOWN
-} presenceState;
-
-/**
- * @class FanEnclosure
- * @brief OpenBMC fan enclosure inventory presence implementation
- * @details Inventory is based on the fan enclosure being present or not. This
- * class represents that fan enclosure and updates its presences status within
- * its inventory object based on the status of all its sensors.
- */
-class FanEnclosure
-{
-    using Property = std::string;
-    using Value = sdbusplus::message::variant<bool, int64_t, std::string>;
-    // Association between property and its value
-    using PropertyMap = std::map<Property, Value>;
-    using Interface = std::string;
-    // Association between interface and the dbus property
-    using InterfaceMap = std::map<Interface, PropertyMap>;
-    using Object = sdbusplus::message::object_path;
-    // Association between object and the interface
-    using ObjectMap = std::map<Object, InterfaceMap>;
-
-    public:
-        FanEnclosure() = delete;
-        FanEnclosure(const FanEnclosure&) = delete;
-        FanEnclosure(FanEnclosure&&) = default;
-        FanEnclosure& operator=(const FanEnclosure&) = delete;
-        FanEnclosure& operator=(FanEnclosure&&) = delete;
-        ~FanEnclosure() = default;
-
-        /**
-         * @brief Constructs Fan Enclosure Object
-         *
-         * @param[in] fanProp - Fan enclosure properties
-         * @param[in] initialState - The initial state of the enclosure.
-         */
-        explicit FanEnclosure(const phosphor::fan::Properties& fanProp,
-                              presenceState initialState = UNKNOWN) :
-                        invPath(std::get<0>(fanProp)),
-                        fanDesc(std::get<1>(fanProp)),
-                        presState(initialState)
-        {
-        }
-
-        /**
-         * @brief Update inventory when the determined presence of this fan
-         * enclosure has changed
-         */
-        void updInventory();
-        /**
-         * @brief Add a sensor association to this fan enclosure
-         *
-         * @param[in] sensor - Sensor associated to this fan enclosure
-         */
-        void addSensor(
-            std::unique_ptr<Sensor>&& sensor);
-
-    private:
-        /** @brief Inventory path for this fan enclosure */
-        const std::string invPath;
-        /** @brief Description used as 'PrettyName' on inventory object */
-        const std::string fanDesc;
-        /** @brief List of sensors associated with this fan enclosure */
-        std::vector<std::unique_ptr<Sensor>> sensors;
-        /** @brief Last known presence state of this fan enclosure */
-        presenceState presState;
-
-        /**
-         * @brief Get the current presence state based on all sensors
-         *
-         * @return Current presence state determined from all sensors
-         */
-        presenceState getCurPresState();
-
-        /**
-         * @brief Construct the inventory object map
-         *
-         * @param[in] Current presence state
-         *
-         * @return The inventory object map to update inventory
-         */
-        ObjectMap getObjectMap(bool curPresState);
-
-};
-
-} // namespace presence
-} // namespace fan
-} // namespace phosphor
diff --git a/presence/fan_properties.hpp b/presence/fan_properties.hpp
deleted file mode 100644
index 296318d..0000000
--- a/presence/fan_properties.hpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#pragma once
-
-#include <string>
-#include <vector>
-#include <tuple>
-
-
-namespace phosphor
-{
-namespace fan
-{
-
-/**
- * @brief Fan enclosure properties
- * @details Contains the inventory path, description and list of sensors
- */
-using Properties = std::tuple<std::string,
-                              std::string,
-                              std::vector<std::string>>;
-
-} // namespace fan
-} // namespace phosphor
diff --git a/presence/gen-fan-detect-defs.py b/presence/gen-fan-detect-defs.py
deleted file mode 100755
index 842bbeb..0000000
--- a/presence/gen-fan-detect-defs.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-
-"""
-This script parses the given fan presence definition yaml file and generates
-a header file based on the defined methods for determining when a fan is
-present.
-"""
-
-import os
-import sys
-import yaml
-from argparse import ArgumentParser
-from mako.template import Template
-
-tmpl = '''/* This is a generated file. */
-#include "fan_detect_defs.hpp"
-
-const std::map<std::string, std::set<phosphor::fan::Properties>>
-fanDetectMap = {
-%for methods in presence:
-    %for method in methods:
-    <% m = method.lower() %> \
-    {"${m}", {
-        %for fan in methods[method]:
-            std::make_tuple("${fan['Inventory']}",
-                            "${fan['PrettyName']}",
-                            std::vector<std::string>{
-            %for s in fan['Sensors']:
-                                                    "${s}",
-            %endfor
-                                                    }),
-        %endfor
-    %endfor
-    }},
-%endfor
-};
-'''
-
-
-if __name__ == '__main__':
-    parser = ArgumentParser()
-    # Input yaml containing how each fan's presence detection should be done
-    parser.add_argument("-y", "--yaml", dest="pres_yaml",
-                        default=
-                        "example/fan-detect.yaml",
-                        help=
-                        "Input fan presences definition yaml file to parse")
-    args = parser.parse_args(sys.argv[1:])
-
-    # Verify given yaml file exists
-    yaml_file = os.path.abspath(args.pres_yaml)
-    if not os.path.isfile(yaml_file):
-        print "Unable to find input yaml file " + yaml_file
-        exit(1)
-
-    with open(yaml_file, 'r') as yaml_input:
-        presence_data = yaml.safe_load(yaml_input) or {}
-
-    sys.stdout.write(Template(tmpl).render(presence=presence_data))
diff --git a/presence/sensor_base.hpp b/presence/sensor_base.hpp
deleted file mode 100644
index c206e70..0000000
--- a/presence/sensor_base.hpp
+++ /dev/null
@@ -1,59 +0,0 @@
-#pragma once
-
-
-namespace phosphor
-{
-namespace fan
-{
-namespace presence
-{
-
-// Forward declare FanEnclosure
-class FanEnclosure;
-/**
- * @class Sensor
- * @brief Base sensor implementation to be extended
- * @details A type of presence detection sensor would extend this to override
- * how presences is determined by the fan enclosure containing that type
- */
-class Sensor
-{
-    public:
-        Sensor() = delete;
-        Sensor(const Sensor&) = delete;
-        Sensor(Sensor&&) = delete;
-        Sensor& operator=(const Sensor&) = delete;
-        Sensor& operator=(Sensor&&) = delete;
-        virtual ~Sensor() = default;
-
-        /**
-         * @brief Constructs Sensor Object
-         *
-         * @param[in] id - ID name of this sensor
-         * @param[in] fanEnc - Reference to the fan enclosure with this sensor
-         */
-        Sensor(const std::string& id,
-               FanEnclosure& fanEnc) :
-            id(id),
-            fanEnc(fanEnc)
-        {
-            //Nothing to do here
-        }
-
-        /**
-         * @brief Presence function that must be implemented within the derived
-         * type of sensor's implementation on how presence is determined
-         */
-        virtual bool isPresent() = 0;
-
-    protected:
-        /** @brief ID name of this sensor */
-        const std::string id;
-        /** @brief Reference to the fan enclosure containing this sensor */
-        FanEnclosure& fanEnc;
-
-};
-
-} // namespace presence
-} // namespace fan
-} // namespace phosphor
diff --git a/presence/tach_detect.cpp b/presence/tach_detect.cpp
index 6ec5a5c..da0f40f 100644
--- a/presence/tach_detect.cpp
+++ b/presence/tach_detect.cpp
@@ -13,79 +13,26 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <phosphor-logging/log.hpp>
-#include <vector>
-#include "fan_enclosure.hpp"
-#include "fan_detect_defs.hpp"
 #include "generated.hpp"
 #include "sdbusplus.hpp"
-#include "tach_sensor.hpp"
+#include "sdevent.hpp"
 
 
 int main(void)
 {
     using namespace phosphor::fan;
-    using namespace std::literals::string_literals;
-    using namespace phosphor::logging;
 
-    std::vector<std::unique_ptr<phosphor::fan::presence::FanEnclosure>> fans;
+    auto& event = util::SDEvent::getEvent();
+    event.attach(util::SDBusPlus::getBus());
 
-    for (auto const& detectMap: fanDetectMap)
+    for (auto& p: presence::ConfigPolicy::get())
     {
-        if (detectMap.first == "tach")
-        {
-            for (auto const& fanProp: detectMap.second)
-            {
-                auto path = "/xyz/openbmc_project/inventory"s +
-                    std::get<0>(fanProp);
-
-                auto state = presence::UNKNOWN;
-                try
-                {
-                    auto boolstate = util::SDBusPlus::getProperty<bool>(
-                            path,
-                            "xyz.openbmc_project.Inventory.Item"s,
-                            "Present"s);
-                    state = boolstate ?
-                        presence::PRESENT : presence::NOT_PRESENT;
-                }
-                catch (const std::exception& err)
-                {
-                    log<level::INFO>(err.what());
-                }
-
-                auto fan = std::make_unique<
-                    phosphor::fan::presence::FanEnclosure>(fanProp,
-                                                           state);
-                for (auto const &fanSensor: std::get<2>(fanProp))
-                {
-                    auto initialSpeed = static_cast<int64_t>(0);
-                    auto sensorPath =
-                        "/xyz/openbmc_project/sensors/fan_tach/"s +
-                        fanSensor;
-                    initialSpeed = util::SDBusPlus::getProperty<int64_t>(
-                            sensorPath,
-                            "xyz.openbmc_project.Sensor.Value"s,
-                            "Value"s);
-
-                    auto sensor = std::make_unique<
-                        phosphor::fan::presence::TachSensor>(fanSensor,
-                                                             *fan,
-                                                             initialSpeed != 0);
-                    fan->addSensor(std::move(sensor));
-                }
-
-                fan->updInventory();
-                fans.push_back(std::move(fan));
-            }
-        }
+        p->monitor();
     }
 
-    while (true)
-    {
-        // Respond to dbus signals
-        util::SDBusPlus::getBus().process_discard();
-        util::SDBusPlus::getBus().wait();
-    }
-    return 0;
+    event.loop();
+
+    // The loop should never exit.  Exit with
+    // non zero status just in case.
+    return 1;
 }
diff --git a/presence/tach_sensor.cpp b/presence/tach_sensor.cpp
deleted file mode 100644
index 36d4bb1..0000000
--- a/presence/tach_sensor.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Copyright © 2017 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 <sdbusplus/exception.hpp>
-#include "tach_sensor.hpp"
-#include "fan_enclosure.hpp"
-
-
-namespace phosphor
-{
-namespace fan
-{
-namespace presence
-{
-
-bool TachSensor::isPresent()
-{
-    return state;
-}
-
-void TachSensor::handleTachChange(sdbusplus::message::message& sdbpMsg)
-{
-    std::string msgSensor;
-    std::map<std::string, sdbusplus::message::variant<int64_t>> msgData;
-    sdbpMsg.read(msgSensor, msgData);
-
-    // Find the 'Value' property containing tach
-    auto valPropMap = msgData.find("Value");
-    if (valPropMap != msgData.end())
-    {
-        state = sdbusplus::message::variant_ns::get<int64_t>(
-            valPropMap->second) != 0;
-    }
-    // Update inventory according to latest tach reported
-    fanEnc.updInventory();
-}
-
-} // namespace presence
-} // namespace fan
-} // namespace phosphor
diff --git a/presence/tach_sensor.hpp b/presence/tach_sensor.hpp
deleted file mode 100644
index 068a66f..0000000
--- a/presence/tach_sensor.hpp
+++ /dev/null
@@ -1,95 +0,0 @@
-#pragma once
-
-#include <sdbusplus/server.hpp>
-#include "sdbusplus.hpp"
-#include "sensor_base.hpp"
-
-
-namespace phosphor
-{
-namespace fan
-{
-namespace presence
-{
-
-using namespace sdbusplus::bus::match::rules;
-
-/**
- * @class TachSensor
- * @brief OpenBMC Tach feedback sensor presence implementation
- * @details Derived sensor type that uses the tach feedback value to determine
- * the presence of the fan enclosure that contains this sensor
- */
-class TachSensor : public Sensor
-{
-    public:
-        TachSensor() = delete;
-        TachSensor(const TachSensor&) = delete;
-        TachSensor(TachSensor&&) = delete;
-        TachSensor& operator=(const TachSensor&) = delete;
-        TachSensor& operator=(TachSensor&&) = delete;
-        ~TachSensor() = default;
-
-        /**
-         * @brief Constructs Tach Sensor Object
-         *
-         * @param[in] id - ID name of this sensor
-         * @param[in] fanEnc - Reference to the fan enclosure with this sensor
-         */
-        TachSensor(
-            const std::string& id,
-            FanEnclosure& fanEnc,
-            bool initialState = false) :
-                Sensor(id, fanEnc),
-                tachSignal(util::SDBusPlus::getBus(),
-                           match(id).c_str(),
-                           std::bind(
-                               std::mem_fn(&TachSensor::handleTachChange),
-                               this,
-                               std::placeholders::_1)),
-                state(initialState)
-        {
-            // Nothing to do here
-        }
-
-        /**
-         * @brief Determine the presence of this sensor using the tach feedback
-         *
-         * @return Presence state based on tach feedback
-         */
-        bool isPresent();
-
-    private:
-        /** @brief Used to subscribe to dbus signals */
-        sdbusplus::server::match::match tachSignal;
-        /** @brief Tach speed value given from the signal */
-        bool state;
-
-        /**
-         * @brief Appends the fan sensor id to construct a match string
-         *
-         * @param[in] id - Fan sensor id
-         *
-         * @return Match string to register signal for the fan sensor id
-         */
-        static std::string match(const std::string& id)
-        {
-            return std::string(
-                    interface("org.freedesktop.DBus.Properties") +
-                    member("PropertiesChanged") +
-                    type::signal() +
-                    path("/xyz/openbmc_project/sensors/fan_tach/" + id) +
-                    argN(0, "xyz.openbmc_project.Sensor.Value"));
-        }
-        /**
-         * @brief Handle when the signal was a tach change
-         *
-         * @param[in] msg - Expanded sdbusplus message data
-         */
-        void handleTachChange(sdbusplus::message::message& msg);
-
-};
-
-} // namespace presence
-} // namespace fan
-} // namespace phosphor