2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2016 Vladimir Ermakov <vooon341@gmail.com>
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.
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.
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/>.
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
48 import sigrokdecode as srd
49 from common.srdhelper import bitpack_msb
51 class SamplerateError(Exception):
54 class DecoderError(Exception):
57 ( ANN_BIT, ANN_RESET, ANN_RGB, ) = range(3)
59 class Decoder(srd.Decoder):
62 name = 'RGB LED (WS281x)'
63 longname = 'RGB LED string decoder (WS281x)'
64 desc = 'RGB LED string protocol (WS281x).'
68 tags = ['Display', 'IC']
70 {'id': 'din', 'name': 'DIN', 'desc': 'DIN data line'},
78 ('bits', 'Bits', (ANN_BIT, ANN_RESET,)),
79 ('rgb-vals', 'RGB values', (ANN_RGB,)),
82 {'id': 'wireorder', 'desc': 'colour components order (wire)',
84 'values': ('BGR', 'BRG', 'GBR', 'GRB', 'RBG', 'RGB', 'RWBG', 'RGBW')},
85 {'id': 'textorder', 'desc': 'components output order (text)',
86 'default': 'RGB', 'values': ('wire', 'RGB[W]', 'RGB', 'RGBW', 'RGWB')},
93 self.samplerate = None
97 self.out_ann = self.register(srd.OUTPUT_ANN)
99 def metadata(self, key, value):
100 if key == srd.SRD_CONF_SAMPLERATE:
101 self.samplerate = value
103 def putg(self, ss, es, cls, text):
104 self.put(ss, es, self.out_ann, [cls, text])
106 def handle_bits(self):
107 if len(self.bits) < self.need_bits:
109 ss_packet, es_packet = self.bits[0][1], self.bits[-1][2]
110 r, g, b, w = 0, 0, 0, None
112 for i, c in enumerate(self.wireformat):
113 first_idx, after_idx = 8 * i, 8 * i + 8
114 comp_bits = self.bits[first_idx:after_idx]
115 comp_ss, comp_es = comp_bits[0][1], comp_bits[-1][2]
116 comp_value = bitpack_msb(comp_bits, 0)
117 comp_item = (comp_ss, comp_es, comp_value)
118 comps.append(comp_item)
121 elif c.lower() == 'g':
123 elif c.lower() == 'b':
125 elif c.lower() == 'w':
127 wt = '' if w is None else '{:02x}'.format(w)
128 if self.textformat == 'wire':
129 rgb_text = ['{:02x}'.format(c[-1]) for c in comps]
130 rgb_text = '#' + ''.join(rgb_text)
132 rgb_text = self.textformat.format(r = r, g = g, b = b, w = w, wt = wt)
134 self.putg(ss_packet, es_packet, ANN_RGB, [rgb_text])
137 def handle_bit(self, ss, es, value, ann_late = False):
139 text = ['{:d}'.format(value)]
140 self.putg(ss, es, ANN_BIT, text)
141 item = (value, ss, es)
142 self.bits.append(item)
145 text = ['{:d}'.format(value)]
146 self.putg(ss, es, ANN_BIT, text)
149 if not self.samplerate:
150 raise SamplerateError('Cannot decode without samplerate.')
152 # Preprocess options here, to simplify logic which executes
153 # much later in loops while settings have the same values.
154 wireorder = self.options['wireorder'].lower()
155 self.wireformat = [c for c in wireorder if c in 'rgbw']
156 self.need_bits = len(self.wireformat) * 8
157 textorder = self.options['textorder'].lower()
158 if textorder == 'wire':
159 self.textformat = 'wire'
160 elif textorder == 'rgb[w]':
161 self.textformat = '#{r:02x}{g:02x}{b:02x}{wt:s}'
164 # "Obvious" permutations of R/G/B.
165 'bgr': '#{b:02x}{g:02x}{r:02x}',
166 'brg': '#{b:02x}{r:02x}{g:02x}',
167 'gbr': '#{g:02x}{b:02x}{r:02x}',
168 'grb': '#{g:02x}{r:02x}{b:02x}',
169 'rbg': '#{r:02x}{b:02x}{g:02x}',
170 'rgb': '#{r:02x}{g:02x}{b:02x}',
171 # RGB plus White. Only one of them useful?
172 'rgbw': '#{r:02x}{g:02x}{b:02x}{w:02x}',
173 # Weird RGBW permutation for compatibility to test case.
174 # Neither used RGBW nor the 'wire' order. Obsolete now?
175 'rgwb': '#{r:02x}{g:02x}{w:02x}{b:02x}',
176 }.get(textorder, None)
177 if self.textformat is None:
178 raise DecoderError('Unsupported text output format.')
180 # Either check for edges which communicate bit values, or for
181 # long periods of idle level which represent a reset pulse.
182 # Track the left-most, right-most, and inner edge positions of
183 # a bit. The positive period's width determines the bit's value.
184 # Initially synchronize to the input stream by searching for a
185 # low period, which preceeds a data bit or starts a reset pulse.
186 # Don't annotate the very first reset pulse, but process it. We
187 # may not see the right-most edge of a data bit when reset is
188 # adjacent to that bit time.
189 cond_bit_starts = {0: 'r'}
190 cond_inbit_edge = {0: 'f'}
191 samples_625ns = int(self.samplerate * 625e-9)
192 samples_50us = round(self.samplerate * 50e-6)
193 cond_reset_pulse = {'skip': samples_50us + 1}
194 conds = [cond_bit_starts, cond_inbit_edge, cond_reset_pulse]
195 ss_bit, inv_bit, es_bit = None, None, None
196 pin, = self.wait({0: 'l'})
197 inv_bit = self.samplenum
200 pin, = self.wait(conds)
202 # Check RESET condition. Manufacturers may disagree on the
203 # minimal pulse width. 50us are recommended in datasheets,
204 # experiments suggest the limit is around 10us.
205 # When the RESET pulse is adjacent to the low phase of the
206 # last bit time, we have no appropriate condition for the
207 # bit time's end location. That's why this BIT's annotation
208 # is shorter (only spans the high phase), and the RESET
209 # annotation immediately follows (spans from the falling edge
210 # to the end of the minimum RESET pulse width).
211 if check_reset and self.matched[2]:
213 ss_rst, es_rst = inv_bit, self.samplenum
215 if ss_bit and inv_bit and es_bit:
216 # Decode last bit value. Use the last processed bit's
217 # width for comparison when available. Fallback to an
218 # arbitrary threshold otherwise (which can result in
219 # false detection of value 1 for those captures where
220 # high and low pulses are of similar width).
221 duty = inv_bit - ss_bit
222 thres = samples_625ns
224 period = self.bits[-1][2] - self.bits[-1][1]
226 bit_value = 1 if duty >= thres else 0
227 self.handle_bit(ss_bit, inv_bit, bit_value, True)
229 if ss_rst and es_rst:
230 text = ['RESET', 'RST', 'R']
231 self.putg(ss_rst, es_rst, ANN_RESET, text)
235 ss_bit, inv_bit, es_bit = None, None, None
237 # Rising edge starts a bit time. Falling edge ends its high
238 # period. Get the previous bit's duty cycle and thus its
239 # bit value when the next bit starts.
240 if self.matched[0]: # and pin:
242 if ss_bit and inv_bit:
243 # Got a previous bit? Handle it.
244 es_bit = self.samplenum
245 period = es_bit - ss_bit
246 duty = inv_bit - ss_bit
247 # Ideal duty for T0H: 33%, T1H: 66%.
248 bit_value = 1 if (duty / period) > 0.5 else 0
249 self.handle_bit(ss_bit, es_bit, bit_value)
250 ss_bit, inv_bit, es_bit = self.samplenum, None, None
251 if self.matched[1]: # and not pin:
253 inv_bit = self.samplenum