]> sigrok.org Git - libsigrokdecode.git/blob - decoders/rgb_led_ws281x/pd.py
7c8ead4375b8ffc7979937cd7e41a338451ff4a9
[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 class DecoderError(Exception):
27     pass
28
29 ( ANN_BIT, ANN_RESET, ANN_RGB, ) = range(3)
30
31 class Decoder(srd.Decoder):
32     api_version = 3
33     id = 'rgb_led_ws281x'
34     name = 'RGB LED (WS281x)'
35     longname = 'RGB LED string decoder (WS281x)'
36     desc = 'RGB LED string protocol (WS281x).'
37     license = 'gplv3+'
38     inputs = ['logic']
39     outputs = []
40     tags = ['Display', 'IC']
41     channels = (
42         {'id': 'din', 'name': 'DIN', 'desc': 'DIN data line'},
43     )
44     annotations = (
45         ('bit', 'Bit'),
46         ('reset', 'RESET'),
47         ('rgb', 'RGB'),
48     )
49     annotation_rows = (
50         ('bits', 'Bits', (ANN_BIT, ANN_RESET,)),
51         ('rgb-vals', 'RGB values', (ANN_RGB,)),
52     )
53     options = (
54         {'id': 'wireorder', 'desc': 'colour components order (wire)',
55          'default': 'GRB',
56          'values': ('BGR', 'BRG', 'GBR', 'GRB', 'RBG', 'RGB', 'RWBG', 'RGBW')},
57         {'id': 'textorder', 'desc': 'components output order (text)',
58          'default': 'RGB', 'values': ('wire', 'RGB[W]', 'RGB', 'RGBW', 'RGWB')},
59     )
60
61     def __init__(self):
62         self.reset()
63
64     def reset(self):
65         self.samplerate = None
66         self.bits = []
67
68     def start(self):
69         self.out_ann = self.register(srd.OUTPUT_ANN)
70
71     def metadata(self, key, value):
72         if key == srd.SRD_CONF_SAMPLERATE:
73             self.samplerate = value
74
75     def putg(self, ss, es, cls, text):
76         self.put(ss, es, self.out_ann, [cls, text])
77
78     def handle_bits(self):
79         if len(self.bits) < self.need_bits:
80             return
81         ss_packet, es_packet = self.bits[0][1], self.bits[-1][2]
82         r, g, b, w = 0, 0, 0, None
83         comps = []
84         for i, c in enumerate(self.wireformat):
85             first_idx, after_idx = 8 * i, 8 * i + 8
86             comp_bits = self.bits[first_idx:after_idx]
87             comp_ss, comp_es = comp_bits[0][1], comp_bits[-1][2]
88             comp_value = bitpack_msb(comp_bits, 0)
89             comp_item = (comp_ss, comp_es, comp_value)
90             comps.append(comp_item)
91             if c.lower() == 'r':
92                 r = comp_value
93             elif c.lower() == 'g':
94                 g = comp_value
95             elif c.lower() == 'b':
96                 b = comp_value
97             elif c.lower() == 'w':
98                 w = comp_value
99         wt = '' if w is None else '{:02x}'.format(w)
100         if self.textformat == 'wire':
101             rgb_text = ['{:02x}'.format(c[-1]) for c in comps]
102             rgb_text = '#' + ''.join(rgb_text)
103         else:
104             rgb_text = self.textformat.format(r = r, g = g, b = b, w = w, wt = wt)
105         if rgb_text:
106             self.putg(ss_packet, es_packet, ANN_RGB, [rgb_text])
107         self.bits.clear()
108
109     def handle_bit(self, ss, es, value, ann_late = False):
110         if not ann_late:
111             text = ['{:d}'.format(value)]
112             self.putg(ss, es, ANN_BIT, text)
113         item = (value, ss, es)
114         self.bits.append(item)
115         self.handle_bits()
116         if ann_late:
117             text = ['{:d}'.format(value)]
118             self.putg(ss, es, ANN_BIT, text)
119
120     def decode(self):
121         if not self.samplerate:
122             raise SamplerateError('Cannot decode without samplerate.')
123
124         # Preprocess options here, to simplify logic which executes
125         # much later in loops while settings have the same values.
126         wireorder = self.options['wireorder'].lower()
127         self.wireformat = [c for c in wireorder if c in 'rgbw']
128         self.need_bits = len(self.wireformat) * 8
129         textorder = self.options['textorder'].lower()
130         if textorder == 'wire':
131             self.textformat = 'wire'
132         elif textorder == 'rgb[w]':
133             self.textformat = '#{r:02x}{g:02x}{b:02x}{wt:s}'
134         else:
135             self.textformat = {
136                 # "Obvious" permutations of R/G/B.
137                 'bgr': '#{b:02x}{g:02x}{r:02x}',
138                 'brg': '#{b:02x}{r:02x}{g:02x}',
139                 'gbr': '#{g:02x}{b:02x}{r:02x}',
140                 'grb': '#{g:02x}{r:02x}{b:02x}',
141                 'rbg': '#{r:02x}{b:02x}{g:02x}',
142                 'rgb': '#{r:02x}{g:02x}{b:02x}',
143                 # RGB plus White. Only one of them useful?
144                 'rgbw': '#{r:02x}{g:02x}{b:02x}{w:02x}',
145                 # Weird RGBW permutation for compatibility to test case.
146                 # Neither used RGBW nor the 'wire' order. Obsolete now?
147                 'rgwb': '#{r:02x}{g:02x}{w:02x}{b:02x}',
148             }.get(textorder, None)
149             if self.textformat is None:
150                 raise DecoderError('Unsupported text output format.')
151
152         # Either check for edges which communicate bit values, or for
153         # long periods of idle level which represent a reset pulse.
154         # Track the left-most, right-most, and inner edge positions of
155         # a bit. The positive period's width determines the bit's value.
156         # Initially synchronize to the input stream by searching for a
157         # low period, which preceeds a data bit or starts a reset pulse.
158         # Don't annotate the very first reset pulse, but process it. We
159         # may not see the right-most edge of a data bit when reset is
160         # adjacent to that bit time.
161         cond_bit_starts = {0: 'r'}
162         cond_inbit_edge = {0: 'f'}
163         samples_625ns = int(self.samplerate * 625e-9)
164         samples_50us = round(self.samplerate * 50e-6)
165         cond_reset_pulse = {'skip': samples_50us + 1}
166         conds = [cond_bit_starts, cond_inbit_edge, cond_reset_pulse]
167         ss_bit, inv_bit, es_bit = None, None, None
168         pin, = self.wait({0: 'l'})
169         inv_bit = self.samplenum
170         check_reset = False
171         while True:
172             pin, = self.wait(conds)
173
174             # Check RESET condition. Manufacturers may disagree on the
175             # minimal pulse width. 50us are recommended in datasheets,
176             # experiments suggest the limit is around 10us.
177             # When the RESET pulse is adjacent to the low phase of the
178             # last bit time, we have no appropriate condition for the
179             # bit time's end location. That's why this BIT's annotation
180             # is shorter (only spans the high phase), and the RESET
181             # annotation immediately follows (spans from the falling edge
182             # to the end of the minimum RESET pulse width).
183             if check_reset and self.matched[2]:
184                 es_bit = inv_bit
185                 ss_rst, es_rst = inv_bit, self.samplenum
186
187                 if ss_bit and inv_bit and es_bit:
188                     # Decode last bit value. Use the last processed bit's
189                     # width for comparison when available. Fallback to an
190                     # arbitrary threshold otherwise (which can result in
191                     # false detection of value 1 for those captures where
192                     # high and low pulses are of similar width).
193                     duty = inv_bit - ss_bit
194                     thres = samples_625ns
195                     if self.bits:
196                         period = self.bits[-1][2] - self.bits[-1][1]
197                         thres = period * 0.5
198                     bit_value = 1 if duty >= thres else 0
199                     self.handle_bit(ss_bit, inv_bit, bit_value, True)
200
201                 if ss_rst and es_rst:
202                     text = ['RESET', 'RST', 'R']
203                     self.putg(ss_rst, es_rst, ANN_RESET, text)
204                 check_reset = False
205
206                 self.bits.clear()
207                 ss_bit, inv_bit, es_bit = None, None, None
208
209             # Rising edge starts a bit time. Falling edge ends its high
210             # period. Get the previous bit's duty cycle and thus its
211             # bit value when the next bit starts.
212             if self.matched[0]: # and pin:
213                 check_reset = False
214                 if ss_bit and inv_bit:
215                     # Got a previous bit? Handle it.
216                     es_bit = self.samplenum
217                     period = es_bit - ss_bit
218                     duty = inv_bit - ss_bit
219                     # Ideal duty for T0H: 33%, T1H: 66%.
220                     bit_value = 1 if (duty / period) > 0.5 else 0
221                     self.handle_bit(ss_bit, es_bit, bit_value)
222                 ss_bit, inv_bit, es_bit = self.samplenum, None, None
223             if self.matched[1]: # and not pin:
224                 check_reset = True
225                 inv_bit = self.samplenum