|
10 | 10 | import warnings
|
11 | 11 | from time import sleep, time
|
12 | 12 | from threading import Event, Lock
|
| 13 | +try: |
| 14 | + from statistics import median |
| 15 | +except ImportError: |
| 16 | + from .compat import median |
13 | 17 |
|
14 | 18 | from .exc import InputDeviceError, DeviceClosed, DistanceSensorNoEcho
|
15 | 19 | from .devices import GPIODevice
|
@@ -103,13 +107,14 @@ def __init__(
|
103 | 107 |
|
104 | 108 | class SmoothedInputDevice(EventsMixin, InputDevice):
|
105 | 109 | """
|
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. |
108 | 112 |
|
109 | 113 | This class extends :class:`InputDevice` with a queue which is filled by a
|
110 | 114 | 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. |
113 | 118 |
|
114 | 119 | .. note::
|
115 | 120 |
|
@@ -140,19 +145,25 @@ class SmoothedInputDevice(EventsMixin, InputDevice):
|
140 | 145 | filled. If ``True``, a value will be returned immediately, but be
|
141 | 146 | aware that this value is likely to fluctuate excessively.
|
142 | 147 |
|
| 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 | +
|
143 | 154 | :param Factory pin_factory:
|
144 | 155 | See :doc:`api_pins` for more information (this is an advanced feature
|
145 | 156 | which most users can ignore).
|
146 | 157 | """
|
147 | 158 | 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): |
150 | 161 | self._queue = None
|
151 | 162 | super(SmoothedInputDevice, self).__init__(
|
152 | 163 | pin, pull_up, pin_factory=pin_factory
|
153 | 164 | )
|
154 | 165 | try:
|
155 |
| - self._queue = GPIOQueue(self, queue_len, sample_wait, partial) |
| 166 | + self._queue = GPIOQueue(self, queue_len, sample_wait, partial, average) |
156 | 167 | self.threshold = float(threshold)
|
157 | 168 | except:
|
158 | 169 | self.close()
|
|
0 commit comments