2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2014 Gump Yang <gump.yang@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 2 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
23 class SamplerateError(Exception):
30 BIT, AGC, LONG_PAUSE, SHORT_PAUSE, STOP_BIT, \
31 LEADER_CODE, ADDR, ADDR_INV, CMD, CMD_INV, REPEAT_CODE, \
32 REMOTE, WARN = range(13)
34 class Decoder(srd.Decoder):
39 desc = 'NEC infrared remote control protocol.'
45 {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
48 {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
49 'values': ('active-low', 'active-high')},
50 {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
54 ('agc-pulse', 'AGC pulse'),
55 ('longpause', 'Long pause'),
56 ('shortpause', 'Short pause'),
57 ('stop-bit', 'Stop bit'),
58 ('leader-code', 'Leader code'),
60 ('addr-inv', 'Address#'),
62 ('cmd-inv', 'Command#'),
63 ('repeat-code', 'Repeat code'),
65 ('warning', 'Warning'),
68 ('bits', 'Bits', (Ann.BIT, Ann.AGC, Ann.LONG_PAUSE, Ann.SHORT_PAUSE, Ann.STOP_BIT)),
69 ('fields', 'Fields', (Ann.LEADER_CODE, Ann.ADDR, Ann.ADDR_INV, Ann.CMD, Ann.CMD_INV, Ann.REPEAT_CODE)),
70 ('remote-vals', 'Remote', (Ann.REMOTE,)),
71 ('warnings', 'Warnings', (Ann.WARN,)),
75 self.put(self.ss_start, self.samplenum, self.out_ann, data)
78 self.put(self.ss_bit, self.samplenum, self.out_ann, data)
81 name = self.state.title()
82 d = {'ADDRESS': Ann.ADDR, 'ADDRESS#': Ann.ADDR_INV,
83 'COMMAND': Ann.CMD, 'COMMAND#': Ann.CMD_INV}
84 s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'],
85 'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']}
86 self.putx([d[self.state], [
87 '{}: 0x{:02X}'.format(name, data),
88 '{}: 0x{:02X}'.format(s[self.state][0], data),
89 '{}: 0x{:02X}'.format(s[self.state][1], data),
93 def putstop(self, ss):
94 self.put(ss, ss + self.stop, self.out_ann,
95 [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
97 def putpause(self, p):
98 self.put(self.ss_start, self.ss_other_edge, self.out_ann,
99 [Ann.AGC, ['AGC pulse', 'AGC', 'A']])
100 idx = Ann.LONG_PAUSE if p == 'Long' else Ann.SHORT_PAUSE
101 self.put(self.ss_other_edge, self.samplenum, self.out_ann, [idx, [
102 '{} pause'.format(p),
103 '{}-pause'.format(p[0]),
109 dev = address.get(self.addr, 'Unknown device')
110 buttons = command.get(self.addr, {})
111 btn = buttons.get(self.cmd, ['Unknown', 'Unk'])
112 self.put(self.ss_remote, self.ss_bit + self.stop, self.out_ann, [Ann.REMOTE, [
113 '{}: {}'.format(dev, btn[0]),
114 '{}: {}'.format(dev, btn[1]),
123 self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
124 self.data = self.count = self.active = None
125 self.addr = self.cmd = None
128 self.out_ann = self.register(srd.OUTPUT_ANN)
130 def metadata(self, key, value):
131 if key == srd.SRD_CONF_SAMPLERATE:
132 self.samplerate = value
135 self.tolerance = 0.05 # +/-5%
136 self.lc = int(self.samplerate * 0.0135) - 1 # 13.5ms
137 self.rc = int(self.samplerate * 0.01125) - 1 # 11.25ms
138 self.dazero = int(self.samplerate * 0.001125) - 1 # 1.125ms
139 self.daone = int(self.samplerate * 0.00225) - 1 # 2.25ms
140 self.stop = int(self.samplerate * 0.000652) - 1 # 0.652ms
142 def compare_with_tolerance(self, measured, base):
143 return (measured >= base * (1 - self.tolerance)
144 and measured <= base * (1 + self.tolerance))
146 def handle_bit(self, tick):
148 if self.compare_with_tolerance(tick, self.dazero):
150 elif self.compare_with_tolerance(tick, self.daone):
153 self.putb([Ann.BIT, ['{:d}'.format(ret)]])
154 self.data |= (ret << self.count) # LSB-first
155 self.count = self.count + 1
156 self.ss_bit = self.samplenum
158 def data_ok(self, check):
159 name = self.state.title()
160 valid = ((self.data >> 8) ^ (self.data & 0xff)) == 0xff
162 if self.state == 'ADDRESS':
163 self.addr = self.data
164 if self.state == 'COMMAND':
167 self.ss_start = self.samplenum
169 if check and not valid:
170 self.putx([Ann.WARN, ['{} error: 0x{:04X}'.format(name, self.data)]])
172 self.putd(self.data >> 8)
173 self.data = self.count = 0
174 self.ss_bit = self.ss_start = self.samplenum
178 if not self.samplerate:
179 raise SamplerateError('Cannot decode without samplerate.')
183 if self.options['cd_freq']:
184 cd_count = int(self.samplerate / self.options['cd_freq']) + 1
187 self.active = 0 if self.options['polarity'] == 'active-low' else 1
190 # Detect changes in the presence of an active input signal.
191 # The decoder can either be fed an already filtered RX signal
192 # or optionally can detect the presence of a carrier. Periods
193 # of inactivity (signal changes slower than the carrier freq,
194 # if specified) pass on the most recently sampled level. This
195 # approach works for filtered and unfiltered input alike, and
196 # only slightly extends the active phase of input signals with
197 # carriers included by one period of the carrier frequency.
198 # IR based communication protocols can cope with this slight
199 # inaccuracy just fine by design. Enabling carrier detection
200 # on already filtered signals will keep the length of their
201 # active period, but will shift their signal changes by one
202 # carrier period before they get passed to decoding logic.
204 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
207 if cur_ir == prev_ir:
212 (self.ir,) = self.wait({Pin.IR: 'e'})
214 if self.ir != self.active:
215 # Save the non-active edge, then wait for the next edge.
216 self.ss_other_edge = self.samplenum
219 b = self.samplenum - self.ss_bit
222 if self.state == 'IDLE':
223 if self.compare_with_tolerance(b, self.lc):
224 self.putpause('Long')
225 self.putx([Ann.LEADER_CODE, ['Leader code', 'Leader', 'LC', 'L']])
226 self.ss_remote = self.ss_start
227 self.data = self.count = 0
228 self.state = 'ADDRESS'
229 elif self.compare_with_tolerance(b, self.rc):
230 self.putpause('Short')
231 self.putstop(self.samplenum)
232 self.samplenum += self.stop
233 self.putx([Ann.REPEAT_CODE, ['Repeat code', 'Repeat', 'RC', 'R']])
234 self.data = self.count = 0
235 self.ss_bit = self.ss_start = self.samplenum
236 elif self.state == 'ADDRESS':
240 self.state = 'ADDRESS#'
241 elif self.state == 'ADDRESS#':
244 self.state = 'COMMAND' if self.data_ok(True) else 'IDLE'
245 elif self.state == 'COMMAND':
249 self.state = 'COMMAND#'
250 elif self.state == 'COMMAND#':
253 self.state = 'STOP' if self.data_ok(True) else 'IDLE'
254 elif self.state == 'STOP':
255 self.putstop(self.ss_bit)
257 self.ss_bit = self.ss_start = self.samplenum