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 from common.srdhelper import bitpack
22 import sigrokdecode as srd
24 # Concentrate all timing constraints of the IR protocol here in a single
25 # location at the top of the source, to raise awareness and to simplify
26 # review and adjustment.
27 _TIME_TOL = 5 # tolerance, in percent
28 _TIME_LC = 13.5 # leader code, in ms
29 _TIME_RC = 11.25 # repeat code, in ms
30 _TIME_ZERO = 1.125 # zero data bit, in ms
31 _TIME_ONE = 2.25 # one data bit, in ms
32 _TIME_STOP = 0.652 # stop bit, in ms
33 _TIME_IDLE = 20.0 # inter frame timeout, in ms, arbitrary choice
35 class SamplerateError(Exception):
42 BIT, AGC, LONG_PAUSE, SHORT_PAUSE, STOP_BIT, \
43 LEADER_CODE, ADDR, ADDR_INV, CMD, CMD_INV, REPEAT_CODE, \
44 REMOTE, WARN = range(13)
46 class Decoder(srd.Decoder):
51 desc = 'NEC infrared remote control protocol.'
57 {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
60 {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
61 'values': ('auto', 'active-low', 'active-high')},
62 {'id': 'tolerance', 'desc': 'Timing tolerance (%)', 'default': _TIME_TOL},
63 {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
64 {'id': 'extended', 'desc': 'Extended NEC Protocol',
65 'default': 'no', 'values': ('yes', 'no')},
69 ('agc-pulse', 'AGC pulse'),
70 ('longpause', 'Long pause'),
71 ('shortpause', 'Short pause'),
72 ('stop-bit', 'Stop bit'),
73 ('leader-code', 'Leader code'),
75 ('addr-inv', 'Address#'),
77 ('cmd-inv', 'Command#'),
78 ('repeat-code', 'Repeat code'),
80 ('warning', 'Warning'),
83 ('bits', 'Bits', (Ann.BIT, Ann.AGC, Ann.LONG_PAUSE, Ann.SHORT_PAUSE, Ann.STOP_BIT)),
84 ('fields', 'Fields', (Ann.LEADER_CODE, Ann.ADDR, Ann.ADDR_INV, Ann.CMD, Ann.CMD_INV, Ann.REPEAT_CODE)),
85 ('remote-vals', 'Remote', (Ann.REMOTE,)),
86 ('warnings', 'Warnings', (Ann.WARN,)),
90 self.put(self.ss_start, self.samplenum, self.out_ann, data)
93 self.put(self.ss_bit, self.samplenum, self.out_ann, data)
95 def putd(self, data, bit_count):
96 name = self.state.title()
97 d = {'ADDRESS': Ann.ADDR, 'ADDRESS#': Ann.ADDR_INV,
98 'COMMAND': Ann.CMD, 'COMMAND#': Ann.CMD_INV}
99 s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'],
100 'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']}
101 fmt = '{{}}: 0x{{:0{}X}}'.format(bit_count // 4)
102 self.putx([d[self.state], [
103 fmt.format(name, data),
104 fmt.format(s[self.state][0], data),
105 fmt.format(s[self.state][1], data),
109 def putstop(self, ss):
110 self.put(ss, ss + self.stop, self.out_ann,
111 [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
113 def putpause(self, p):
114 self.put(self.ss_start, self.ss_other_edge, self.out_ann,
115 [Ann.AGC, ['AGC pulse', 'AGC', 'A']])
116 idx = Ann.LONG_PAUSE if p == 'Long' else Ann.SHORT_PAUSE
117 self.put(self.ss_other_edge, self.samplenum, self.out_ann, [idx, [
118 '{} pause'.format(p),
119 '{}-pause'.format(p[0]),
125 dev = address.get(self.addr, 'Unknown device')
126 buttons = command.get(self.addr, {})
127 btn = buttons.get(self.cmd, ['Unknown', 'Unk'])
128 self.put(self.ss_remote, self.ss_bit + self.stop, self.out_ann, [Ann.REMOTE, [
129 '{}: {}'.format(dev, btn[0]),
130 '{}: {}'.format(dev, btn[1]),
139 self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
141 self.addr = self.cmd = None
144 self.out_ann = self.register(srd.OUTPUT_ANN)
146 def metadata(self, key, value):
147 if key == srd.SRD_CONF_SAMPLERATE:
148 self.samplerate = value
151 self.tolerance = self.options['tolerance'] / 100
152 self.lc = int(self.samplerate * _TIME_LC / 1000) - 1
153 self.rc = int(self.samplerate * _TIME_RC / 1000) - 1
154 self.dazero = int(self.samplerate * _TIME_ZERO / 1000) - 1
155 self.daone = int(self.samplerate * _TIME_ONE / 1000) - 1
156 self.stop = int(self.samplerate * _TIME_STOP / 1000) - 1
157 self.idle_to = int(self.samplerate * _TIME_IDLE / 1000) - 1
159 def compare_with_tolerance(self, measured, base):
160 return (measured >= base * (1 - self.tolerance)
161 and measured <= base * (1 + self.tolerance))
163 def handle_bit(self, tick):
165 if self.compare_with_tolerance(tick, self.dazero):
167 elif self.compare_with_tolerance(tick, self.daone):
170 self.putb([Ann.BIT, ['{:d}'.format(ret)]])
171 self.data.append(ret)
172 self.ss_bit = self.samplenum
174 def data_ok(self, check, want_len):
175 name = self.state.title()
176 normal, inverted = bitpack(self.data[:8]), bitpack(self.data[8:])
177 valid = (normal ^ inverted) == 0xff
178 show = inverted if self.state.endswith('#') else normal
179 is_ext_addr = self.is_extended and self.state == 'ADDRESS'
181 normal = bitpack(self.data)
184 if len(self.data) == want_len:
185 if self.state == 'ADDRESS':
187 if self.state == 'COMMAND':
189 self.putd(show, want_len)
190 self.ss_start = self.samplenum
193 self.ss_bit = self.ss_start = self.samplenum
195 self.putd(show, want_len)
196 if check and not valid:
197 warn_show = bitpack(self.data)
198 self.putx([Ann.WARN, ['{} error: 0x{:04X}'.format(name, warn_show)]])
200 self.ss_bit = self.ss_start = self.samplenum
204 if not self.samplerate:
205 raise SamplerateError('Cannot decode without samplerate.')
209 if self.options['cd_freq']:
210 cd_count = int(self.samplerate / self.options['cd_freq']) + 1
213 if self.options['polarity'] == 'auto':
214 # Take sample 0 as reference.
215 curr_level, = self.wait({'skip': 0})
216 active = 1 - curr_level
218 active = 0 if self.options['polarity'] == 'active-low' else 1
219 self.is_extended = self.options['extended'] == 'yes'
220 want_addr_len = 16 if self.is_extended else 8
223 # Detect changes in the presence of an active input signal.
224 # The decoder can either be fed an already filtered RX signal
225 # or optionally can detect the presence of a carrier. Periods
226 # of inactivity (signal changes slower than the carrier freq,
227 # if specified) pass on the most recently sampled level. This
228 # approach works for filtered and unfiltered input alike, and
229 # only slightly extends the active phase of input signals with
230 # carriers included by one period of the carrier frequency.
231 # IR based communication protocols can cope with this slight
232 # inaccuracy just fine by design. Enabling carrier detection
233 # on already filtered signals will keep the length of their
234 # active period, but will shift their signal changes by one
235 # carrier period before they get passed to decoding logic.
237 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
240 if cur_ir == prev_ir:
245 (self.ir,) = self.wait({Pin.IR: 'e'})
247 if self.ir != active:
248 # Save the location of the non-active edge (recessive),
249 # then wait for the next edge. Immediately process the
250 # end of the STOP bit which completes an IR frame.
251 self.ss_other_edge = self.samplenum
252 if self.state != 'STOP':
255 # Reset internal state for long periods of idle level.
256 width = self.samplenum - self.ss_bit
257 if width >= self.idle_to and self.state != 'STOP':
261 if self.state == 'IDLE':
262 if self.compare_with_tolerance(width, self.lc):
263 self.putpause('Long')
264 self.putx([Ann.LEADER_CODE, ['Leader code', 'Leader', 'LC', 'L']])
265 self.ss_remote = self.ss_start
267 self.state = 'ADDRESS'
268 elif self.compare_with_tolerance(width, self.rc):
269 self.putpause('Short')
270 self.putstop(self.samplenum)
271 self.samplenum += self.stop
272 self.putx([Ann.REPEAT_CODE, ['Repeat code', 'Repeat', 'RC', 'R']])
274 self.ss_bit = self.ss_start = self.samplenum
275 elif self.state == 'ADDRESS':
276 self.handle_bit(width)
277 if len(self.data) == want_addr_len:
278 self.data_ok(False, want_addr_len)
279 self.state = 'COMMAND' if self.is_extended else 'ADDRESS#'
280 elif self.state == 'ADDRESS#':
281 self.handle_bit(width)
282 if len(self.data) == 16:
283 self.data_ok(True, 8)
284 self.state = 'COMMAND'
285 elif self.state == 'COMMAND':
286 self.handle_bit(width)
287 if len(self.data) == 8:
288 self.data_ok(False, 8)
289 self.state = 'COMMAND#'
290 elif self.state == 'COMMAND#':
291 self.handle_bit(width)
292 if len(self.data) == 16:
293 self.data_ok(True, 8)
295 elif self.state == 'STOP':
296 self.putstop(self.ss_bit)
298 self.ss_bit = self.ss_start = self.samplenum