Change PD options to be a tuple of dictionaries.
[libsigrokdecode.git] / decoders / usb_signalling / pd.py
index 3272cbf713c19abbe07cf908c1a6b706f5d86b94..6f3ceffca75e771f22653b095bff6eaf74b877e1 100644 (file)
@@ -1,8 +1,8 @@
 ##
-## This file is part of the sigrok project.
+## This file is part of the libsigrokdecode project.
 ##
 ## Copyright (C) 2011 Gareth McMullin <gareth@blacksphere.co.nz>
-## Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
+## Copyright (C) 2012-2013 Uwe Hermann <uwe@hermann-uwe.de>
 ##
 ## This program is free software; you can redistribute it and/or modify
 ## it under the terms of the GNU General Public License as published by
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-# USB signalling (low-speed and full-speed) protocol decoder
-
 import sigrokdecode as srd
 
-# Low-/full-speed symbols (used as states of our state machine, too).
+'''
+OUTPUT_PYTHON format:
+
+Packet:
+[<ptype>, <pdata>]
+
+<ptype>, <pdata>:
+ - 'SOP', None
+ - 'SYM', <sym>
+ - 'BIT', <bit>
+ - 'STUFF BIT', None
+ - 'EOP', None
+
+<sym>:
+ - 'J', 'K', 'SE0', or 'SE1'
+
+<bit>:
+ - 0 or 1
+ - Note: Symbols like SE0, SE1, and the J that's part of EOP don't yield 'BIT'.
+'''
+
+# Low-/full-speed symbols.
 # Note: Low-speed J and K are inverted compared to the full-speed J and K!
-symbols_ls = {
+symbols = {
+    'low-speed': {
         # (<dp>, <dm>): <symbol/state>
         (0, 0): 'SE0',
         (1, 0): 'K',
         (0, 1): 'J',
         (1, 1): 'SE1',
-}
-symbols_fs = {
+    },
+    'full-speed': {
         # (<dp>, <dm>): <symbol/state>
         (0, 0): 'SE0',
         (1, 0): 'J',
         (0, 1): 'K',
         (1, 1): 'SE1',
+    },
+}
+
+bitrates = {
+    'low-speed': 1500000,   # 1.5Mb/s (+/- 1.5%)
+    'full-speed': 12000000, # 12Mb/s (+/- 0.25%)
 }
 
 class Decoder(srd.Decoder):
@@ -45,7 +71,7 @@ class Decoder(srd.Decoder):
     id = 'usb_signalling'
     name = 'USB signalling'
     longname = 'Universal Serial Bus (LS/FS) signalling'
-    desc = 'USB 1.x (low-speed and full-speed) signalling protocol.'
+    desc = 'USB (low-speed and full-speed) signalling protocol.'
     license = 'gplv2+'
     inputs = ['logic']
     outputs = ['usb_signalling']
@@ -54,99 +80,154 @@ class Decoder(srd.Decoder):
         {'id': 'dm', 'name': 'D-', 'desc': 'USB D- signal'},
     ]
     optional_probes = []
-    options = {
-        'signalling': ['Signalling', 'full-speed'],
-    }
+    options = (
+        {'id': 'signalling', 'desc': 'Signalling',
+            'default': 'full-speed', 'values': ('full-speed', 'low-speed')},
+    )
     annotations = [
-        ['Text', 'Human-readable text']
+        ['sym', 'Symbol'],
+        ['sop', 'Start of packet (SOP)'],
+        ['eop', 'End of packet (EOP)'],
+        ['bit', 'Bit'],
+        ['stuffbit', 'Stuff bit'],
     ]
+    annotation_rows = (
+        ('bits', 'Bits', (1, 2, 3, 4)),
+        ('symbols', 'Symbols', (0,)),
+    )
 
     def __init__(self):
-        self.sym = 'J' # The "idle" state is J.
+        self.samplerate = None
+        self.oldsym = 'J' # The "idle" state is J.
+        self.ss_sop = None
+        self.ss_block = None
         self.samplenum = 0
-        self.scount = 0
-        self.packet = ''
         self.syms = []
+        self.bitrate = None
+        self.bitwidth = None
+        self.bitnum = 0
+        self.samplenum_target = None
         self.oldpins = None
-
-    def start(self, metadata):
-        self.samplerate = metadata['samplerate']
-        self.out_proto = self.add(srd.OUTPUT_PROTO, 'usb_signalling')
-        self.out_ann = self.add(srd.OUTPUT_ANN, 'usb_signalling')
-
-    def report(self):
-        pass
+        self.consecutive_ones = 0
+        self.state = 'IDLE'
+
+    def start(self):
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+            self.bitrate = bitrates[self.options['signalling']]
+            self.bitwidth = float(self.samplerate) / float(self.bitrate)
+            self.halfbit = int(self.bitwidth / 2)
+
+    def putpx(self, data):
+        self.put(self.samplenum, self.samplenum, self.out_python, data)
+
+    def putx(self, data):
+        self.put(self.samplenum, self.samplenum, self.out_ann, data)
+
+    def putpm(self, data):
+        s, h = self.samplenum, self.halfbit
+        self.put(self.ss_block - h, s + h, self.out_python, data)
+
+    def putm(self, data):
+        s, h = self.samplenum, self.halfbit
+        self.put(self.ss_block - h, s + h, self.out_ann, data)
+
+    def putpb(self, data):
+        s, h = self.samplenum, self.halfbit
+        self.put(s - h, s + h, self.out_python, data)
+
+    def putb(self, data):
+        s, h = self.samplenum, self.halfbit
+        self.put(s - h, s + h, self.out_ann, data)
+
+    def set_new_target_samplenum(self):
+        bitpos = self.ss_sop + (self.bitwidth / 2)
+        bitpos += self.bitnum * self.bitwidth
+        self.samplenum_target = int(bitpos)
+
+    def wait_for_sop(self, sym):
+        # Wait for a Start of Packet (SOP), i.e. a J->K symbol change.
+        if sym != 'K':
+            self.oldsym = sym
+            return
+        self.ss_sop = self.samplenum
+        self.set_new_target_samplenum()
+        self.putpx(['SOP', None])
+        self.putx([1, ['SOP']])
+        self.state = 'GET BIT'
+
+    def handle_bit(self, sym, b):
+        if self.consecutive_ones == 6 and b == '0':
+            # Stuff bit.
+            self.putpb(['STUFF BIT', None])
+            self.putb([4, ['SB: %s' % b]])
+            self.putb([0, ['%s' % sym]])
+            self.consecutive_ones = 0
+        else:
+            # Normal bit (not a stuff bit).
+            self.putpb(['BIT', b])
+            self.putb([3, ['%s' % b]])
+            self.putb([0, ['%s' % sym]])
+            if b == '1':
+                self.consecutive_ones += 1
+            else:
+                self.consecutive_ones = 0
+
+    def get_eop(self, sym):
+        # EOP: SE0 for >= 1 bittime (usually 2 bittimes), then J.
+        self.syms.append(sym)
+        self.putpb(['SYM', sym])
+        self.putb([0, ['%s' % sym]])
+        self.bitnum += 1
+        self.set_new_target_samplenum()
+        self.oldsym = sym
+        if self.syms[-2:] == ['SE0', 'J']:
+            # Got an EOP.
+            self.putpm(['EOP', None])
+            self.putm([2, ['EOP']])
+            self.bitnum, self.syms, self.state = 0, [], 'IDLE'
+            self.consecutive_ones = 0
+
+    def get_bit(self, sym):
+        if sym == 'SE0':
+            # Start of an EOP. Change state, run get_eop() for this bit.
+            self.state = 'GET EOP'
+            self.ss_block = self.samplenum
+            self.get_eop(sym)
+            return
+        self.syms.append(sym)
+        self.putpb(['SYM', sym])
+        b = '0' if self.oldsym != sym else '1'
+        self.handle_bit(sym, b)
+        self.bitnum += 1
+        self.set_new_target_samplenum()
+        self.oldsym = sym
 
     def decode(self, ss, es, data):
+        if self.samplerate is None:
+            raise Exception("Cannot decode without samplerate.")
         for (self.samplenum, pins) in data:
-
-            # Note: self.samplenum is the absolute sample number, whereas
-            # self.scount only counts the number of samples since the
-            # last change in the D+/D- lines.
-            self.scount += 1
-
-            # Ignore identical samples early on (for performance reasons).
-            if self.oldpins == pins:
-                continue
-            self.oldpins, (dp, dm) = pins, pins
-
-            if self.options['signalling'] == 'low-speed':
-                sym = symbols_ls[dp, dm]
-            elif self.options['signalling'] == 'full-speed':
-                sym = symbols_fs[dp, dm]
-
-            self.put(0, 0, self.out_ann, [0, [sym]])
-            self.put(0, 0, self.out_proto, ['SYM', sym])
-
-            # Wait for a symbol change (i.e., change in D+/D- lines).
-            if sym == self.sym:
-                continue
-
-            ## # Debug code:
-            ## self.syms.append(sym + ' ')
-            ## if len(self.syms) == 16:
-            ##     self.put(0, 0, self.out_ann, [0, [''.join(self.syms)]])
-            ##     self.syms = []
-            # continue
-
-            # How many bits since the last transition?
-            if self.packet != '' or self.sym != 'J':
-                if self.options['signalling'] == 'low-speed':
-                    bitrate = 1500000 # 1.5Mb/s (+/- 1.5%)
-                elif self.options['signalling'] == 'full-speed':
-                    bitrate = 12000000 # 12Mb/s (+/- 0.25%)
-                bitcount = int((self.scount - 1) * bitrate / self.samplerate)
+            # State machine.
+            if self.state == 'IDLE':
+                # Ignore identical samples early on (for performance reasons).
+                if self.oldpins == pins:
+                    continue
+                self.oldpins = pins
+                sym = symbols[self.options['signalling']][tuple(pins)]
+                self.wait_for_sop(sym)
+            elif self.state in ('GET BIT', 'GET EOP'):
+                # Wait until we're in the middle of the desired bit.
+                if self.samplenum < self.samplenum_target:
+                    continue
+                sym = symbols[self.options['signalling']][tuple(pins)]
+                if self.state == 'GET BIT':
+                    self.get_bit(sym)
+                elif self.state == 'GET EOP':
+                    self.get_eop(sym)
             else:
-                bitcount = 0
-
-            if self.sym == 'SE0':
-                if bitcount == 1:
-                    # End-Of-Packet (EOP)
-                    # self.put(0, 0, self.out_ann,
-                    #          [0, [packet_decode(self.packet), self.packet]])
-                    if self.packet != '': # FIXME?
-                        self.put(0, 0, self.out_ann, [0, ['PACKET: %s' % self.packet]])
-                        self.put(0, 0, self.out_proto, ['PACKET', self.packet])
-                else:
-                    # Longer than EOP, assume reset.
-                    self.put(0, 0, self.out_ann, [0, ['RESET']])
-                    self.put(0, 0, self.out_proto, ['RESET', None])
-                # self.put(0, 0, self.out_ann, [0, [self.packet]])
-                self.scount = 0
-                self.sym = sym
-                self.packet = ''
-                continue
-
-            # Add bits to the packet string.
-            self.packet += '1' * bitcount
-
-            # Handle bit stuffing.
-            if bitcount < 6 and sym != 'SE0':
-                self.packet += '0'
-            elif bitcount > 6:
-                self.put(0, 0, self.out_ann, [0, ['BIT STUFF ERROR']])
-                self.put(0, 0, self.out_proto, ['BIT STUFF ERROR', None])
-
-            self.scount = 0
-            self.sym = sym
+                raise Exception('Invalid state: %s' % self.state)