Change PD options to be a tuple of dictionaries.
[libsigrokdecode.git] / decoders / usb_signalling / pd.py
index 4bf74b6ddaab6b93b9f4dec619da2de35a85063b..6f3ceffca75e771f22653b095bff6eaf74b877e1 100644 (file)
 ## 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 = {
     'low-speed': {
@@ -61,100 +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
+        self.consecutive_ones = 0
+        self.state = 'IDLE'
 
-    def start(self, metadata):
-        self.out_proto = self.add(srd.OUTPUT_PROTO, 'usb_signalling')
-        self.out_ann = self.add(srd.OUTPUT_ANN, 'usb_signalling')
-        self.bitrate = bitrates[self.options['signalling']]
-        self.bitwidth = float(metadata['samplerate']) / float(self.bitrate)
+    def start(self):
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+        self.out_ann = self.register(srd.OUTPUT_ANN)
 
-    def report(self):
-        pass
+    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 putp(self, data):
-        self.put(self.samplenum, self.samplenum, self.out_proto, data)
+    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
-
-            sym = symbols[self.options['signalling']][dp, dm]
-
-            self.putx([0, [sym]])
-            self.putp(['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.putx([0, [''.join(self.syms)]])
-            ##     self.syms = []
-            # continue
-
-            # How many bits since the last transition?
-            if self.packet != '' or self.sym != 'J':
-                bitcount = int((self.scount - 1) / self.bitwidth)
+            # 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.putx([0, [packet_decode(self.packet), self.packet]])
-                    if self.packet != '': # FIXME?
-                        self.putx([0, ['PACKET: %s' % self.packet]])
-                        self.putp(['PACKET', self.packet])
-                else:
-                    # Longer than EOP, assume reset.
-                    self.putx([0, ['RESET']])
-                    self.putp(['RESET', None])
-                # self.putx([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.putx([0, ['BIT STUFF ERROR']])
-                self.putp(['BIT STUFF ERROR', None])
-
-            self.scount = 0
-            self.sym = sym
+                raise Exception('Invalid state: %s' % self.state)