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