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
25 # Symbols (used as states of our state machine, too)
35 '10000111': 'OUT', # Tokens
39 '11000011': 'DATA0', # Data
41 '01001011': 'ACK', # Handshake
47 def bitstr_to_num(bitstr):
52 return int(''.join(l), 2)
54 def packet_decode(packet):
57 pid = pids.get(pid, pid)
60 if pid in ('OUT', 'IN', 'SOF', 'SETUP'):
63 data = str(bitstr_to_num(data))
65 dev = bitstr_to_num(data[:7])
66 ep = bitstr_to_num(data[7:])
67 data = 'DEV %d EP %d' % (dev, ep)
69 elif pid in ('DATA0', 'DATA1'):
73 tmp += '%02x ' % bitstr_to_num(data[:8])
79 if sync != '00000001':
80 return 'SYNC INVALID!'
82 return pid + ' ' + data
84 class Decoder(srd.Decoder):
88 longname = 'Universal Serial Bus'
89 desc = 'Universal Serial Bus'
94 {'id': 'dp', 'name': 'D+', 'desc': 'USB D+ signal'},
95 {'id': 'dm', 'name': 'D-', 'desc': 'USB D- signal'},
100 ['Text', 'Human-readable text']
106 def start(self, metadata):
107 self.samplerate = metadata['samplerate']
109 # self.out_proto = self.add(srd.OUTPUT_PROTO, 'usb')
110 self.out_ann = self.add(srd.OUTPUT_ANN, 'usb')
112 if self.samplerate < 48000000:
113 raise Exception('Samplerate (%d) not sufficient for USB '
114 'decoding, need at least 48MHz' % self.samplerate)
116 # Initialise decoder state.
124 def decode(self, ss, es, data):
125 for (self.samplenum, (dm, dp)) in data:
133 if self.samplenum == 1:
134 # We ignore single sample width pulses.
135 # I sometimes get these with the OLS.
140 # How many bits since the last transition?
141 if self.packet != '' or self.sym != 'J':
142 bitcount = int((self.samplenum - 1) * 12000000 / self.samplerate)
146 if self.sym == 'SE0':
148 # End-Of-Packet (EOP)
149 self.put(0, 0, self.out_ann,
150 [0, [packet_decode(self.packet), self.packet]])
152 # Longer than EOP, assume reset.
153 self.put(0, 0, self.out_ann, [0, ['RESET']])
159 # Add bits to the packet string.
160 self.packet += '1' * bitcount
162 # Handle bit stuffing.
163 if bitcount < 6 and sym != 'SE0':
166 self.put(0, 0, self.out_ann, [0, ['BIT STUFF ERROR']])