Bluenet  5.7.0
Bluenet, firmware for nRF52 smart home devices
Loading...
Searching...
No Matches
cs_Component.h
Go to the documentation of this file.
1/*
2 * Author: Crownstone Team
3 * Copyright: Crownstone (https://crownstone.rocks)
4 * Date: Aug 18, 2021
5 * License: LGPLv3+, Apache License 2.0, and/or MIT (triple-licensed)
6 */
7
8#pragma once
9
10#include <logging/cs_Logger.h>
13
14#include <vector>
15
35class Component {
36public:
45 template <class T>
46 T* getComponent(Component* requester = nullptr);
47
48 // ============== life cycle events ===============
49
70 virtual cs_ret_code_t init() { return ERR_SUCCESS; }
71
77
78 // ================== Con-/destructors ==================
79
80 virtual ~Component() = default;
81
82protected:
83 // ================== Getters ==================
84
90 virtual std::vector<Component*> getChildren() { return {}; }
91
92 // ============== parenting ==============
93
104
110
111
112private:
113 Component* _parent = nullptr;
114};
115
116// -------------------- Template implementation details -------------------
117
118template <class T>
120 // jump up in hierarchy to parent.
121 if (requester == nullptr) {
122 if (_parent != nullptr) {
123 // request from the parent to find a sibling.
124 // keeping track of the original requester.
125 return _parent->getComponent<T>(this);
126 }
127 else {
128 // no parent means no siblings.
129 // use get subcomponents if you want that.
130 return nullptr;
131 }
132 }
133
134 // traverse children
135 for (auto c : getChildren()) {
136 if (c == requester) {
137 // skip original requester to avoid infinite recursions.
138 continue;
139 }
140
141 T* t = dynamic_cast<T*>(c);
142 if (t != nullptr) {
143 return t;
144 }
145 }
146
147 // jump up in hierarchy one stack frame deeper
148 if (_parent != nullptr) {
149 return _parent->getComponent<T>(this);
150 }
151
152 return nullptr;
153}
Helper class to manage decoupling of components.
Definition: cs_Component.h:35
cs_ret_code_t initChildren()
virtual std::vector< Component * > getChildren()
Components with children can override this method to return them.
Definition: cs_Component.h:90
void setParent(Component *p)
Children that are instantiated later can also be added individually.
void parentAllChildren()
utility that loops over all elements of getChildren() and setParent on the non-nullptr ones.
virtual cs_ret_code_t init()
Components can implement this if they need to get references to sibling or if they need to do specifi...
Definition: cs_Component.h:70
T * getComponent(Component *requester=nullptr)
Returns a component of type T* from _parent->children(), If not found try again with ancestors: _pare...
Definition: cs_Component.h:119
virtual ~Component()=default
Component * _parent
Definition: cs_Component.h:113
@ ERR_SUCCESS
Definition: cs_ErrorCodes.h:10
uint16_t cs_ret_code_t
Definition: cs_Typedefs.h:21