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 import sigrokdecode as srd
21 from functools import reduce
23 class SamplerateError(Exception):
26 class Decoder(srd.Decoder):
29 name = 'RGB LED (WS281x)'
30 longname = 'RGB LED string decoder (WS281x)'
31 desc = 'RGB LED string protocol (WS281x).'
34 outputs = ['rgb_led_ws281x']
36 {'id': 'din', 'name': 'DIN', 'desc': 'DIN data line'},
44 ('bit', 'Bits', (0, 1)),
49 self.samplerate = None
58 self.out_ann = self.register(srd.OUTPUT_ANN)
60 def metadata(self, key, value):
61 if key == srd.SRD_CONF_SAMPLERATE:
62 self.samplerate = value
64 def handle_bits(self, samplenum):
65 if len(self.bits) == 24:
66 grb = reduce(lambda a, b: (a << 1) | b, self.bits)
67 rgb = (grb & 0xff0000) >> 8 | (grb & 0x00ff00) << 8 | (grb & 0x0000ff)
68 self.put(self.ss_packet, samplenum, self.out_ann,
73 def decode(self, ss, es, data):
74 if not self.samplerate:
75 raise SamplerateError('Cannot decode without samplerate.')
77 for (self.samplenum, (pin, )) in data:
78 if self.oldpin is None:
82 # Check RESET condition (manufacturer recommends 50 usec minimal,
83 # but real minimum is ~10 usec).
84 if not self.inreset and not pin and self.es is not None and \
85 (self.samplenum - self.es) / self.samplerate > 50e-6:
87 # Decode last bit value.
88 tH = (self.es - self.ss) / self.samplerate
89 bit_ = True if tH >= 625e-9 else False
91 self.bits.append(bit_)
92 self.handle_bits(self.es)
94 self.put(self.ss, self.es, self.out_ann, [0, ['%d' % bit_]])
95 self.put(self.es, self.samplenum, self.out_ann,
96 [1, ['RESET', 'RST', 'R']])
100 self.ss_packet = None
103 if not self.oldpin and pin:
105 if self.ss and self.es:
106 period = self.samplenum - self.ss
107 duty = self.es - self.ss
108 # Ideal duty for T0H: 33%, T1H: 66%.
109 bit_ = (duty / period) > 0.5
111 self.put(self.ss, self.samplenum, self.out_ann,
114 self.bits.append(bit_)
115 self.handle_bits(self.samplenum)
117 if self.ss_packet is None:
118 self.ss_packet = self.samplenum
120 self.ss = self.samplenum
122 elif self.oldpin and not pin:
125 self.es = self.samplenum