]> sigrok.org Git - libsigrokdecode.git/blame - decoders/rgb_led_ws281x/pd.py
rgb_led_ws281x: rework the .decode() main loop, improve robustness
[libsigrokdecode.git] / decoders / rgb_led_ws281x / pd.py
CommitLineData
66fc6e7c
UH
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
4539e9ca 17## along with this program; if not, see <http://www.gnu.org/licenses/>.
66fc6e7c
UH
18##
19
20import sigrokdecode as srd
6d1cde1d 21from common.srdhelper import bitpack_msb
66fc6e7c
UH
22
23class SamplerateError(Exception):
24 pass
25
0e3c3498
GS
26( ANN_BIT, ANN_RESET, ANN_RGB, ) = range(3)
27
66fc6e7c 28class Decoder(srd.Decoder):
7a85bbbe 29 api_version = 3
66fc6e7c
UH
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']
6cbba91f 36 outputs = []
2787cf2a 37 tags = ['Display', 'IC']
66fc6e7c
UH
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 = (
0e3c3498
GS
47 ('bits', 'Bits', (ANN_BIT, ANN_RESET,)),
48 ('rgb-vals', 'RGB values', (ANN_RGB,)),
66fc6e7c 49 )
47ff9910
S
50 options = (
51 {'id': 'type', 'desc': 'RGB or RGBW', 'default': 'RGB',
52 'values': ('RGB', 'RGBW')},
53 )
66fc6e7c 54
92b7b49f 55 def __init__(self):
10aeb8ea
GS
56 self.reset()
57
58 def reset(self):
66fc6e7c 59 self.samplerate = None
66fc6e7c 60 self.bits = []
66fc6e7c
UH
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
192a9e78
GS
69 def putg(self, ss, es, cls, text):
70 self.put(ss, es, self.out_ann, [cls, text])
71
6d1cde1d
GS
72 def handle_bits(self):
73 if len(self.bits) < self.need_bits:
74 return
75 grb = bitpack_msb(self.bits, 0)
47ff9910 76 if self.options['type'] == 'RGB':
6d1cde1d
GS
77 rgb = (grb & 0xff0000) >> 8 | (grb & 0x00ff00) << 8 | (grb & 0x0000ff)
78 text = '#{:06x}'.format(rgb)
47ff9910 79 else:
6d1cde1d
GS
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)
66fc6e7c 96
7a85bbbe 97 def decode(self):
66fc6e7c
UH
98 if not self.samplerate:
99 raise SamplerateError('Cannot decode without samplerate.')
6d1cde1d 100 self.need_bits = len(self.options['type']) * 8
66fc6e7c 101
5e8090d7
GS
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
7a85bbbe 121 while True:
5e8090d7
GS
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
7a85bbbe 155
6d1cde1d 156 self.bits.clear()
5e8090d7
GS
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
66fc6e7c 169 # Ideal duty for T0H: 33%, T1H: 66%.
5e8090d7
GS
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