]> sigrok.org Git - libsigrokdecode.git/blob - decoders/usb_packet/pd.py
s/out_proto/out_python/.
[libsigrokdecode.git] / decoders / usb_packet / 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  - 'SYNC', <sync>
32  - 'PID', <pid>
33  - 'ADDR', <addr>
34  - 'EP', <ep>
35  - 'CRC5', <crc5>
36  - 'CRC16', <crc16>
37  - 'EOP', <eop>
38  - 'FRAMENUM', <framenum>
39  - 'DATABYTE', <databyte>
40  - 'HUBADDR', <hubaddr>
41  - 'SC', <sc>
42  - 'PORT', <port>
43  - 'S', <s>
44  - 'E/U', <e/u>
45  - 'ET', <et>
46  - 'PACKET', [<pcategory>, <pname>, <pinfo>]
47
48 <pcategory>, <pname>, <pinfo>:
49  - 'TOKEN', 'OUT', [<sync>, <pid>, <addr>, <ep>, <crc5>, <eop>]
50  - 'TOKEN', 'IN', [<sync>, <pid>, <addr>, <ep>, <crc5>, <eop>]
51  - 'TOKEN', 'SOF', [<sync>, <pid>, <framenum>, <crc5>, <eop>]
52  - 'TOKEN', 'SETUP', [<sync>, <pid>, <addr>, <ep>, <crc5>, <eop>]
53  - 'DATA', 'DATA0', [<sync>, <pid>, <databytes>, <crc16>, <eop>]
54  - 'DATA', 'DATA1', [<sync>, <pid>, <databytes>, <crc16>, <eop>]
55  - 'DATA', 'DATA2', [<sync>, <pid>, <databytes>, <crc16>, <eop>]
56  - 'DATA', 'MDATA', [<sync>, <pid>, <databytes>, <crc16>, <eop>]
57  - 'HANDSHAKE', 'ACK', [<sync>, <pid>, <eop>]
58  - 'HANDSHAKE', 'NACK', [<sync>, <pid>, <eop>]
59  - 'HANDSHAKE', 'STALL', [<sync>, <pid>, <eop>]
60  - 'HANDSHAKE', 'NYET', [<sync>, <pid>, <eop>]
61  - 'SPECIAL', 'PRE', [<sync>, <pid>, <addr>, <ep>, <crc5>, <eop>]
62  - 'SPECIAL', 'ERR', [<sync>, <pid>, <eop>]
63  - 'SPECIAL', 'SPLIT',
64    [<sync>, <pid>, <hubaddr>, <sc>, <port>, <s>, <e/u>, <et>, <crc5>, <eop>]
65  - 'SPECIAL', 'PING', [<sync>, <pid>, <addr>, <ep>, <crc5>, <eop>]
66  - 'SPECIAL', 'Reserved', None
67
68 <sync>: SYNC field bitstring, normally '00000001' (8 chars).
69 <pid>: Packet ID bitstring, e.g. '11000011' for DATA0 (8 chars).
70 <addr>: Address field number, 0-127 (7 bits).
71 <ep>: Endpoint number, 0-15 (4 bits).
72 <crc5>: CRC-5 number (5 bits).
73 <crc16>: CRC-16 number (16 bits).
74 <eop>: End of packet marker. List of symbols, usually ['SE0', 'SE0', 'J'].
75 <framenum>: USB (micro)frame number, 0-2047 (11 bits).
76 <databyte>: A single data byte, e.g. 0x55.
77 <databytes>: List of data bytes, e.g. [0x55, 0xaa, 0x99] (0 - 1024 bytes).
78 <hubaddr>: TODO
79 <sc>: TODO
80 <port>: TODO
81 <s>: TODO
82 <e/u>: TODO
83 <et>: TODO
84 '''
85
86 # Packet IDs (PIDs).
87 # The first 4 bits are the 'packet type' field, the last 4 bits are the
88 # 'check field' (each bit in the check field must be the inverse of the resp.
89 # bit in the 'packet type' field; if not, that's a 'PID error').
90 # For the 4-bit strings, the left-most '1' or '0' is the LSB, i.e. it's sent
91 # to the bus first.
92 pids = {
93     # Tokens
94     '10000111': ['OUT', 'Address & EP number in host-to-function transaction'],
95     '10010110': ['IN', 'Address & EP number in function-to-host transaction'],
96     '10100101': ['SOF', 'Start-Of-Frame marker & frame number'],
97     '10110100': ['SETUP', 'Address & EP number in host-to-function transaction for SETUP to a control pipe'],
98
99     # Data
100     # Note: DATA2 and MDATA are HS-only.
101     '11000011': ['DATA0', 'Data packet PID even'],
102     '11010010': ['DATA1', 'Data packet PID odd'],
103     '11100001': ['DATA2', 'Data packet PID HS, high bandwidth isosynchronous transaction in a microframe'],
104     '11110000': ['MDATA', 'Data packet PID HS for split and high-bandwidth isosynchronous transactions'],
105
106     # Handshake
107     '01001011': ['ACK', 'Receiver accepts error-free packet'],
108     '01011010': ['NAK', 'Receiver cannot accept or transmitter cannot send'],
109     '01111000': ['STALL', 'EP halted or control pipe request unsupported'],
110     '01101001': ['NYET', 'No response yet from receiver'],
111
112     # Special
113     '00111100': ['PRE', 'Host-issued preamble; enables downstream bus traffic to low-speed devices'],
114     '00111100': ['ERR', 'Split transaction error handshake'],
115     '00011110': ['SPLIT', 'HS split transaction token'],
116     '00101101': ['PING', 'HS flow control probe for a bulk/control EP'],
117     '00001111': ['Reserved', 'Reserved PID'],
118 }
119
120 def get_category(pidname):
121     if pidname in ('OUT', 'IN', 'SOF', 'SETUP'):
122         return 'TOKEN'
123     elif pidname in ('DATA0', 'DATA1', 'DATA2', 'MDATA'):
124         return 'DATA'
125     elif pidname in ('ACK', 'NACK', 'STALL', 'NYET'):
126         return 'HANDSHAKE'
127     else:
128         return 'SPECIAL'
129
130 def bitstr_to_num(bitstr):
131     if not bitstr:
132         return 0
133     l = list(bitstr)
134     l.reverse()
135     return int(''.join(l), 2)
136
137 class Decoder(srd.Decoder):
138     api_version = 1
139     id = 'usb_packet'
140     name = 'USB packet'
141     longname = 'Universal Serial Bus (LS/FS) packet'
142     desc = 'USB (low-speed and full-speed) packet protocol.'
143     license = 'gplv2+'
144     inputs = ['usb_signalling']
145     outputs = ['usb_packet']
146     probes = []
147     optional_probes = []
148     options = {
149         'signalling': ['Signalling', 'full-speed'],
150     }
151     annotations = [
152         ['text', 'Human-readable text']
153     ]
154
155     def __init__(self):
156         self.samplenum = 0
157         self.bits = []
158         self.packet = []
159         self.packet_summary = ''
160         self.ss = self.es = None
161         self.ss_packet = self.es_packet = None
162         self.state = 'WAIT FOR SOP'
163
164     def putpb(self, data):
165         self.put(self.ss, self.es, self.out_python, data)
166
167     def putb(self, data):
168         self.put(self.ss, self.es, self.out_ann, data)
169
170     def putpp(self, data):
171         self.put(self.ss_packet, self.es_packet, self.out_python, data)
172
173     def putp(self, data):
174         self.put(self.ss_packet, self.es_packet, self.out_ann, data)
175
176     def start(self):
177         self.out_python = self.register(srd.OUTPUT_PYTHON)
178         self.out_ann = self.register(srd.OUTPUT_ANN)
179
180     def handle_packet(self):
181         packet = ''
182         for (bit, ss, es) in self.bits:
183             packet += bit
184
185         # Bits[0:7]: SYNC
186         sync = packet[:7 + 1]
187         self.ss, self.es = self.bits[0][1], self.bits[7][2]
188         # The SYNC pattern for low-speed/full-speed is KJKJKJKK (00000001).
189         if sync != '00000001':
190             self.putpb(['SYNC ERROR', sync])
191             self.putb([0, ['SYNC ERROR: %s' % sync]])
192         else:
193             self.putpb(['SYNC', sync])
194             self.putb([0, ['SYNC: %s' % sync]])
195         self.packet.append(sync)
196
197         # Bits[8:15]: PID
198         pid = packet[8:15 + 1]
199         pidname = pids.get(pid, (pid, ''))[0]
200         self.ss, self.es = self.bits[8][1], self.bits[15][2]
201         self.putpb(['PID', pidname])
202         self.putb([0, ['PID: %s' % pidname]])
203         self.packet.append(pid)
204         self.packet_summary += pidname
205
206         if pidname in ('OUT', 'IN', 'SOF', 'SETUP', 'PRE', 'PING'):
207             if pidname == 'SOF':
208                 # Bits[16:26]: Framenum
209                 framenum = bitstr_to_num(packet[16:26 + 1])
210                 self.ss, self.es = self.bits[16][1], self.bits[26][2]
211                 self.putpb(['FRAMENUM', framenum])
212                 self.putb([0, ['Frame: %d' % framenum]])
213                 self.packet.append(framenum)
214                 self.packet_summary += ' %d' % framenum
215             else:
216                 # Bits[16:22]: Addr
217                 addr = bitstr_to_num(packet[16:22 + 1])
218                 self.ss, self.es = self.bits[16][1], self.bits[22][2]
219                 self.putpb(['ADDR', addr])
220                 self.putb([0, ['Addr: %d' % addr]])
221                 self.packet.append(addr)
222                 self.packet_summary += ' ADDR %d' % addr
223
224                 # Bits[23:26]: EP
225                 ep = bitstr_to_num(packet[23:26 + 1])
226                 self.ss, self.es = self.bits[23][1], self.bits[26][2]
227                 self.putpb(['EP', ep])
228                 self.putb([0, ['EP: %d' % ep]])
229                 self.packet.append(ep)
230                 self.packet_summary += ' EP %d' % ep
231
232             # Bits[27:31]: CRC5
233             crc5 = bitstr_to_num(packet[27:31 + 1])
234             self.ss, self.es = self.bits[27][1], self.bits[31][2]
235             self.putpb(['CRC5', crc5])
236             self.putb([0, ['CRC5: 0x%02x' % crc5]])
237             self.packet.append(crc5)
238         elif pidname in ('DATA0', 'DATA1', 'DATA2', 'MDATA'):
239             # Bits[16:packetlen-16]: Data
240             data = packet[16:-16]
241             # TODO: len(data) must be a multiple of 8.
242             databytes = []
243             self.packet_summary += ' ['
244             for i in range(0, len(data), 8):
245                 db = bitstr_to_num(data[i:i + 8])
246                 self.ss, self.es = self.bits[16 + i][1], self.bits[23 + i][2]
247                 self.putpb(['DATABYTE', db])
248                 self.putb([0, ['Databyte: %02x' % db]])
249                 databytes.append(db)
250                 self.packet_summary += ' %02x' % db
251                 data = data[8:]
252             self.packet_summary += ' ]'
253
254             # Convenience python output (no annotation) for all bytes together.
255             self.ss, self.es = self.bits[16][1], self.bits[-16][2]
256             self.putpb(['DATABYTES', databytes])
257             self.packet.append(databytes)
258
259             # Bits[packetlen-16:packetlen]: CRC16
260             crc16 = bitstr_to_num(packet[-16:])
261             self.ss, self.es = self.bits[-16][1], self.bits[-1][2]
262             self.putpb(['CRC16', crc16])
263             self.putb([0, ['CRC16: 0x%04x' % crc16]])
264             self.packet.append(crc16)
265         elif pidname in ('ACK', 'NAK', 'STALL', 'NYET', 'ERR'):
266             pass # Nothing to do, these only have SYNC+PID+EOP fields.
267         else:
268             pass # TODO: Handle 'SPLIT' and possibly 'Reserved' packets.
269
270         # Output a (summary of) the whole packet.
271         pcategory, pname, pinfo = get_category(pidname), pidname, self.packet
272         self.putpp(['PACKET', [pcategory, pname, pinfo]])
273         self.putp([0, ['PACKET: %s' % self.packet_summary]])
274
275         self.packet, self.packet_summary = [], ''
276
277     def decode(self, ss, es, data):
278         (ptype, pdata) = data
279
280         # We only care about certain packet types for now.
281         if ptype not in ('SOP', 'BIT', 'EOP'):
282             return
283
284         # State machine.
285         if self.state == 'WAIT FOR SOP':
286             if ptype != 'SOP':
287                 return
288             self.ss_packet = ss
289             self.state = 'GET BIT'
290         elif self.state == 'GET BIT':
291             if ptype == 'BIT':
292                 self.bits.append([pdata, ss, es])
293             elif ptype == 'EOP':
294                 self.es_packet = es
295                 self.handle_packet()
296                 self.bits, self.state = [], 'WAIT FOR SOP'
297             else:
298                 pass # TODO: Error
299         else:
300             raise Exception('Invalid state: %s' % self.state)
301