2 ## This file is part of the sigrok project.
4 ## Copyright (C) 2011 Gareth McMullin <gareth@blacksphere.co.nz>
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, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 # USB (full-speed) protocol decoder
23 import sigrokdecode as srd
26 SE0, J, K, SE1 = 0, 1, 2, 3
38 '10000111': 'OUT', # Tokens
42 '11000011': 'DATA0', # Data
44 '01001011': 'ACK', # Handshake
50 def bitstr_to_num(bitstr):
55 return int(''.join(l), 2)
57 def packet_decode(packet):
60 pid = pids.get(pid, pid)
63 if pid in ('OUT', 'IN', 'SOF', 'SETUP'):
66 data = str(bitstr_to_num(data))
68 dev = bitstr_to_num(data[:7])
69 ep = bitstr_to_num(data[7:])
70 data = 'DEV %d EP %d' % (dev, ep)
72 elif pid in ('DATA0', 'DATA1'):
76 tmp += '%02x ' % bitstr_to_num(data[:8])
82 if sync != '00000001':
83 return 'SYNC INVALID!'
85 return pid + ' ' + data
87 class Decoder(srd.Decoder):
91 longname = 'Universal Serial Bus'
92 desc = 'Universal Serial Bus'
93 longdesc = '...longdesc...'
98 {'id': 'dp', 'name': 'D+', 'desc': 'USB D+ signal'},
99 {'id': 'dm', 'name': 'D-', 'desc': 'USB D- signal'},
110 def start(self, metadata):
111 self.rate = metadata['samplerate']
113 # self.out_proto = self.add(srd.OUTPUT_PROTO, 'usb')
114 self.out_ann = self.add(srd.OUTPUT_ANN, 'usb')
116 if self.rate < 48000000:
117 raise Exception('Sample rate (%d) not sufficient for USB '
118 'decoding, need at least 48MHz' % self.rate)
120 # Initialise decoder state.
128 def decode(self, ss, es, data):
129 for (samplenum, (dm, dp)) in data:
140 # We ignore single sample width pulses.
141 # I sometimes get these with the OLS.
146 # How many bits since the last transition?
147 if self.packet != '' or self.sym != J:
148 bitcount = int((self.scount - 1) * 12000000 / self.rate)
154 # End-Of-Packet (EOP)
155 self.put(0, 0, self.out_ann,
156 [0, [packet_decode(self.packet), self.packet]])
158 # Longer than EOP, assume reset.
159 self.put(0, 0, self.out_ann, [0, ['RESET']])
165 # Add bits to the packet string.
166 self.packet += '1' * bitcount
168 # Handle bit stuffing.
169 if bitcount < 6 and sym != SE0:
172 self.put(0, 0, self.out_ann, [0, ['BIT STUFF ERROR']])