2018-06-12 00:36:43 +02:00
|
|
|
import time
|
|
|
|
|
2018-06-11 21:07:54 +02:00
|
|
|
from platypush.backend import Backend
|
2019-08-14 19:49:19 +02:00
|
|
|
from platypush.context import get_plugin
|
2018-06-11 21:07:54 +02:00
|
|
|
from platypush.message.event.sensor import SensorDataChangeEvent, \
|
|
|
|
SensorDataAboveThresholdEvent, SensorDataBelowThresholdEvent
|
|
|
|
|
|
|
|
|
|
|
|
class SensorBackend(Backend):
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
|
|
|
Abstract backend for polling sensors.
|
|
|
|
|
|
|
|
Triggers:
|
2018-06-12 00:36:43 +02:00
|
|
|
|
2018-06-26 00:16:39 +02:00
|
|
|
* :class:`platypush.message.event.sensor.SensorDataChangeEvent` if the measurements of a sensor have changed
|
2019-07-02 14:04:25 +02:00
|
|
|
* :class:`platypush.message.event.sensor.SensorDataAboveThresholdEvent` if the measurements of a sensor have
|
|
|
|
gone above a configured threshold
|
|
|
|
* :class:`platypush.message.event.sensor.SensorDataBelowThresholdEvent` if the measurements of a sensor have
|
|
|
|
gone below a configured threshold
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
2018-06-11 21:07:54 +02:00
|
|
|
|
2019-08-14 19:49:19 +02:00
|
|
|
default_tolerance = 1e-7
|
|
|
|
|
|
|
|
def __init__(self, plugin=None, plugin_args=None, thresholds=None, tolerance=default_tolerance, poll_seconds=None,
|
|
|
|
enabled_sensors=None, **kwargs):
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
2019-08-14 19:49:19 +02:00
|
|
|
:param plugin: If set, then this plugin instance, referenced by plugin id, will be polled
|
|
|
|
through ``get_plugin()``. Example: ``'gpio.sensor.bme280'`` or ``'gpio.sensor.envirophat'``.
|
|
|
|
:type plugin: str
|
|
|
|
|
|
|
|
:param plugin_args: If plugin is set and its ``get_measurement()`` method accepts optional arguments, then you
|
|
|
|
can pass those arguments through ``plugin_args``.
|
|
|
|
:type plugin_args: dict
|
|
|
|
|
2019-07-02 14:04:25 +02:00
|
|
|
:param thresholds: Thresholds can be either a scalar value or a dictionary (e.g. ``{"temperature": 20.0}``).
|
|
|
|
Sensor threshold events will be fired when measurements get above or below these values.
|
|
|
|
Set it as a scalar if your get_measurement() code returns a scalar, as a dictionary if it returns a
|
2019-08-14 19:49:19 +02:00
|
|
|
dictionary of values. For instance, if your sensor code returns both humidity and temperature in a format
|
|
|
|
like ``{'humidity':60.0, 'temperature': 25.0}``, you'll want to set up a threshold on temperature with a
|
|
|
|
syntax like ``{'temperature':20.0}`` to trigger events when the temperature goes above/below 20 degrees.
|
2018-06-11 21:07:54 +02:00
|
|
|
|
2019-08-14 19:49:19 +02:00
|
|
|
:param tolerance: If set, then the sensor change events will be triggered only if the difference between
|
|
|
|
the new value and the previous value is higher than the specified tolerance. Example::
|
|
|
|
|
|
|
|
{
|
|
|
|
"temperature": 0.01, # Tolerance on the 2nd decimal digit
|
|
|
|
"humidity": 0.1 # Tolerance on the 1st decimal digit
|
|
|
|
}
|
|
|
|
|
|
|
|
:type tolerance: dict or float
|
2018-06-11 21:07:54 +02:00
|
|
|
|
2019-07-02 14:04:25 +02:00
|
|
|
:param poll_seconds: If set, the thread will wait for the specified number of seconds between a read and the
|
|
|
|
next one.
|
2018-06-26 00:16:39 +02:00
|
|
|
:type poll_seconds: float
|
2019-08-14 19:49:19 +02:00
|
|
|
|
|
|
|
:param enabled_sensors: If ``get_measurement()`` returns data in dict form, then ``enabled_sensors`` selects
|
|
|
|
which keys should be taken into account when monitoring for new events (e.g. "temperature" or "humidity").
|
|
|
|
:type enabled_sensors: dict (in the form ``name -> [True/False]``), set or list
|
2018-06-11 21:07:54 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
super().__init__(**kwargs)
|
2018-06-12 00:36:43 +02:00
|
|
|
|
2018-06-11 22:12:25 +02:00
|
|
|
self.data = None
|
2019-08-14 19:49:19 +02:00
|
|
|
self.plugin = plugin
|
|
|
|
self.plugin_args = plugin_args or {}
|
2018-06-11 21:07:54 +02:00
|
|
|
self.thresholds = thresholds
|
2019-08-14 20:39:21 +02:00
|
|
|
self.tolerance = tolerance
|
2018-06-12 00:36:43 +02:00
|
|
|
self.poll_seconds = poll_seconds
|
2018-06-11 21:07:54 +02:00
|
|
|
|
2019-08-14 19:49:19 +02:00
|
|
|
if isinstance(enabled_sensors, list):
|
|
|
|
enabled_sensors = set(enabled_sensors)
|
|
|
|
if isinstance(enabled_sensors, set):
|
|
|
|
enabled_sensors = {k: True for k in enabled_sensors}
|
|
|
|
|
|
|
|
self.enabled_sensors = enabled_sensors or {}
|
|
|
|
|
2018-06-11 21:07:54 +02:00
|
|
|
def get_measurement(self):
|
2019-08-14 19:49:19 +02:00
|
|
|
"""
|
|
|
|
Wrapper around ``plugin.get_measurement()`` that can filter events on specified enabled sensors data or on
|
|
|
|
specified tolerance values. It can be overridden by derived classes.
|
|
|
|
"""
|
|
|
|
if not self.plugin:
|
|
|
|
raise NotImplementedError('No plugin specified')
|
|
|
|
|
|
|
|
plugin = get_plugin(self.plugin)
|
|
|
|
data = plugin.get_data(**self.plugin_args).output
|
|
|
|
|
|
|
|
if self.enabled_sensors:
|
|
|
|
data = {
|
|
|
|
sensor: data[sensor]
|
|
|
|
for sensor, enabled in self.enabled_sensors.items()
|
|
|
|
if enabled and sensor in data
|
|
|
|
}
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
def get_new_data(self, new_data):
|
|
|
|
if self.data is None or new_data is None:
|
|
|
|
return new_data
|
|
|
|
|
|
|
|
# noinspection PyBroadException
|
|
|
|
try:
|
|
|
|
# Scalar data case
|
|
|
|
new_data = float(new_data)
|
|
|
|
return new_data if abs(new_data - self.data) >= self.tolerance else None
|
|
|
|
except:
|
|
|
|
# If it's not a scalar then it should be a dict
|
|
|
|
assert isinstance(new_data, dict)
|
|
|
|
|
|
|
|
ret = {}
|
|
|
|
for k, v in new_data.items():
|
|
|
|
if (v is None and self.data.get(k) is not None) \
|
|
|
|
or k not in self.data \
|
|
|
|
or self.tolerance is None:
|
|
|
|
ret[k] = v
|
|
|
|
continue
|
|
|
|
|
2019-08-14 20:39:21 +02:00
|
|
|
if v is None:
|
|
|
|
continue
|
|
|
|
|
2019-08-14 22:45:50 +02:00
|
|
|
tolerance = None
|
2020-01-05 00:46:46 +01:00
|
|
|
is_nan = False
|
|
|
|
old_v = None
|
2019-08-14 22:45:50 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
v = float(v)
|
2019-08-14 22:49:18 +02:00
|
|
|
old_v = float(self.data.get(k))
|
2019-08-14 22:45:50 +02:00
|
|
|
except (TypeError, ValueError):
|
2020-01-05 00:46:46 +01:00
|
|
|
is_nan = True
|
2019-08-14 22:45:50 +02:00
|
|
|
|
2020-01-05 00:46:46 +01:00
|
|
|
if not is_nan:
|
2019-08-14 22:45:50 +02:00
|
|
|
if isinstance(self.tolerance, dict):
|
|
|
|
tolerance = float(self.tolerance.get(k, self.default_tolerance))
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
tolerance = float(self.tolerance)
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
pass
|
|
|
|
|
2020-01-05 00:46:46 +01:00
|
|
|
if tolerance is None or is_nan or abs(v - old_v) >= tolerance:
|
2019-08-14 19:49:19 +02:00
|
|
|
ret[k] = v
|
|
|
|
|
|
|
|
return ret
|
2018-06-11 21:07:54 +02:00
|
|
|
|
2020-01-05 00:46:46 +01:00
|
|
|
def on_stop(self):
|
|
|
|
if not self.plugin:
|
|
|
|
return
|
|
|
|
|
|
|
|
plugin = get_plugin(self.plugin)
|
|
|
|
if plugin and hasattr(plugin, 'close'):
|
|
|
|
plugin.close()
|
|
|
|
|
2018-10-25 20:45:58 +02:00
|
|
|
def run(self):
|
|
|
|
super().run()
|
2018-06-11 23:49:37 +02:00
|
|
|
self.logger.info('Initialized {} sensor backend'.format(self.__class__.__name__))
|
2018-06-11 21:07:54 +02:00
|
|
|
|
|
|
|
while not self.should_stop():
|
2019-08-14 19:49:19 +02:00
|
|
|
data = self.get_measurement()
|
|
|
|
new_data = self.get_new_data(data)
|
|
|
|
|
|
|
|
if new_data:
|
2018-06-11 21:07:54 +02:00
|
|
|
self.bus.post(SensorDataChangeEvent(data=new_data))
|
|
|
|
|
2018-07-15 17:28:13 +02:00
|
|
|
data_below_threshold = {}
|
|
|
|
data_above_threshold = {}
|
|
|
|
|
2018-06-11 21:07:54 +02:00
|
|
|
if self.thresholds:
|
2019-08-14 19:49:19 +02:00
|
|
|
if isinstance(self.thresholds, dict) and isinstance(data, dict):
|
2018-08-25 12:29:20 +02:00
|
|
|
for (measure, thresholds) in self.thresholds.items():
|
2019-08-14 19:49:19 +02:00
|
|
|
if measure not in data:
|
2018-06-11 21:07:54 +02:00
|
|
|
continue
|
|
|
|
|
2018-08-25 12:29:20 +02:00
|
|
|
if not isinstance(thresholds, list):
|
|
|
|
thresholds = [thresholds]
|
|
|
|
|
|
|
|
for threshold in thresholds:
|
2019-08-14 19:49:19 +02:00
|
|
|
if data[measure] > threshold and (self.data is None or (
|
2018-08-25 12:29:20 +02:00
|
|
|
measure in self.data and self.data[measure] <= threshold)):
|
2019-08-14 19:49:19 +02:00
|
|
|
data_above_threshold[measure] = data[measure]
|
|
|
|
elif data[measure] < threshold and (self.data is None or (
|
2018-08-25 12:29:20 +02:00
|
|
|
measure in self.data and self.data[measure] >= threshold)):
|
2019-08-14 19:49:19 +02:00
|
|
|
data_below_threshold[measure] = data[measure]
|
2018-07-15 17:28:13 +02:00
|
|
|
|
|
|
|
if data_below_threshold:
|
|
|
|
self.bus.post(SensorDataBelowThresholdEvent(data=data_below_threshold))
|
|
|
|
|
|
|
|
if data_above_threshold:
|
|
|
|
self.bus.post(SensorDataAboveThresholdEvent(data=data_above_threshold))
|
|
|
|
|
2019-08-14 20:39:21 +02:00
|
|
|
self.data = data
|
|
|
|
|
|
|
|
if new_data:
|
|
|
|
if isinstance(new_data, dict):
|
|
|
|
for k, v in new_data.items():
|
|
|
|
self.data[k] = v
|
|
|
|
else:
|
|
|
|
self.data = new_data
|
2018-06-11 21:07:54 +02:00
|
|
|
|
2018-06-12 00:36:43 +02:00
|
|
|
if self.poll_seconds:
|
|
|
|
time.sleep(self.poll_seconds)
|
|
|
|
|
2018-06-11 21:07:54 +02:00
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|