Browse Source

sns: notify hook

either timed or instant callbacks, intended to be called from within the
sensor itself or by any other module needing to 'ping' sensor instance
test/dev
Maxim Prokhorov 2 months ago
parent
commit
89fd41d6c8
3 changed files with 58 additions and 0 deletions
  1. +47
    -0
      code/espurna/sensor.cpp
  2. +7
    -0
      code/espurna/sensor.h
  3. +4
    -0
      code/espurna/sensors/BaseSensor.h

+ 47
- 0
code/espurna/sensor.cpp View File

@ -1908,6 +1908,32 @@ enum class State {
Reading,
};
namespace notifications {
namespace internal {
std::forward_list<NotifyCallback> callbacks;
std::forward_list<timer::SystemTimer> timers;
} // namespace internal
} // namespace notifications
void notify_after(duration::Milliseconds after, NotifyCallback callback) {
using namespace notifications;
internal::timers.push_front(timer::SystemTimer());
auto& instance = internal::timers.front();
instance.schedule_once(
after,
[callback]() {
internal::callbacks.push_front(callback);
});
}
void notify_now(NotifyCallback callback) {
notifications::internal::callbacks.push_front(callback);
}
namespace internal {
std::vector<BaseSensorPtr> sensors;
@ -3864,6 +3890,24 @@ bool try_init() {
// Magnitude processing
// -----------------------------------------------------------------------------
void notify() {
decltype(notifications::internal::callbacks) callbacks;
std::swap(callbacks, notifications::internal::callbacks);
for (auto sensor : internal::sensors) {
for (auto& callback : callbacks) {
if (callback(sensor.get())) {
sensor->notify();
}
}
}
notifications::internal::timers.remove_if(
[](const timer::SystemTimer& timer) {
return !static_cast<bool>(timer);
});
}
void tick() {
for (auto sensor : internal::sensors) {
sensor->tick();
@ -3941,6 +3985,9 @@ void loop() {
return;
}
// Notify hook, called when requested by sensor
sensor::notify();
// Tick hook, called every loop()
sensor::tick();


+ 7
- 0
code/espurna/sensor.h View File

@ -20,6 +20,8 @@ Copyright (C) 2020 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
#include "system.h"
class BaseSensor;
namespace espurna {
namespace sensor {
@ -238,6 +240,11 @@ struct Info {
String description;
};
using NotifyCallback = bool (*)(const BaseSensor*);
void notify_after(duration::Milliseconds, NotifyCallback);
void notify_now(NotifyCallback);
} // namespace sensor
} // namespace espurna


+ 4
- 0
code/espurna/sensors/BaseSensor.h View File

@ -144,6 +144,10 @@ public:
virtual void resume() {
}
// Custom hook (usually to update sensor state outside of normal methods)
virtual void notify() {
}
// Loop-like method, call it in your main loop
virtual void tick() {
}


Loading…
Cancel
Save