]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/ir_nec/pd.py
ir_nec: concentrate timing at the top of the source file
[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.
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
34
35class SamplerateError(Exception):
36 pass
37
38class Pin:
39 IR, = range(1)
40
41class Ann:
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)
45
46class Decoder(srd.Decoder):
47 api_version = 3
48 id = 'ir_nec'
49 name = 'IR NEC'
50 longname = 'IR NEC'
51 desc = 'NEC infrared remote control protocol.'
52 license = 'gplv2+'
53 inputs = ['logic']
54 outputs = []
55 tags = ['IR']
56 channels = (
57 {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
58 )
59 options = (
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')},
66 )
67 annotations = (
68 ('bit', 'Bit'),
69 ('agc-pulse', 'AGC pulse'),
70 ('longpause', 'Long pause'),
71 ('shortpause', 'Short pause'),
72 ('stop-bit', 'Stop bit'),
73 ('leader-code', 'Leader code'),
74 ('addr', 'Address'),
75 ('addr-inv', 'Address#'),
76 ('cmd', 'Command'),
77 ('cmd-inv', 'Command#'),
78 ('repeat-code', 'Repeat code'),
79 ('remote', 'Remote'),
80 ('warning', 'Warning'),
81 )
82 annotation_rows = (
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,)),
87 )
88
89 def putx(self, data):
90 self.put(self.ss_start, self.samplenum, self.out_ann, data)
91
92 def putb(self, data):
93 self.put(self.ss_bit, self.samplenum, self.out_ann, data)
94
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),
106 s[self.state][1],
107 ]])
108
109 def putstop(self, ss):
110 self.put(ss, ss + self.stop, self.out_ann,
111 [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
112
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]),
120 '{}P'.format(p[0]),
121 'P',
122 ]])
123
124 def putremote(self):
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]),
131 '{}'.format(btn[1]),
132 ]])
133
134 def __init__(self):
135 self.reset()
136
137 def reset(self):
138 self.state = 'IDLE'
139 self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
140 self.data = []
141 self.addr = self.cmd = None
142
143 def start(self):
144 self.out_ann = self.register(srd.OUTPUT_ANN)
145
146 def metadata(self, key, value):
147 if key == srd.SRD_CONF_SAMPLERATE:
148 self.samplerate = value
149
150 def calc_rate(self):
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
158
159 def compare_with_tolerance(self, measured, base):
160 return (measured >= base * (1 - self.tolerance)
161 and measured <= base * (1 + self.tolerance))
162
163 def handle_bit(self, tick):
164 ret = None
165 if self.compare_with_tolerance(tick, self.dazero):
166 ret = 0
167 elif self.compare_with_tolerance(tick, self.daone):
168 ret = 1
169 if ret in (0, 1):
170 self.putb([Ann.BIT, ['{:d}'.format(ret)]])
171 self.data.append(ret)
172 self.ss_bit = self.samplenum
173
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'
180 if is_ext_addr:
181 normal = bitpack(self.data)
182 show = normal
183 valid = True
184 if len(self.data) == want_len:
185 if self.state == 'ADDRESS':
186 self.addr = normal
187 if self.state == 'COMMAND':
188 self.cmd = normal
189 self.putd(show, want_len)
190 self.ss_start = self.samplenum
191 if is_ext_addr:
192 self.data = []
193 self.ss_bit = self.ss_start = self.samplenum
194 return True
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)]])
199 self.data = []
200 self.ss_bit = self.ss_start = self.samplenum
201 return valid
202
203 def decode(self):
204 if not self.samplerate:
205 raise SamplerateError('Cannot decode without samplerate.')
206 self.calc_rate()
207
208 cd_count = None
209 if self.options['cd_freq']:
210 cd_count = int(self.samplerate / self.options['cd_freq']) + 1
211 prev_ir = None
212
213 if self.options['polarity'] == 'auto':
214 # Take sample 0 as reference.
215 curr_level, = self.wait({'skip': 0})
216 active = 1 - curr_level
217 else:
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
221
222 while True:
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.
236 if cd_count:
237 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
238 if self.matched[0]:
239 cur_ir = active
240 if cur_ir == prev_ir:
241 continue
242 prev_ir = cur_ir
243 self.ir = cur_ir
244 else:
245 (self.ir,) = self.wait({Pin.IR: 'e'})
246
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':
253 continue
254
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':
258 self.reset()
259
260 # State machine.
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
266 self.data = []
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']])
273 self.data = []
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)
294 self.state = 'STOP'
295 elif self.state == 'STOP':
296 self.putstop(self.ss_bit)
297 self.putremote()
298 self.ss_bit = self.ss_start = self.samplenum
299 self.state = 'IDLE'