2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2017 Christoph Rackwitz <christoph.rackwitz@rwth-aachen.de>
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
21 import sigrokdecode as srd
22 from collections import deque
23 from common.srdhelper import bitpack, bitunpack
25 def gray_encode(plain):
26 return plain & (plain >> 1)
28 def gray_decode(gray):
36 def prefix_fmt(value, emin=None):
37 sgn = (value > 0) - (value < 0)
39 p = math.log10(value) if value else 0
40 value = sgn * math.floor(value * 10**int(3 - p)) * 10**-int(3 - p)
42 if emin is not None and e < emin:
47 prefixes = {-9: 'n', -6: 'µ', -3: 'm', 0: '', 3: 'k', 6: 'M', 9: 'G'}
48 return '{0:.{1}f} {2}'.format(value, decimals, prefixes[e])
50 class ChannelMapError(Exception):
54 def __init__(self, onchange):
55 self.onchange = onchange
62 def set(self, timestamp, newval):
63 if newval != self.value:
64 if self.value is not None:
65 self.onchange(self.timestamp, self.value, timestamp, newval)
68 self.timestamp = timestamp
70 if self.value is not None:
71 self.onchange(self.timestamp, self.value, timestamp, newval)
73 MAX_CHANNELS = 8 # 10 channels causes some weird problems...
75 class Decoder(srd.Decoder):
79 longname = 'Gray code and rotary encoder'
80 desc = 'Accumulate rotary encoder increments, provide statistics.'
85 optional_channels = tuple(
86 {'id': 'd{}'.format(i), 'name': 'D{}'.format(i), 'desc': 'Data line {}'.format(i)}
87 for i in range(MAX_CHANNELS)
90 {'id': 'edges', 'desc': 'Edges per rotation', 'default': 0},
91 {'id': 'avg_period', 'desc': 'Averaging period', 'default': 10},
95 ('increment', 'Increment'),
98 ('interval', 'Interval'),
99 ('average', 'Average'),
102 annotation_rows = tuple((u + 's', v + 's', (i,)) for i, (u, v) in enumerate(annotations))
108 self.num_channels = 0
109 self.samplerate = None
110 self.last_n = deque()
112 self.phase = Value(self.on_phase)
113 self.increment = Value(self.on_increment)
114 self.count = Value(self.on_count)
115 self.turns = Value(self.on_turns)
117 def on_phase(self, told, vold, tnew, vnew):
118 self.put(told, tnew, self.out_ann, [0, ['{}'.format(vold)]])
120 def on_increment(self, told, vold, tnew, vnew):
123 elif abs(vold) == self.ENCODER_STEPS // 2:
126 message = '{:+d}'.format(vold)
127 self.put(told, tnew, self.out_ann, [1, [message]])
129 def on_count(self, told, vold, tnew, vnew):
130 self.put(told, tnew, self.out_ann, [2, ['{}'.format(vold)]])
132 def on_turns(self, told, vold, tnew, vnew):
133 self.put(told, tnew, self.out_ann, [3, ['{:+d}'.format(vold)]])
135 def metadata(self, key, value):
136 if key == srd.SRD_CONF_SAMPLERATE:
137 self.samplerate = value
140 self.out_ann = self.register(srd.OUTPUT_ANN)
143 chmask = [self.has_channel(i) for i in range(MAX_CHANNELS)]
144 self.num_channels = sum(chmask)
145 if chmask != [i < self.num_channels for i in range(MAX_CHANNELS)]:
146 raise ChannelMapError('Assigned channels need to be contiguous')
148 self.ENCODER_STEPS = 1 << self.num_channels
150 startbits = self.wait()
151 curtime = self.samplenum
153 self.turns.set(self.samplenum, 0)
154 self.count.set(self.samplenum, 0)
155 self.phase.set(self.samplenum, gray_decode(bitpack(startbits[:self.num_channels])))
159 bits = self.wait([{i: 'e'} for i in range(self.num_channels)])
160 curtime = self.samplenum
162 oldcount = self.count.get()
163 oldphase = self.phase.get()
165 newphase = gray_decode(bitpack(bits[:self.num_channels]))
166 self.phase.set(self.samplenum, newphase)
168 phasedelta_raw = (newphase - oldphase + (self.ENCODER_STEPS // 2 - 1)) % self.ENCODER_STEPS - (self.ENCODER_STEPS // 2 - 1)
169 phasedelta = phasedelta_raw
170 self.increment.set(self.samplenum, phasedelta)
171 if abs(phasedelta) == self.ENCODER_STEPS // 2:
174 self.count.set(self.samplenum, self.count.get() + phasedelta)
176 if self.options['edges']:
177 self.turns.set(self.samplenum, self.count.get() // self.options['edges'])
180 period = (curtime - prevtime) / self.samplerate
181 freq = abs(phasedelta_raw) / period
183 self.put(prevtime, curtime, self.out_ann, [4, [
184 '{}s, {}Hz'.format(prefix_fmt(period), prefix_fmt(freq))]])
186 if self.options['avg_period']:
187 self.last_n.append((abs(phasedelta_raw), period))
188 if len(self.last_n) > self.options['avg_period']:
189 self.last_n.popleft()
191 avg_period = sum(v for u, v in self.last_n) / (sum(u for u, v in self.last_n) or 1)
192 self.put(prevtime, curtime, self.out_ann, [5, [
193 '{}s, {}Hz'.format(prefix_fmt(avg_period),
194 prefix_fmt(1 / avg_period))]])
196 if self.options['edges']:
197 self.put(prevtime, curtime, self.out_ann, [6, ['{}rpm'.format(prefix_fmt(60 * freq / self.options['edges'], emin=0))]])