]> sigrok.org Git - libsigrokdecode.git/blob - decoders/rgb_led_ws281x/pd.py
avr_isp: Add more parts
[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 # Implementor's notes on the wire format:
21 # - World Semi vendor, (Adafruit copy of the) datasheet
22 #   https://cdn-shop.adafruit.com/datasheets/WS2812.pdf
23 # - reset pulse is 50us (or more) of low pin level
24 # - 24bits per WS281x item, 3x 8bits, MSB first, GRB sequence,
25 #   cascaded WS281x items, all "excess bits" are passed through
26 # - bit time starts with high period, continues with low period,
27 #   high to low periods' ratio determines bit value, datasheet
28 #   mentions 0.35us/0.8us for value 0, 0.7us/0.6us for value 1
29 #   (huge 150ns tolerances, un-even 0/1 value length, hmm)
30 # - experience suggests the timing "is variable", rough estimation
31 #   often is good enough, microcontroller firmware got away with
32 #   four quanta per bit time, or even with three quanta (30%/60%),
33 #   Adafruit learn article suggests 1.2us total and 0.4/0.8 or
34 #   0.8/0.4 high/low parts, four quanta are easier to handle when
35 #   the bit stream is sent via SPI to avoid MCU bit banging and its
36 #   inaccurate timing (when interrupts are used in the firmware)
37 # - RGBW datasheet (Adafruit copy) for SK6812
38 #   https://cdn-shop.adafruit.com/product-files/2757/p2757_SK6812RGBW_REV01.pdf
39 #   also 1.2us total, shared across 0.3/0.9 for 0, 0.6/0.6 for 1,
40 #   80us reset pulse, R8/G8/B8/W8 format per 32bits
41 # - WS2815, RGB LED, uses GRB wire format, 280us RESET pulse width
42 # - more vendors and models available and in popular use,
43 #   suggests "one third" or "two thirds" ratio would be most robust,
44 #   sample "a little before" the bit half? reset pulse width may need
45 #   to become an option? matrices and/or fast refresh environments
46 #   may want to experiment with back to back pixel streams
47
48 import sigrokdecode as srd
49 from common.srdhelper import bitpack_msb
50
51 class SamplerateError(Exception):
52     pass
53
54 class DecoderError(Exception):
55     pass
56
57 (
58     ANN_BIT, ANN_RESET, ANN_RGB,
59     ANN_COMP_R, ANN_COMP_G, ANN_COMP_B, ANN_COMP_W,
60 ) = range(7)
61
62 class Decoder(srd.Decoder):
63     api_version = 3
64     id = 'rgb_led_ws281x'
65     name = 'RGB LED (WS281x)'
66     longname = 'RGB LED string decoder (WS281x)'
67     desc = 'RGB LED string protocol (WS281x).'
68     license = 'gplv3+'
69     inputs = ['logic']
70     outputs = []
71     tags = ['Display', 'IC']
72     channels = (
73         {'id': 'din', 'name': 'DIN', 'desc': 'DIN data line'},
74     )
75     annotations = (
76         ('bit', 'Bit'),
77         ('reset', 'RESET'),
78         ('rgb', 'RGB'),
79         ('r', 'R'),
80         ('g', 'G'),
81         ('b', 'B'),
82         ('w', 'W'),
83     )
84     annotation_rows = (
85         ('bits', 'Bits', (ANN_BIT, ANN_RESET,)),
86         ('rgb-comps', 'RGB components', (ANN_COMP_R, ANN_COMP_G, ANN_COMP_B, ANN_COMP_W,)),
87         ('rgb-vals', 'RGB values', (ANN_RGB,)),
88     )
89     options = (
90         {'id': 'wireorder', 'desc': 'colour components order (wire)',
91          'default': 'GRB',
92          'values': ('BGR', 'BRG', 'GBR', 'GRB', 'RBG', 'RGB', 'RWBG', 'RGBW')},
93         {'id': 'textorder', 'desc': 'components output order (text)',
94          'default': 'RGB[W]', 'values': ('wire', 'RGB[W]', 'RGB', 'RGBW', 'RGWB')},
95     )
96
97     def __init__(self):
98         self.reset()
99
100     def reset(self):
101         self.samplerate = None
102         self.bits = []
103
104     def start(self):
105         self.out_ann = self.register(srd.OUTPUT_ANN)
106
107     def metadata(self, key, value):
108         if key == srd.SRD_CONF_SAMPLERATE:
109             self.samplerate = value
110
111     def putg(self, ss, es, cls, text):
112         self.put(ss, es, self.out_ann, [cls, text])
113
114     def handle_bits(self):
115         if len(self.bits) < self.need_bits:
116             return
117         ss_packet, es_packet = self.bits[0][1], self.bits[-1][2]
118         r, g, b, w = 0, 0, 0, None
119         comps = []
120         for i, c in enumerate(self.wireformat):
121             first_idx, after_idx = 8 * i, 8 * i + 8
122             comp_bits = self.bits[first_idx:after_idx]
123             comp_ss, comp_es = comp_bits[0][1], comp_bits[-1][2]
124             comp_value = bitpack_msb(comp_bits, 0)
125             comp_text = '{:02x}'.format(comp_value)
126             comp_ann = {
127                     'r': ANN_COMP_R, 'g': ANN_COMP_G,
128                     'b': ANN_COMP_B, 'w': ANN_COMP_W,
129             }.get(c.lower(), None)
130             comp_item = (comp_ss, comp_es, comp_ann, comp_value, comp_text)
131             comps.append(comp_item)
132             if c.lower() == 'r':
133                 r = comp_value
134             elif c.lower() == 'g':
135                 g = comp_value
136             elif c.lower() == 'b':
137                 b = comp_value
138             elif c.lower() == 'w':
139                 w = comp_value
140         wt = '' if w is None else '{:02x}'.format(w)
141         if self.textformat == 'wire':
142             rgb_text = '#' + ''.join([c[-1] for c in comps])
143         else:
144             rgb_text = self.textformat.format(r = r, g = g, b = b, w = w, wt = wt)
145         for ss_comp, es_comp, cls_comp, value_comp, text_comp in comps:
146             self.putg(ss_comp, es_comp, cls_comp, [text_comp])
147         if rgb_text:
148             self.putg(ss_packet, es_packet, ANN_RGB, [rgb_text])
149         self.bits.clear()
150
151     def handle_bit(self, ss, es, value, ann_late = False):
152         if not ann_late:
153             text = ['{:d}'.format(value)]
154             self.putg(ss, es, ANN_BIT, text)
155         item = (value, ss, es)
156         self.bits.append(item)
157         self.handle_bits()
158         if ann_late:
159             text = ['{:d}'.format(value)]
160             self.putg(ss, es, ANN_BIT, text)
161
162     def decode(self):
163         if not self.samplerate:
164             raise SamplerateError('Cannot decode without samplerate.')
165
166         # Preprocess options here, to simplify logic which executes
167         # much later in loops while settings have the same values.
168         wireorder = self.options['wireorder'].lower()
169         self.wireformat = [c for c in wireorder if c in 'rgbw']
170         self.need_bits = len(self.wireformat) * 8
171         textorder = self.options['textorder'].lower()
172         if textorder == 'wire':
173             self.textformat = 'wire'
174         elif textorder == 'rgb[w]':
175             self.textformat = '#{r:02x}{g:02x}{b:02x}{wt:s}'
176         else:
177             self.textformat = {
178                 # "Obvious" permutations of R/G/B.
179                 'bgr': '#{b:02x}{g:02x}{r:02x}',
180                 'brg': '#{b:02x}{r:02x}{g:02x}',
181                 'gbr': '#{g:02x}{b:02x}{r:02x}',
182                 'grb': '#{g:02x}{r:02x}{b:02x}',
183                 'rbg': '#{r:02x}{b:02x}{g:02x}',
184                 'rgb': '#{r:02x}{g:02x}{b:02x}',
185                 # RGB plus White. Only one of them useful?
186                 'rgbw': '#{r:02x}{g:02x}{b:02x}{w:02x}',
187                 # Weird RGBW permutation for compatibility to test case.
188                 # Neither used RGBW nor the 'wire' order. Obsolete now?
189                 'rgwb': '#{r:02x}{g:02x}{w:02x}{b:02x}',
190             }.get(textorder, None)
191             if self.textformat is None:
192                 raise DecoderError('Unsupported text output format.')
193
194         # Either check for edges which communicate bit values, or for
195         # long periods of idle level which represent a reset pulse.
196         # Track the left-most, right-most, and inner edge positions of
197         # a bit. The positive period's width determines the bit's value.
198         # Initially synchronize to the input stream by searching for a
199         # low period, which preceeds a data bit or starts a reset pulse.
200         # Don't annotate the very first reset pulse, but process it. We
201         # may not see the right-most edge of a data bit when reset is
202         # adjacent to that bit time.
203         cond_bit_starts = {0: 'r'}
204         cond_inbit_edge = {0: 'f'}
205         samples_625ns = int(self.samplerate * 625e-9)
206         samples_50us = round(self.samplerate * 50e-6)
207         cond_reset_pulse = {'skip': samples_50us + 1}
208         conds = [cond_bit_starts, cond_inbit_edge, cond_reset_pulse]
209         ss_bit, inv_bit, es_bit = None, None, None
210         pin, = self.wait({0: 'l'})
211         inv_bit = self.samplenum
212         check_reset = False
213         while True:
214             pin, = self.wait(conds)
215
216             # Check RESET condition. Manufacturers may disagree on the
217             # minimal pulse width. 50us are recommended in datasheets,
218             # experiments suggest the limit is around 10us.
219             # When the RESET pulse is adjacent to the low phase of the
220             # last bit time, we have no appropriate condition for the
221             # bit time's end location. That's why this BIT's annotation
222             # is shorter (only spans the high phase), and the RESET
223             # annotation immediately follows (spans from the falling edge
224             # to the end of the minimum RESET pulse width).
225             if check_reset and self.matched[2]:
226                 es_bit = inv_bit
227                 ss_rst, es_rst = inv_bit, self.samplenum
228
229                 if ss_bit and inv_bit and es_bit:
230                     # Decode last bit value. Use the last processed bit's
231                     # width for comparison when available. Fallback to an
232                     # arbitrary threshold otherwise (which can result in
233                     # false detection of value 1 for those captures where
234                     # high and low pulses are of similar width).
235                     duty = inv_bit - ss_bit
236                     thres = samples_625ns
237                     if self.bits:
238                         period = self.bits[-1][2] - self.bits[-1][1]
239                         thres = period * 0.5
240                     bit_value = 1 if duty >= thres else 0
241                     self.handle_bit(ss_bit, inv_bit, bit_value, True)
242
243                 if ss_rst and es_rst:
244                     text = ['RESET', 'RST', 'R']
245                     self.putg(ss_rst, es_rst, ANN_RESET, text)
246                 check_reset = False
247
248                 self.bits.clear()
249                 ss_bit, inv_bit, es_bit = None, None, None
250
251             # Rising edge starts a bit time. Falling edge ends its high
252             # period. Get the previous bit's duty cycle and thus its
253             # bit value when the next bit starts.
254             if self.matched[0]: # and pin:
255                 check_reset = False
256                 if ss_bit and inv_bit:
257                     # Got a previous bit? Handle it.
258                     es_bit = self.samplenum
259                     period = es_bit - ss_bit
260                     duty = inv_bit - ss_bit
261                     # Ideal duty for T0H: 33%, T1H: 66%.
262                     bit_value = 1 if (duty / period) > 0.5 else 0
263                     self.handle_bit(ss_bit, es_bit, bit_value)
264                 ss_bit, inv_bit, es_bit = self.samplenum, None, None
265             if self.matched[1]: # and not pin:
266                 check_reset = True
267                 inv_bit = self.samplenum