]> sigrok.org Git - libsigrokdecode.git/blob - decoders/usb_signalling/pd.py
usb_signalling: detect bit stuffing errors
[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-2013 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, write to the Free Software
19 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
20 ##
21
22 import sigrokdecode as srd
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
38 <sym>:
39  - 'J', 'K', 'SE0', or 'SE1'
40
41 <bit>:
42  - '0' or '1'
43  - Note: Symbols like SE0, SE1, and the J that's part of EOP don't yield 'BIT'.
44 '''
45
46 # Low-/full-speed symbols.
47 # Note: Low-speed J and K are inverted compared to the full-speed J and K!
48 symbols = {
49     'low-speed': {
50         # (<dp>, <dm>): <symbol/state>
51         (0, 0): 'SE0',
52         (1, 0): 'K',
53         (0, 1): 'J',
54         (1, 1): 'SE1',
55     },
56     'full-speed': {
57         # (<dp>, <dm>): <symbol/state>
58         (0, 0): 'SE0',
59         (1, 0): 'J',
60         (0, 1): 'K',
61         (1, 1): 'SE1',
62     },
63 }
64
65 bitrates = {
66     'low-speed': 1500000,   # 1.5Mb/s (+/- 1.5%)
67     'full-speed': 12000000, # 12Mb/s (+/- 0.25%)
68 }
69
70 sym_annotation = {
71     'J': [0, ['J']],
72     'K': [1, ['K']],
73     'SE0': [2, ['SE0', '0']],
74     'SE1': [3, ['SE1', '1']],
75 }
76
77 class SamplerateError(Exception):
78     pass
79
80 class Decoder(srd.Decoder):
81     api_version = 2
82     id = 'usb_signalling'
83     name = 'USB signalling'
84     longname = 'Universal Serial Bus (LS/FS) signalling'
85     desc = 'USB (low-speed and full-speed) signalling protocol.'
86     license = 'gplv2+'
87     inputs = ['logic']
88     outputs = ['usb_signalling']
89     channels = (
90         {'id': 'dp', 'name': 'D+', 'desc': 'USB D+ signal'},
91         {'id': 'dm', 'name': 'D-', 'desc': 'USB D- signal'},
92     )
93     options = (
94         {'id': 'signalling', 'desc': 'Signalling',
95             'default': 'full-speed', 'values': ('full-speed', 'low-speed')},
96     )
97     annotations = (
98         ('sym-j', 'J symbol'),
99         ('sym-k', 'K symbol'),
100         ('sym-se0', 'SE0 symbol'),
101         ('sym-se1', 'SE1 symbol'),
102         ('sop', 'Start of packet (SOP)'),
103         ('eop', 'End of packet (EOP)'),
104         ('bit', 'Bit'),
105         ('stuffbit', 'Stuff bit'),
106         ('error', 'Error'),
107     )
108     annotation_rows = (
109         ('bits', 'Bits', (4, 5, 6, 7, 8)),
110         ('symbols', 'Symbols', (0, 1, 2, 3)),
111     )
112
113     def __init__(self):
114         self.samplerate = None
115         self.oldsym = 'J' # The "idle" state is J.
116         self.ss_sop = None
117         self.ss_block = None
118         self.samplenum = 0
119         self.syms = []
120         self.bitrate = None
121         self.bitwidth = None
122         self.samplepos = None
123         self.samplenum_target = None
124         self.samplenum_edge = None
125         self.oldpins = None
126         self.edgepins = None
127         self.consecutive_ones = 0
128         self.state = 'IDLE'
129
130     def start(self):
131         self.out_python = self.register(srd.OUTPUT_PYTHON)
132         self.out_ann = self.register(srd.OUTPUT_ANN)
133
134     def metadata(self, key, value):
135         if key == srd.SRD_CONF_SAMPLERATE:
136             self.samplerate = value
137             self.bitrate = bitrates[self.options['signalling']]
138             self.bitwidth = float(self.samplerate) / float(self.bitrate)
139             self.halfbit = int(self.bitwidth / 2)
140
141     def putpx(self, data):
142         self.put(self.samplenum, self.samplenum, self.out_python, data)
143
144     def putx(self, data):
145         self.put(self.samplenum, self.samplenum, self.out_ann, data)
146
147     def putpm(self, data):
148         s, h = self.samplenum, self.halfbit
149         self.put(self.ss_block - h, s + h, self.out_python, data)
150
151     def putm(self, data):
152         s, h = self.samplenum, self.halfbit
153         self.put(self.ss_block - h, s + h, self.out_ann, data)
154
155     def putpb(self, data):
156         s, h = self.samplenum, self.halfbit
157         self.put(self.samplenum_edge, s + h, self.out_python, data)
158
159     def putb(self, data):
160         s, h = self.samplenum, self.halfbit
161         self.put(self.samplenum_edge, s + h, self.out_ann, data)
162
163     def set_new_target_samplenum(self):
164         self.samplepos += self.bitwidth;
165         self.samplenum_target = int(self.samplepos)
166         self.samplenum_edge = int(self.samplepos - (self.bitwidth / 2))
167
168     def wait_for_sop(self, sym):
169         # Wait for a Start of Packet (SOP), i.e. a J->K symbol change.
170         if sym != 'K':
171             self.oldsym = sym
172             return
173         self.consecutive_ones = 0
174         self.ss_sop = self.samplenum
175         self.samplepos = self.ss_sop - (self.bitwidth / 2) + 0.5
176         self.set_new_target_samplenum()
177         self.putpx(['SOP', None])
178         self.putx([4, ['SOP', 'S']])
179         self.state = 'GET BIT'
180
181     def handle_bit(self, sym, b):
182         if self.consecutive_ones == 6:
183             if b == '0':
184                 # Stuff bit.
185                 self.putpb(['STUFF BIT', None])
186                 self.putb([7, ['Stuff bit: 0', 'SB: 0', '0']])
187                 self.consecutive_ones = 0
188             else:
189                 self.putpb(['ERR', None])
190                 self.putb([8, ['Bit stuff error', 'BS ERR', 'B']])
191                 self.state = 'IDLE'
192         else:
193             # Normal bit (not a stuff bit).
194             self.putpb(['BIT', b])
195             self.putb([6, ['%s' % b]])
196             if b == '1':
197                 self.consecutive_ones += 1
198             else:
199                 self.consecutive_ones = 0
200
201     def get_eop(self, sym):
202         # EOP: SE0 for >= 1 bittime (usually 2 bittimes), then J.
203         self.syms.append(sym)
204         self.putpb(['SYM', sym])
205         self.putb(sym_annotation[sym])
206         self.set_new_target_samplenum()
207         self.oldsym = sym
208         if self.syms[-2:] == ['SE0', 'J']:
209             # Got an EOP.
210             self.putpm(['EOP', None])
211             self.putm([5, ['EOP', 'E']])
212             self.syms, self.state = [], 'IDLE'
213             self.bitwidth = float(self.samplerate) / float(self.bitrate)
214
215     def get_bit(self, sym):
216         if sym == 'SE0':
217             # Start of an EOP. Change state, run get_eop() for this bit.
218             self.state = 'GET EOP'
219             self.ss_block = self.samplenum
220             self.get_eop(sym)
221             return
222         self.syms.append(sym)
223         self.putpb(['SYM', sym])
224         b = '0' if self.oldsym != sym else '1'
225         self.putb(sym_annotation[sym])
226         if self.oldsym != sym:
227             edgesym = symbols[self.options['signalling']][tuple(self.edgepins)]
228             if edgesym not in ('SE0', 'SE1'):
229                 if edgesym == sym:
230                     self.bitwidth = self.bitwidth - (0.001 * self.bitwidth)
231                     self.samplepos = self.samplepos - (0.01 * self.bitwidth)
232                 else:
233                     self.bitwidth = self.bitwidth + (0.001 * self.bitwidth)
234                     self.samplepos = self.samplepos + (0.01 * self.bitwidth)
235         self.handle_bit(sym, b)
236         self.set_new_target_samplenum()
237         self.oldsym = sym
238
239     def decode(self, ss, es, data):
240         if not self.samplerate:
241             raise SamplerateError('Cannot decode without samplerate.')
242         for (self.samplenum, pins) in data:
243             # State machine.
244             if self.state == 'IDLE':
245                 # Ignore identical samples early on (for performance reasons).
246                 if self.oldpins == pins:
247                     continue
248                 self.oldpins = pins
249                 sym = symbols[self.options['signalling']][tuple(pins)]
250                 self.wait_for_sop(sym)
251                 self.edgepins = pins
252             elif self.state in ('GET BIT', 'GET EOP'):
253                 # Wait until we're in the middle of the desired bit.
254                 if self.samplenum == self.samplenum_edge:
255                     self.edgepins = pins
256                 if self.samplenum < self.samplenum_target:
257                     continue
258                 sym = symbols[self.options['signalling']][tuple(pins)]
259                 if self.state == 'GET BIT':
260                     self.get_bit(sym)
261                 elif self.state == 'GET EOP':
262                     self.get_eop(sym)