]> sigrok.org Git - libsigrokdecode.git/blob - decoders/rgb_led_ws281x/pd.py
rgb_led_ws281x: rework the .decode() main loop, improve robustness
[libsigrokdecode.git] / decoders / rgb_led_ws281x / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2016 Vladimir Ermakov <vooon341@gmail.com>
5 ##
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 3 of the License, or
9 ## (at your option) any later version.
10 ##
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.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
18 ##
19
20 import sigrokdecode as srd
21 from common.srdhelper import bitpack_msb
22
23 class SamplerateError(Exception):
24     pass
25
26 ( ANN_BIT, ANN_RESET, ANN_RGB, ) = range(3)
27
28 class Decoder(srd.Decoder):
29     api_version = 3
30     id = 'rgb_led_ws281x'
31     name = 'RGB LED (WS281x)'
32     longname = 'RGB LED string decoder (WS281x)'
33     desc = 'RGB LED string protocol (WS281x).'
34     license = 'gplv3+'
35     inputs = ['logic']
36     outputs = []
37     tags = ['Display', 'IC']
38     channels = (
39         {'id': 'din', 'name': 'DIN', 'desc': 'DIN data line'},
40     )
41     annotations = (
42         ('bit', 'Bit'),
43         ('reset', 'RESET'),
44         ('rgb', 'RGB'),
45     )
46     annotation_rows = (
47         ('bits', 'Bits', (ANN_BIT, ANN_RESET,)),
48         ('rgb-vals', 'RGB values', (ANN_RGB,)),
49     )
50     options = (
51         {'id': 'type', 'desc': 'RGB or RGBW', 'default': 'RGB',
52          'values': ('RGB', 'RGBW')},
53     )
54
55     def __init__(self):
56         self.reset()
57
58     def reset(self):
59         self.samplerate = None
60         self.bits = []
61
62     def start(self):
63         self.out_ann = self.register(srd.OUTPUT_ANN)
64
65     def metadata(self, key, value):
66         if key == srd.SRD_CONF_SAMPLERATE:
67             self.samplerate = value
68
69     def putg(self, ss, es, cls, text):
70         self.put(ss, es, self.out_ann, [cls, text])
71
72     def handle_bits(self):
73         if len(self.bits) < self.need_bits:
74             return
75         grb = bitpack_msb(self.bits, 0)
76         if self.options['type'] == 'RGB':
77             rgb = (grb & 0xff0000) >> 8 | (grb & 0x00ff00) << 8 | (grb & 0x0000ff)
78             text = '#{:06x}'.format(rgb)
79         else:
80             rgb = (grb & 0xff0000) >> 8 | (grb & 0x00ff00) << 8 | (grb & 0xff0000ff)
81             text = '#{:08x}'.format(rgb)
82         ss_packet, es_packet = self.bits[0][1], self.bits[-1][2]
83         self.putg(ss_packet, es_packet, ANN_RGB, [text])
84         self.bits.clear()
85
86     def handle_bit(self, ss, es, value, ann_late = False):
87         if not ann_late:
88             text = ['{:d}'.format(value)]
89             self.putg(ss, es, ANN_BIT, text)
90         item = (value, ss, es)
91         self.bits.append(item)
92         self.handle_bits()
93         if ann_late:
94             text = ['{:d}'.format(value)]
95             self.putg(ss, es, ANN_BIT, text)
96
97     def decode(self):
98         if not self.samplerate:
99             raise SamplerateError('Cannot decode without samplerate.')
100         self.need_bits = len(self.options['type']) * 8
101
102         # Either check for edges which communicate bit values, or for
103         # long periods of idle level which represent a reset pulse.
104         # Track the left-most, right-most, and inner edge positions of
105         # a bit. The positive period's width determines the bit's value.
106         # Initially synchronize to the input stream by searching for a
107         # low period, which preceeds a data bit or starts a reset pulse.
108         # Don't annotate the very first reset pulse, but process it. We
109         # may not see the right-most edge of a data bit when reset is
110         # adjacent to that bit time.
111         cond_bit_starts = {0: 'r'}
112         cond_inbit_edge = {0: 'f'}
113         samples_625ns = int(self.samplerate * 625e-9)
114         samples_50us = round(self.samplerate * 50e-6)
115         cond_reset_pulse = {'skip': samples_50us + 1}
116         conds = [cond_bit_starts, cond_inbit_edge, cond_reset_pulse]
117         ss_bit, inv_bit, es_bit = None, None, None
118         pin, = self.wait({0: 'l'})
119         inv_bit = self.samplenum
120         check_reset = False
121         while True:
122             pin, = self.wait(conds)
123
124             # Check RESET condition. Manufacturers may disagree on the
125             # minimal pulse width. 50us are recommended in datasheets,
126             # experiments suggest the limit is around 10us.
127             # When the RESET pulse is adjacent to the low phase of the
128             # last bit time, we have no appropriate condition for the
129             # bit time's end location. That's why this BIT's annotation
130             # is shorter (only spans the high phase), and the RESET
131             # annotation immediately follows (spans from the falling edge
132             # to the end of the minimum RESET pulse width).
133             if check_reset and self.matched[2]:
134                 es_bit = inv_bit
135                 ss_rst, es_rst = inv_bit, self.samplenum
136
137                 if ss_bit and inv_bit and es_bit:
138                     # Decode last bit value. Use the last processed bit's
139                     # width for comparison when available. Fallback to an
140                     # arbitrary threshold otherwise (which can result in
141                     # false detection of value 1 for those captures where
142                     # high and low pulses are of similar width).
143                     duty = inv_bit - ss_bit
144                     thres = samples_625ns
145                     if self.bits:
146                         period = self.bits[-1][2] - self.bits[-1][1]
147                         thres = period * 0.5
148                     bit_value = 1 if duty >= thres else 0
149                     self.handle_bit(ss_bit, inv_bit, bit_value, True)
150
151                 if ss_rst and es_rst:
152                     text = ['RESET', 'RST', 'R']
153                     self.putg(ss_rst, es_rst, ANN_RESET, text)
154                 check_reset = False
155
156                 self.bits.clear()
157                 ss_bit, inv_bit, es_bit = None, None, None
158
159             # Rising edge starts a bit time. Falling edge ends its high
160             # period. Get the previous bit's duty cycle and thus its
161             # bit value when the next bit starts.
162             if self.matched[0]: # and pin:
163                 check_reset = False
164                 if ss_bit and inv_bit:
165                     # Got a previous bit? Handle it.
166                     es_bit = self.samplenum
167                     period = es_bit - ss_bit
168                     duty = inv_bit - ss_bit
169                     # Ideal duty for T0H: 33%, T1H: 66%.
170                     bit_value = 1 if (duty / period) > 0.5 else 0
171                     self.handle_bit(ss_bit, es_bit, bit_value)
172                 ss_bit, inv_bit, es_bit = self.samplenum, None, None
173             if self.matched[1]: # and not pin:
174                 check_reset = True
175                 inv_bit = self.samplenum