]> sigrok.org Git - libsigrokdecode.git/blob - decoders/graycode/pd.py
2edc8373c61993ed016e2b20b8ae05bf12dd1cc0
[libsigrokdecode.git] / decoders / graycode / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2017 Christoph Rackwitz <christoph.rackwitz@rwth-aachen.de>
5 ##
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.
10 ##
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.
15 ##
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/>.
18 ##
19
20 import math
21 import sigrokdecode as srd
22 from collections import deque
23
24 def bitpack(bits):
25     res = 0
26     for i, b in enumerate(bits):
27         res |= b << i
28     return res
29
30 def bitunpack(num, minbits=0):
31     res = []
32     while num or minbits > 0:
33         res.append(num & 1)
34         num >>= 1
35         minbits -= 1
36     return tuple(res)
37
38 def gray_encode(plain):
39     return plain & (plain >> 1)
40
41 def gray_decode(gray):
42     temp = gray
43     temp ^= (temp >> 8)
44     temp ^= (temp >> 4)
45     temp ^= (temp >> 2)
46     temp ^= (temp >> 1)
47     return temp
48
49 def prefix_fmt(value, emin=None):
50     sgn = (value > 0) - (value < 0)
51     value = abs(value)
52     p = math.log10(value) if value else 0
53     value = sgn * math.floor(value * 10**int(3 - p)) * 10**-int(3 - p)
54     e = p // 3 * 3
55     if emin is not None and e < emin:
56         e = emin
57     value *= 10**-e
58     p -= e
59     decimals = 2 - int(p)
60     prefixes = {-9: 'n', -6: 'µ', -3: 'm', 0: '', 3: 'k', 6: 'M', 9: 'G'}
61     return '{0:.{1}f} {2}'.format(value, decimals, prefixes[e])
62
63 class ChannelMapError(Exception):
64     pass
65
66 class Value:
67     def __init__(self, onchange):
68         self.onchange = onchange
69         self.timestamp = None
70         self.value = None
71
72     def get(self):
73         return self.value
74
75     def set(self, timestamp, newval):
76         if newval != self.value:
77             if self.value is not None:
78                 self.onchange(self.timestamp, self.value, timestamp, newval)
79
80             self.value = newval
81             self.timestamp = timestamp
82         elif False:
83             if self.value is not None:
84                 self.onchange(self.timestamp, self.value, timestamp, newval)
85
86 MAX_CHANNELS = 8 # 10 channels causes some weird problems...
87
88 class Decoder(srd.Decoder):
89     api_version = 3
90     id = 'graycode'
91     name = 'Gray code'
92     longname = 'Gray code and rotary encoder'
93     desc = 'Accumulate rotary encoder increments, provide timing statistics.'
94     license = 'gplv2+'
95     inputs = ['logic']
96     outputs = ['graycode']
97     optional_channels = tuple(
98         {'id': 'd{}'.format(i), 'name': 'D{}'.format(i), 'desc': 'Data line {}'.format(i)}
99         for i in range(MAX_CHANNELS)
100     )
101     options = (
102         {'id': 'edges', 'desc': 'Edges per rotation', 'default': 0},
103         {'id': 'avg_period', 'desc': 'Averaging period', 'default': 10},
104     )
105     annotations = (
106         ('phase', 'Phase'),
107         ('increment', 'Increment'),
108         ('count', 'Count'),
109         ('turns', 'Turns'),
110         ('interval', 'Interval'),
111         ('average', 'Average'),
112         ('rpm', 'Rate'),
113     )
114     annotation_rows = tuple((u, v, (i,)) for i, (u, v) in enumerate(annotations))
115
116     def __init__(self):
117         self.num_channels = 0
118         self.samplerate = None
119         self.last_n = deque()
120
121         self.phase = Value(self.on_phase)
122         self.increment = Value(self.on_increment)
123         self.count = Value(self.on_count)
124         self.turns = Value(self.on_turns)
125
126     def on_phase(self, told, vold, tnew, vnew):
127         self.put(told, tnew, self.out_ann, [0, ['{}'.format(vold)]])
128
129     def on_increment(self, told, vold, tnew, vnew):
130         if vold == 0:
131             message = '0'
132         elif abs(vold) == self.ENCODER_STEPS // 2:
133             message = '±π'
134         else:
135             message = '{:+d}'.format(vold)
136         self.put(told, tnew, self.out_ann, [1, [message]])
137
138     def on_count(self, told, vold, tnew, vnew):
139         self.put(told, tnew, self.out_ann, [2, ['{}'.format(vold)]])
140
141     def on_turns(self, told, vold, tnew, vnew):
142         self.put(told, tnew, self.out_ann, [3, ['{:+d}'.format(vold)]])
143
144     def metadata(self, key, value):
145         if key == srd.SRD_CONF_SAMPLERATE:
146             self.samplerate = value
147
148     def start(self):
149         self.out_ann = self.register(srd.OUTPUT_ANN)
150
151     def decode(self):
152         chmask = [self.has_channel(i) for i in range(MAX_CHANNELS)]
153         self.num_channels = sum(chmask)
154         if chmask != [i < self.num_channels for i in range(MAX_CHANNELS)]:
155             raise ChannelMapError('Assigned channels need to be contiguous')
156
157         self.ENCODER_STEPS = 1 << self.num_channels
158
159         startbits = self.wait()
160         curtime = self.samplenum
161
162         self.turns.set(self.samplenum, 0)
163         self.count.set(self.samplenum, 0)
164         self.phase.set(self.samplenum, gray_decode(bitpack(startbits[:self.num_channels])))
165
166         while True:
167             prevtime = curtime
168             bits = self.wait([{i: 'e'} for i in range(self.num_channels)])
169             curtime = self.samplenum
170
171             oldcount = self.count.get()
172             oldphase = self.phase.get()
173
174             newphase = gray_decode(bitpack(bits[:self.num_channels]))
175             self.phase.set(self.samplenum, newphase)
176
177             phasedelta_raw = (newphase - oldphase + (self.ENCODER_STEPS // 2 - 1)) % self.ENCODER_STEPS - (self.ENCODER_STEPS // 2 - 1)
178             phasedelta = phasedelta_raw
179             self.increment.set(self.samplenum, phasedelta)
180             if abs(phasedelta) == self.ENCODER_STEPS // 2:
181                 phasedelta = 0
182
183             self.count.set(self.samplenum, self.count.get() + phasedelta)
184
185             if self.options['edges']:
186                 self.turns.set(self.samplenum, self.count.get() // self.options['edges'])
187
188             if self.samplerate is not None:
189                 period = (curtime - prevtime) / self.samplerate
190                 freq = abs(phasedelta_raw) / period
191
192                 self.put(prevtime, curtime, self.out_ann, [4, [
193                     '{}s, {}Hz'.format(prefix_fmt(period), prefix_fmt(freq))]])
194
195                 if self.options['avg_period']:
196                     self.last_n.append((abs(phasedelta_raw), period))
197                     if len(self.last_n) > self.options['avg_period']:
198                         self.last_n.popleft()
199
200                     avg_period = sum(v for u, v in self.last_n) / (sum(u for u, v in self.last_n) or 1)
201                     self.put(prevtime, curtime, self.out_ann, [5, [
202                         '{}s, {}Hz'.format(prefix_fmt(avg_period),
203                             prefix_fmt(1 / avg_period))]])
204
205                 if self.options['edges']:
206                     self.put(prevtime, curtime, self.out_ann, [6, ['{}rpm'.format(prefix_fmt(60 * freq / self.options['edges'], emin=0))]])