]> sigrok.org Git - libsigrokdecode.git/blob - decoders/usb_signalling/pd.py
avr_isp: Add more parts
[libsigrokdecode.git] / decoders / usb_signalling / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2011 Gareth McMullin <gareth@blacksphere.co.nz>
5 ## Copyright (C) 2012-2020 Uwe Hermann <uwe@hermann-uwe.de>
6 ##
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ##
20
21 import sigrokdecode as srd
22 from common.srdhelper import SrdIntEnum
23
24 '''
25 OUTPUT_PYTHON format:
26
27 Packet:
28 [<ptype>, <pdata>]
29
30 <ptype>, <pdata>:
31  - 'SOP', None
32  - 'SYM', <sym>
33  - 'BIT', <bit>
34  - 'STUFF BIT', None
35  - 'EOP', None
36  - 'ERR', None
37  - 'KEEP ALIVE', None
38  - 'RESET', None
39
40 <sym>:
41  - 'J', 'K', 'SE0', or 'SE1'
42
43 <bit>:
44  - '0' or '1'
45  - Note: Symbols like SE0, SE1, and the J that's part of EOP don't yield 'BIT'.
46 '''
47
48 # Low-/full-speed symbols.
49 # Note: Low-speed J and K are inverted compared to the full-speed J and K!
50 symbols = {
51     'low-speed': {
52         # (<dp>, <dm>): <symbol/state>
53         (0, 0): 'SE0',
54         (1, 0): 'K',
55         (0, 1): 'J',
56         (1, 1): 'SE1',
57     },
58     'full-speed': {
59         # (<dp>, <dm>): <symbol/state>
60         (0, 0): 'SE0',
61         (1, 0): 'J',
62         (0, 1): 'K',
63         (1, 1): 'SE1',
64     },
65     'automatic': {
66         # (<dp>, <dm>): <symbol/state>
67         (0, 0): 'SE0',
68         (1, 0): 'FS_J',
69         (0, 1): 'LS_J',
70         (1, 1): 'SE1',
71     },
72     # After a PREamble PID, the bus segment between Host and Hub uses LS
73     # signalling rate and FS signalling polarity (USB 2.0 spec, 11.8.4: "For
74     # both upstream and downstream low-speed data, the hub is responsible for
75     # inverting the polarity of the data before transmitting to/from a
76     # low-speed port.").
77     'low-speed-rp': {
78         # (<dp>, <dm>): <symbol/state>
79         (0, 0): 'SE0',
80         (1, 0): 'J',
81         (0, 1): 'K',
82         (1, 1): 'SE1',
83     },
84 }
85
86 bitrates = {
87     'low-speed': 1500000, # 1.5Mb/s (+/- 1.5%)
88     'low-speed-rp': 1500000, # 1.5Mb/s (+/- 1.5%)
89     'full-speed': 12000000, # 12Mb/s (+/- 0.25%)
90     'automatic': None
91 }
92
93 sym_annotation = {
94     'J': [0, ['J']],
95     'K': [1, ['K']],
96     'SE0': [2, ['SE0', '0']],
97     'SE1': [3, ['SE1', '1']],
98 }
99
100 St = SrdIntEnum.from_str('St', 'IDLE GET_BIT GET_EOP WAIT_IDLE')
101
102 class SamplerateError(Exception):
103     pass
104
105 class Decoder(srd.Decoder):
106     api_version = 3
107     id = 'usb_signalling'
108     name = 'USB signalling'
109     longname = 'Universal Serial Bus (LS/FS) signalling'
110     desc = 'USB (low-speed/full-speed) signalling protocol.'
111     license = 'gplv2+'
112     inputs = ['logic']
113     outputs = ['usb_signalling']
114     tags = ['PC']
115     channels = (
116         {'id': 'dp', 'name': 'D+', 'desc': 'USB D+ signal'},
117         {'id': 'dm', 'name': 'D-', 'desc': 'USB D- signal'},
118     )
119     options = (
120         {'id': 'signalling', 'desc': 'Signalling',
121             'default': 'automatic', 'values': ('automatic', 'full-speed', 'low-speed')},
122     )
123     annotations = (
124         ('sym-j', 'J symbol'),
125         ('sym-k', 'K symbol'),
126         ('sym-se0', 'SE0 symbol'),
127         ('sym-se1', 'SE1 symbol'),
128         ('sop', 'Start of packet (SOP)'),
129         ('eop', 'End of packet (EOP)'),
130         ('bit', 'Bit'),
131         ('stuffbit', 'Stuff bit'),
132         ('error', 'Error'),
133         ('keep-alive', 'Low-speed keep-alive'),
134         ('reset', 'Reset'),
135     )
136     annotation_rows = (
137         ('bits', 'Bits', (4, 5, 6, 7, 8, 9, 10)),
138         ('symbols', 'Symbols', (0, 1, 2, 3)),
139     )
140
141     def __init__(self):
142         self.reset()
143
144     def reset(self):
145         self.samplerate = None
146         self.oldsym = 'J' # The "idle" state is J.
147         self.ss_block = None
148         self.bitrate = None
149         self.bitwidth = None
150         self.samplepos = None
151         self.samplenum_target = None
152         self.samplenum_edge = None
153         self.samplenum_lastedge = 0
154         self.edgepins = None
155         self.consecutive_ones = 0
156         self.bits = None
157         self.state = St.IDLE
158
159     def start(self):
160         self.out_python = self.register(srd.OUTPUT_PYTHON)
161         self.out_ann = self.register(srd.OUTPUT_ANN)
162
163     def metadata(self, key, value):
164         if key == srd.SRD_CONF_SAMPLERATE:
165             self.samplerate = value
166             self.signalling = self.options['signalling']
167             if self.signalling != 'automatic':
168                 self.update_bitrate()
169
170     def update_bitrate(self):
171         self.bitrate = bitrates[self.signalling]
172         self.bitwidth = float(self.samplerate) / float(self.bitrate)
173
174     def putpx(self, data):
175         s = self.samplenum_edge
176         self.put(s, s, self.out_python, data)
177
178     def putx(self, data):
179         s = self.samplenum_edge
180         self.put(s, s, self.out_ann, data)
181
182     def putpm(self, data):
183         e = self.samplenum_edge
184         self.put(self.ss_block, e, self.out_python, data)
185
186     def putm(self, data):
187         e = self.samplenum_edge
188         self.put(self.ss_block, e, self.out_ann, data)
189
190     def putpb(self, data):
191         s, e = self.samplenum_lastedge, self.samplenum_edge
192         self.put(s, e, self.out_python, data)
193
194     def putb(self, data):
195         s, e = self.samplenum_lastedge, self.samplenum_edge
196         self.put(s, e, self.out_ann, data)
197
198     def set_new_target_samplenum(self):
199         self.samplepos += self.bitwidth
200         self.samplenum_target = int(self.samplepos)
201         self.samplenum_lastedge = self.samplenum_edge
202         self.samplenum_edge = int(self.samplepos - (self.bitwidth / 2))
203
204     def wait_for_sop(self, sym):
205         # Wait for a Start of Packet (SOP), i.e. a J->K symbol change.
206         if sym != 'K' or self.oldsym != 'J':
207             return
208         self.consecutive_ones = 0
209         self.bits = ''
210         self.update_bitrate()
211         self.samplepos = self.samplenum - (self.bitwidth / 2) + 0.5
212         self.set_new_target_samplenum()
213         self.putpx(['SOP', None])
214         self.putx([4, ['SOP', 'S']])
215         self.state = St.GET_BIT
216
217     def handle_bit(self, b):
218         if self.consecutive_ones == 6:
219             if b == '0':
220                 # Stuff bit.
221                 self.putpb(['STUFF BIT', None])
222                 self.putb([7, ['Stuff bit: 0', 'SB: 0', '0']])
223                 self.consecutive_ones = 0
224             else:
225                 self.putpb(['ERR', None])
226                 self.putb([8, ['Bit stuff error', 'BS ERR', 'B']])
227                 self.state = St.IDLE
228         else:
229             # Normal bit (not a stuff bit).
230             self.putpb(['BIT', b])
231             self.putb([6, ['%s' % b]])
232             if b == '1':
233                 self.consecutive_ones += 1
234             else:
235                 self.consecutive_ones = 0
236
237     def get_eop(self, sym):
238         # EOP: SE0 for >= 1 bittime (usually 2 bittimes), then J.
239         self.set_new_target_samplenum()
240         self.putpb(['SYM', sym])
241         self.putb(sym_annotation[sym])
242         self.oldsym = sym
243         if sym == 'SE0':
244             pass
245         elif sym == 'J':
246             # Got an EOP.
247             self.putpm(['EOP', None])
248             self.putm([5, ['EOP', 'E']])
249             self.state = St.WAIT_IDLE
250         else:
251             self.putpm(['ERR', None])
252             self.putm([8, ['EOP Error', 'EErr', 'E']])
253             self.state = St.IDLE
254
255     def get_bit(self, sym):
256         self.set_new_target_samplenum()
257         b = '0' if self.oldsym != sym else '1'
258         self.oldsym = sym
259         if sym == 'SE0':
260             # Start of an EOP. Change state, save edge
261             self.state = St.GET_EOP
262             self.ss_block = self.samplenum_lastedge
263         else:
264             self.handle_bit(b)
265         self.putpb(['SYM', sym])
266         self.putb(sym_annotation[sym])
267         if len(self.bits) <= 16:
268             self.bits += b
269         if len(self.bits) == 16 and self.bits == '0000000100111100':
270             # Sync and low-speed PREamble seen
271             self.putpx(['EOP', None])
272             self.state = St.IDLE
273             self.signalling = 'low-speed-rp'
274             self.update_bitrate()
275             self.oldsym = 'J'
276         if b == '0':
277             edgesym = symbols[self.signalling][tuple(self.edgepins)]
278             if edgesym not in ('SE0', 'SE1'):
279                 if edgesym == sym:
280                     self.bitwidth = self.bitwidth - (0.001 * self.bitwidth)
281                     self.samplepos = self.samplepos - (0.01 * self.bitwidth)
282                 else:
283                     self.bitwidth = self.bitwidth + (0.001 * self.bitwidth)
284                     self.samplepos = self.samplepos + (0.01 * self.bitwidth)
285
286     def handle_idle(self, sym):
287         self.samplenum_edge = self.samplenum
288         se0_length = float(self.samplenum - self.samplenum_lastedge) / self.samplerate
289         if se0_length > 2.5e-6: # 2.5us
290             self.putpb(['RESET', None])
291             self.putb([10, ['Reset', 'Res', 'R']])
292             self.signalling = self.options['signalling']
293         elif se0_length > 1.2e-6 and self.signalling == 'low-speed':
294             self.putpb(['KEEP ALIVE', None])
295             self.putb([9, ['Keep-alive', 'KA', 'A']])
296
297         if sym == 'FS_J':
298             self.signalling = 'full-speed'
299             self.update_bitrate()
300         elif sym == 'LS_J':
301             self.signalling = 'low-speed'
302             self.update_bitrate()
303         self.oldsym = 'J'
304         self.state = St.IDLE
305
306     def decode(self):
307         if not self.samplerate:
308             raise SamplerateError('Cannot decode without samplerate.')
309
310         # Seed internal state from the very first sample.
311         pins = self.wait()
312         sym = symbols[self.options['signalling']][pins]
313         self.handle_idle(sym)
314
315         while True:
316             # State machine.
317             if self.state == St.IDLE:
318                 # Wait for any edge on either DP and/or DM.
319                 pins = self.wait([{0: 'e'}, {1: 'e'}])
320                 sym = symbols[self.signalling][pins]
321                 if sym == 'SE0':
322                     self.samplenum_lastedge = self.samplenum
323                     self.state = St.WAIT_IDLE
324                 else:
325                     self.wait_for_sop(sym)
326                 self.edgepins = pins
327             elif self.state in (St.GET_BIT, St.GET_EOP):
328                 # Wait until we're in the middle of the desired bit.
329                 self.edgepins = self.wait([{'skip': self.samplenum_edge - self.samplenum}])
330                 pins = self.wait([{'skip': self.samplenum_target - self.samplenum}])
331
332                 sym = symbols[self.signalling][pins]
333                 if self.state == St.GET_BIT:
334                     self.get_bit(sym)
335                 elif self.state == St.GET_EOP:
336                     self.get_eop(sym)
337             elif self.state == St.WAIT_IDLE:
338                 # Skip "all-low" input. Wait for high level on either DP or DM.
339                 pins = self.wait()
340                 while not pins[0] and not pins[1]:
341                     pins = self.wait([{0: 'h'}, {1: 'h'}])
342                 if self.samplenum - self.samplenum_lastedge > 1:
343                     sym = symbols[self.options['signalling']][pins]
344                     self.handle_idle(sym)
345                 else:
346                     sym = symbols[self.signalling][pins]
347                     self.wait_for_sop(sym)
348                 self.edgepins = pins