Skip to content

Commit bb0eced

Browse files
committed
Expose GPIOQueue average parameter in SmoothedInputDevice
1 parent 179ab51 commit bb0eced

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

gpiozero/input_devices.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010
import warnings
1111
from time import sleep, time
1212
from threading import Event, Lock
13+
try:
14+
from statistics import median
15+
except ImportError:
16+
from .compat import median
1317

1418
from .exc import InputDeviceError, DeviceClosed, DistanceSensorNoEcho
1519
from .devices import GPIODevice
@@ -103,13 +107,14 @@ def __init__(
103107

104108
class SmoothedInputDevice(EventsMixin, InputDevice):
105109
"""
106-
Represents a generic input device which takes its value from the mean of a
107-
queue of historical values.
110+
Represents a generic input device which takes its value from the average of
111+
a queue of historical values.
108112
109113
This class extends :class:`InputDevice` with a queue which is filled by a
110114
background thread which continually polls the state of the underlying
111-
device. The mean of the values in the queue is compared to a threshold
112-
which is used to determine the state of the :attr:`is_active` property.
115+
device. The average (a configurable function) of the values in the queue is
116+
compared to a threshold which is used to determine the state of the
117+
:attr:`is_active` property.
113118
114119
.. note::
115120
@@ -140,19 +145,25 @@ class SmoothedInputDevice(EventsMixin, InputDevice):
140145
filled. If ``True``, a value will be returned immediately, but be
141146
aware that this value is likely to fluctuate excessively.
142147
148+
:param average:
149+
The function used to average the values in the internal queue. This
150+
defaults to :func:`statistics.median` which a good selection for
151+
discarding outliers from jittery sensors. The function specific must
152+
accept a sequence of numbers and return a single number.
153+
143154
:param Factory pin_factory:
144155
See :doc:`api_pins` for more information (this is an advanced feature
145156
which most users can ignore).
146157
"""
147158
def __init__(
148-
self, pin=None, pull_up=False, threshold=0.5,
149-
queue_len=5, sample_wait=0.0, partial=False, pin_factory=None):
159+
self, pin=None, pull_up=False, threshold=0.5, queue_len=5,
160+
sample_wait=0.0, partial=False, average=median, pin_factory=None):
150161
self._queue = None
151162
super(SmoothedInputDevice, self).__init__(
152163
pin, pull_up, pin_factory=pin_factory
153164
)
154165
try:
155-
self._queue = GPIOQueue(self, queue_len, sample_wait, partial)
166+
self._queue = GPIOQueue(self, queue_len, sample_wait, partial, average)
156167
self.threshold = float(threshold)
157168
except:
158169
self.close()

0 commit comments

Comments
 (0)