blob: 69e05a9bd325db9a7ffe581d63386e94451ef5d7 [file] [log] [blame]
Naveen Mosesa1af3292021-12-15 11:47:01 +05301#pragma once
2
3#include "button_interface.hpp"
4#include "gpio.hpp"
5
6#include <phosphor-logging/elog-errors.hpp>
George Liu5b98f4d2022-06-20 13:31:14 +08007
Naveen Mosesa1af3292021-12-15 11:47:01 +05308#include <unordered_map>
9
10using buttonIfCreatorMethod = std::function<std::unique_ptr<ButtonIface>(
Patrick Williams9a529a62022-07-22 19:26:54 -050011 sdbusplus::bus_t& bus, EventPtr& event, buttonConfig& buttonCfg)>;
Naveen Mosesa1af3292021-12-15 11:47:01 +053012
13/**
14 * @brief This is abstract factory for the creating phosphor buttons objects
15 * based on the button / formfactor type given.
16 */
17
18class ButtonFactory
19{
Naveen Mosesa1af3292021-12-15 11:47:01 +053020 public:
21 static ButtonFactory& instance()
22 {
23 static ButtonFactory buttonFactoryObj;
24 return buttonFactoryObj;
25 }
26
27 /**
28 * @brief this method creates a key and value pair element
29 * for the given button interface where key is the form factor
30 * name and the value is lambda method to return
31 * the instance of the button interface.
32 * This key value pair is stored in the Map buttonIfaceRegistry.
33 */
34
35 template <typename T>
36 void addToRegistry()
37 {
Naveen Mosesa1af3292021-12-15 11:47:01 +053038 buttonIfaceRegistry[std::string(T::getFormFactorName())] =
Patrick Williams9a529a62022-07-22 19:26:54 -050039 [](sdbusplus::bus_t& bus, EventPtr& event,
Naveen Mosesa1af3292021-12-15 11:47:01 +053040 buttonConfig& buttonCfg) {
41 return std::make_unique<T>(bus, T::getDbusObjectPath(), event,
42 buttonCfg);
43 };
44 }
45 /**
46 * @brief this method returns the button interface object
47 * corresponding to the button formfactor name provided
48 */
George Liu94afa4b2022-06-20 13:36:43 +080049 std::unique_ptr<ButtonIface> createInstance(const std::string& name,
Patrick Williams9a529a62022-07-22 19:26:54 -050050 sdbusplus::bus_t& bus,
Naveen Mosesa1af3292021-12-15 11:47:01 +053051 EventPtr& event,
52 buttonConfig& buttonCfg)
53 {
Naveen Mosesa1af3292021-12-15 11:47:01 +053054 // find matching name in the registry and call factory method.
Naveen Moseseea8a4a2022-02-18 01:14:15 +053055 auto objectIter = buttonIfaceRegistry.find(name);
56 if (objectIter != buttonIfaceRegistry.end())
57 {
58 return objectIter->second(bus, event, buttonCfg);
59 }
60 else
61 {
62 return nullptr;
63 }
Naveen Mosesa1af3292021-12-15 11:47:01 +053064 }
65
66 private:
67 // This map is the registry for keeping supported button interface types.
68 std::unordered_map<std::string, buttonIfCreatorMethod> buttonIfaceRegistry;
69};
70
71template <class T>
72class ButtonIFRegister
73{
74 public:
75 ButtonIFRegister()
76 {
77 // register the class factory function
78 ButtonFactory::instance().addToRegistry<T>();
79 }
80};