Difference between revisions of "Protocol decoder HOWTO"

From sigrok
Jump to navigation Jump to search
(Updates.)
(Various updates.)
Line 43: Line 43:
   
   
  class Decoder(srd.Decoder):
  class Decoder(srd.Decoder):
     api_version = 1
     api_version = 2
     id = 'i2c'
     id = 'i2c'
     name = 'I²C'
     name = 'I²C'
Line 51: Line 51:
     inputs = ['logic']
     inputs = ['logic']
     outputs = ['i2c']
     outputs = ['i2c']
     probes = [
     channels = (
         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
     ]
     )
     optional_probes = []
     optional_probes = ()
     options = {
     options = (
         'address_format': ['Displayed slave address format', 'shifted'],
         {'id': 'address_format', 'desc': 'Displayed slave address format',
     }
            'default': 'shifted', 'values': ('shifted', 'unshifted')},
     annotations = [
     )
         ['start', 'Start condition'],
     annotations = (
         ['repeat-start', 'Repeat start condition'],
         ('start', 'Start condition'),
         ['stop', 'Stop condition'],
         ('repeat-start', 'Repeat start condition'),
         ['ack', 'ACK'],
         ('stop', 'Stop condition'),
         ['nack', 'NACK'],
         ('ack', 'ACK'),
         ['bit', 'Data/address bit'],
         ('nack', 'NACK'),
         ['address-read', 'Address read'],
         ('bit', 'Data/address bit'),
         ['address-write', 'Address write'],
         ('address-read', 'Address read'),
         ['data-read', 'Data read'],
         ('address-write', 'Address write'),
         ['data-write', 'Data write'],
         ('data-read', 'Data read'),
         ['warnings', 'Human-readable warnings'],
         ('data-write', 'Data write'),
     ]
         ('warnings', 'Human-readable warnings'),
     )
     annotation_rows = (
     annotation_rows = (
         ('bits', 'Bits', (5,)),
         ('bits', 'Bits', (5,)),
Line 91: Line 92:
     def decode(self, ss, es, data):
     def decode(self, ss, es, data):
         for self.samplenum, (scl, sda) in data:
         for self.samplenum, (scl, sda) in data:
             # ...
             # Decode the samples.
</pre>
</pre>
</small>
</small>


The recommended name for the actual decoder file is '''pd.py'''.
The recommended name for the actual decoder file is '''pd.py'''. This file contains some meta information about the decoder, and the actual code itself, mostly in the '''decode()''' method.


This file contains some meta information about the decoder, and the actual code itself, mostly in the '''decode()''' method.
If needed, large unwieldy lists or similar things can also be factored out into another *.py file (examples: [http://sigrok.org/gitweb/?p=libsigrokdecode.git;a=tree;f=decoders/midi midi], [http://sigrok.org/gitweb/?p=libsigrokdecode.git;a=tree;f=decoders/z80 z80]).


== Random notes, tips and tricks ==
== Random notes, tips and tricks ==


* You should only use '''raise''' in a protocol decoder to raise exceptions in cases which are a clear bug in the protocol decoder.
* You should usually only use '''raise''' in a protocol decoder to raise exceptions in cases which are a clear bug in how the protocol decoder is invoked (e.g. if no samplerate was provided for a PD which needs the samplerate, or if some of the required channels were not provided by the user, and so on).
* A simple and fast way to calculate a parity (i.e., count the number of 1 bits) over a number (0x55 in this example) is: '''<tt>ones = bin(0x55).count('1')</tt>'''.
* A simple and fast way to calculate a parity (i.e., count the number of 1 bits) over a number (0x55 in this example) is: '''<tt>ones = bin(0x55).count('1')</tt>'''.
* A simple function to convert a BCD number (max. 8 bits) to an integer is: '''<tt>def bcd2int(b): return (b & 0x0f) + ((b >> 4) * 10)</tt>'''.
* A simple function to convert a BCD number (max. 8 bits) to an integer is: '''<tt>def bcd2int(b): return (b & 0x0f) + ((b >> 4) * 10)</tt>'''.
* A nice way to construct method names according to (e.g.) protocol commands is: '''<tt>fn = getattr(self, 'handle_cmd_0x%02x' % cmd); fn(arg1, arg2, ...)</tt>'''.
* A nice way to construct method names according to (e.g.) protocol commands is: '''<tt>fn = getattr(self, 'handle_cmd_0x%02x' % cmd); fn(arg1, arg2, ...)</tt>'''.


[[Category:APIs]]
[[Category:APIs]]

Revision as of 19:50, 20 July 2014

This page serves as a quick-start guide for people who want to write their own libsigrokdecode protocol decoders (PDs).

It is not intended to replace the Protocol decoder API page, but rather to give a short overview/tutorial and some tips.

Introduction

Protocol decoders are written entirely in Python (>= 3.0).

Files

Every protocol decoder is a Python module and has its own subdirectory in libsigrokdecode's decoders directory.

This is a minimalistic example of how a protocol decoder looks like, in this case the i2c decoder (license header, comments, and some other parts omitted).

Note: Do not start new protocol decoders by copying code from here. Instead, it's recommended to select an already existing decoder in the source code which is similar to the one you plan to write, and copy that as a starting point.

__init__.py

 '''
 I²C (Inter-Integrated Circuit) is a bidirectional, multi-master
 bus using two signals (SCL = serial clock line, SDA = serial data line).

 <Insert notes and hints for the user here>
 '''
 
 from .pd import *

This is a standard Python file, required in every Python module. It contains a module-level docstring, which is accessible by frontends via the libsigrokdecode API. It should contain a (very) short description of what the protocol (in this case I²C) is about, and some notes and hints for the user of this protocol decoder (which can be shown in GUIs when the user selects/browses different PDs).

This docstring should not contain the full, extensive protocol description. Instead, the per-PD wiki page should be used for protocol description, photos of devices or photos of example acquisition setups, and so on. Each decoder has one unique wiki page at the URL http://sigrok.org/wiki/Protocol_decoder:<pd>, where <pd> is the Python module name of the decoder (i2c in this case). Some examples for such per-PD wiki pages: UART, PAN1321, MX25Lxx05D, DCF77.

The "from .pd import *" line will make sure the code from pd.py gets properly imported when this module is used.

pd.py

 import sigrokdecode as srd
 
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'i2c'
     name = 'I²C'
     longname = 'Inter-Integrated Circuit'
     desc = 'Two-wire, multi-master, serial bus.'
     license = 'gplv2+'
     inputs = ['logic']
     outputs = ['i2c']
     channels = (
         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
     )
     optional_probes = ()
     options = (
         {'id': 'address_format', 'desc': 'Displayed slave address format',
            'default': 'shifted', 'values': ('shifted', 'unshifted')},
     )
     annotations = (
         ('start', 'Start condition'),
         ('repeat-start', 'Repeat start condition'),
         ('stop', 'Stop condition'),
         ('ack', 'ACK'),
         ('nack', 'NACK'),
         ('bit', 'Data/address bit'),
         ('address-read', 'Address read'),
         ('address-write', 'Address write'),
         ('data-read', 'Data read'),
         ('data-write', 'Data write'),
         ('warnings', 'Human-readable warnings'),
     )
     annotation_rows = (
         ('bits', 'Bits', (5,)),
         ('addr-data', 'Address/Data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
         ('warnings', 'Warnings', (10,)),
     )
 
     def __init__(self, **kwargs):
         self.state = 'FIND START'
         # And various other variable initializations...
 
     def metadata(self, key, value):
         if key == srd.SRD_CONF_SAMPLERATE:
             self.samplerate = value
 
     def start(self):
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def decode(self, ss, es, data):
         for self.samplenum, (scl, sda) in data:
             # Decode the samples.

The recommended name for the actual decoder file is pd.py. This file contains some meta information about the decoder, and the actual code itself, mostly in the decode() method.

If needed, large unwieldy lists or similar things can also be factored out into another *.py file (examples: midi, z80).

Random notes, tips and tricks

  • You should usually only use raise in a protocol decoder to raise exceptions in cases which are a clear bug in how the protocol decoder is invoked (e.g. if no samplerate was provided for a PD which needs the samplerate, or if some of the required channels were not provided by the user, and so on).
  • A simple and fast way to calculate a parity (i.e., count the number of 1 bits) over a number (0x55 in this example) is: ones = bin(0x55).count('1').
  • A simple function to convert a BCD number (max. 8 bits) to an integer is: def bcd2int(b): return (b & 0x0f) + ((b >> 4) * 10).
  • A nice way to construct method names according to (e.g.) protocol commands is: fn = getattr(self, 'handle_cmd_0x%02x' % cmd); fn(arg1, arg2, ...).