]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/ir_nec/pd.py
avr_isp: Add more parts
[libsigrokdecode.git] / decoders / ir_nec / pd.py
... / ...
CommitLineData
1##
2## This file is part of the libsigrokdecode project.
3##
4## Copyright (C) 2014 Gump Yang <gump.yang@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 2 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
17## along with this program; if not, see <http://www.gnu.org/licenses/>.
18##
19
20from common.srdhelper import bitpack
21from .lists import *
22import sigrokdecode as srd
23
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. The tolerance is an arbitrary choice, available
27# literature does not mention any. The inter-frame timeout is not a part
28# of the protocol, but an implementation detail of this sigrok decoder.
29_TIME_TOL = 8 # tolerance, in percent
30_TIME_IDLE = 20.0 # inter-frame timeout, in ms
31_TIME_LC = 13.5 # leader code, in ms
32_TIME_RC = 11.25 # repeat code, in ms
33_TIME_ONE = 2.25 # one data bit, in ms
34_TIME_ZERO = 1.125 # zero data bit, in ms
35_TIME_STOP = 0.562 # stop bit, in ms
36
37class SamplerateError(Exception):
38 pass
39
40class Pin:
41 IR, = range(1)
42
43class Ann:
44 BIT, AGC, LONG_PAUSE, SHORT_PAUSE, STOP_BIT, \
45 LEADER_CODE, ADDR, ADDR_INV, CMD, CMD_INV, REPEAT_CODE, \
46 REMOTE, WARN = range(13)
47
48class Decoder(srd.Decoder):
49 api_version = 3
50 id = 'ir_nec'
51 name = 'IR NEC'
52 longname = 'IR NEC'
53 desc = 'NEC infrared remote control protocol.'
54 license = 'gplv2+'
55 inputs = ['logic']
56 outputs = []
57 tags = ['IR']
58 channels = (
59 {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
60 )
61 options = (
62 {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
63 'values': ('auto', 'active-low', 'active-high')},
64 {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
65 {'id': 'extended', 'desc': 'Extended NEC Protocol',
66 'default': 'no', 'values': ('yes', 'no')},
67 )
68 annotations = (
69 ('bit', 'Bit'),
70 ('agc-pulse', 'AGC pulse'),
71 ('longpause', 'Long pause'),
72 ('shortpause', 'Short pause'),
73 ('stop-bit', 'Stop bit'),
74 ('leader-code', 'Leader code'),
75 ('addr', 'Address'),
76 ('addr-inv', 'Address#'),
77 ('cmd', 'Command'),
78 ('cmd-inv', 'Command#'),
79 ('repeat-code', 'Repeat code'),
80 ('remote', 'Remote'),
81 ('warning', 'Warning'),
82 )
83 annotation_rows = (
84 ('bits', 'Bits', (Ann.BIT, Ann.AGC, Ann.LONG_PAUSE, Ann.SHORT_PAUSE, Ann.STOP_BIT)),
85 ('fields', 'Fields', (Ann.LEADER_CODE, Ann.ADDR, Ann.ADDR_INV, Ann.CMD, Ann.CMD_INV, Ann.REPEAT_CODE)),
86 ('remote-vals', 'Remote', (Ann.REMOTE,)),
87 ('warnings', 'Warnings', (Ann.WARN,)),
88 )
89
90 def putx(self, data):
91 self.put(self.ss_start, self.samplenum, self.out_ann, data)
92
93 def putb(self, data):
94 self.put(self.ss_bit, self.samplenum, self.out_ann, data)
95
96 def putd(self, data, bit_count):
97 name = self.state.title()
98 d = {'ADDRESS': Ann.ADDR, 'ADDRESS#': Ann.ADDR_INV,
99 'COMMAND': Ann.CMD, 'COMMAND#': Ann.CMD_INV}
100 s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'],
101 'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']}
102 fmt = '{{}}: 0x{{:0{}X}}'.format(bit_count // 4)
103 self.putx([d[self.state], [
104 fmt.format(name, data),
105 fmt.format(s[self.state][0], data),
106 fmt.format(s[self.state][1], data),
107 s[self.state][1],
108 ]])
109
110 def putstop(self, ss):
111 self.put(ss, ss + self.stop, self.out_ann,
112 [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
113
114 def putpause(self, p):
115 self.put(self.ss_start, self.ss_other_edge, self.out_ann,
116 [Ann.AGC, ['AGC pulse', 'AGC', 'A']])
117 idx = Ann.LONG_PAUSE if p == 'Long' else Ann.SHORT_PAUSE
118 self.put(self.ss_other_edge, self.samplenum, self.out_ann, [idx, [
119 '{} pause'.format(p),
120 '{}-pause'.format(p[0]),
121 '{}P'.format(p[0]),
122 'P',
123 ]])
124
125 def putremote(self):
126 dev = address.get(self.addr, 'Unknown device')
127 buttons = command.get(self.addr, {})
128 btn = buttons.get(self.cmd, ['Unknown', 'Unk'])
129 self.put(self.ss_remote, self.ss_bit + self.stop, self.out_ann, [Ann.REMOTE, [
130 '{}: {}'.format(dev, btn[0]),
131 '{}: {}'.format(dev, btn[1]),
132 '{}'.format(btn[1]),
133 ]])
134
135 def __init__(self):
136 self.reset()
137
138 def reset(self):
139 self.state = 'IDLE'
140 self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
141 self.data = []
142 self.addr = self.cmd = None
143
144 def start(self):
145 self.out_ann = self.register(srd.OUTPUT_ANN)
146
147 def metadata(self, key, value):
148 if key == srd.SRD_CONF_SAMPLERATE:
149 self.samplerate = value
150
151 def calc_rate(self):
152 self.tolerance = _TIME_TOL / 100
153 self.lc = int(self.samplerate * _TIME_LC / 1000) - 1
154 self.rc = int(self.samplerate * _TIME_RC / 1000) - 1
155 self.dazero = int(self.samplerate * _TIME_ZERO / 1000) - 1
156 self.daone = int(self.samplerate * _TIME_ONE / 1000) - 1
157 self.stop = int(self.samplerate * _TIME_STOP / 1000) - 1
158 self.idle_to = int(self.samplerate * _TIME_IDLE / 1000) - 1
159
160 def compare_with_tolerance(self, measured, base):
161 return (measured >= base * (1 - self.tolerance)
162 and measured <= base * (1 + self.tolerance))
163
164 def handle_bit(self, tick):
165 ret = None
166 if self.compare_with_tolerance(tick, self.dazero):
167 ret = 0
168 elif self.compare_with_tolerance(tick, self.daone):
169 ret = 1
170 if ret in (0, 1):
171 self.putb([Ann.BIT, ['{:d}'.format(ret)]])
172 self.data.append(ret)
173 self.ss_bit = self.samplenum
174
175 def data_ok(self, check, want_len):
176 name = self.state.title()
177 normal, inverted = bitpack(self.data[:8]), bitpack(self.data[8:])
178 valid = (normal ^ inverted) == 0xff
179 show = inverted if self.state.endswith('#') else normal
180 is_ext_addr = self.is_extended and self.state == 'ADDRESS'
181 if is_ext_addr:
182 normal = bitpack(self.data)
183 show = normal
184 valid = True
185 if len(self.data) == want_len:
186 if self.state == 'ADDRESS':
187 self.addr = normal
188 if self.state == 'COMMAND':
189 self.cmd = normal
190 self.putd(show, want_len)
191 self.ss_start = self.samplenum
192 if is_ext_addr:
193 self.data = []
194 self.ss_bit = self.ss_start = self.samplenum
195 return True
196 self.putd(show, want_len)
197 if check and not valid:
198 warn_show = bitpack(self.data)
199 self.putx([Ann.WARN, ['{} error: 0x{:04X}'.format(name, warn_show)]])
200 self.data = []
201 self.ss_bit = self.ss_start = self.samplenum
202 return valid
203
204 def decode(self):
205 if not self.samplerate:
206 raise SamplerateError('Cannot decode without samplerate.')
207 self.calc_rate()
208
209 cd_count = None
210 if self.options['cd_freq']:
211 cd_count = int(self.samplerate / self.options['cd_freq']) + 1
212 prev_ir = None
213
214 if self.options['polarity'] == 'auto':
215 # Take sample 0 as reference.
216 curr_level, = self.wait({'skip': 0})
217 active = 1 - curr_level
218 else:
219 active = 0 if self.options['polarity'] == 'active-low' else 1
220 self.is_extended = self.options['extended'] == 'yes'
221 want_addr_len = 16 if self.is_extended else 8
222
223 while True:
224 # Detect changes in the presence of an active input signal.
225 # The decoder can either be fed an already filtered RX signal
226 # or optionally can detect the presence of a carrier. Periods
227 # of inactivity (signal changes slower than the carrier freq,
228 # if specified) pass on the most recently sampled level. This
229 # approach works for filtered and unfiltered input alike, and
230 # only slightly extends the active phase of input signals with
231 # carriers included by one period of the carrier frequency.
232 # IR based communication protocols can cope with this slight
233 # inaccuracy just fine by design. Enabling carrier detection
234 # on already filtered signals will keep the length of their
235 # active period, but will shift their signal changes by one
236 # carrier period before they get passed to decoding logic.
237 if cd_count:
238 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
239 if self.matched[0]:
240 cur_ir = active
241 if cur_ir == prev_ir:
242 continue
243 prev_ir = cur_ir
244 self.ir = cur_ir
245 else:
246 (self.ir,) = self.wait({Pin.IR: 'e'})
247
248 if self.ir != active:
249 # Save the location of the non-active edge (recessive),
250 # then wait for the next edge. Immediately process the
251 # end of the STOP bit which completes an IR frame.
252 self.ss_other_edge = self.samplenum
253 if self.state != 'STOP':
254 continue
255
256 # Reset internal state for long periods of idle level.
257 width = self.samplenum - self.ss_bit
258 if width >= self.idle_to and self.state != 'STOP':
259 self.reset()
260
261 # State machine.
262 if self.state == 'IDLE':
263 if self.compare_with_tolerance(width, self.lc):
264 self.putpause('Long')
265 self.putx([Ann.LEADER_CODE, ['Leader code', 'Leader', 'LC', 'L']])
266 self.ss_remote = self.ss_start
267 self.data = []
268 self.state = 'ADDRESS'
269 elif self.compare_with_tolerance(width, self.rc):
270 self.putpause('Short')
271 self.putstop(self.samplenum)
272 self.samplenum += self.stop
273 self.putx([Ann.REPEAT_CODE, ['Repeat code', 'Repeat', 'RC', 'R']])
274 self.data = []
275 self.ss_bit = self.ss_start = self.samplenum
276 elif self.state == 'ADDRESS':
277 self.handle_bit(width)
278 if len(self.data) == want_addr_len:
279 self.data_ok(False, want_addr_len)
280 self.state = 'COMMAND' if self.is_extended else 'ADDRESS#'
281 elif self.state == 'ADDRESS#':
282 self.handle_bit(width)
283 if len(self.data) == 16:
284 self.data_ok(True, 8)
285 self.state = 'COMMAND'
286 elif self.state == 'COMMAND':
287 self.handle_bit(width)
288 if len(self.data) == 8:
289 self.data_ok(False, 8)
290 self.state = 'COMMAND#'
291 elif self.state == 'COMMAND#':
292 self.handle_bit(width)
293 if len(self.data) == 16:
294 self.data_ok(True, 8)
295 self.state = 'STOP'
296 elif self.state == 'STOP':
297 self.putstop(self.ss_bit)
298 self.putremote()
299 self.ss_bit = self.ss_start = self.samplenum
300 self.state = 'IDLE'