]> sigrok.org Git - libsigrokdecode.git/blame - decoders/ir_nec/pd.py
avr_isp: Add more parts
[libsigrokdecode.git] / decoders / ir_nec / pd.py
CommitLineData
5e6fa9cc
GY
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
4539e9ca 17## along with this program; if not, see <http://www.gnu.org/licenses/>.
5e6fa9cc
GY
18##
19
025c728e 20from common.srdhelper import bitpack
12fecc8f 21from .lists import *
025c728e 22import sigrokdecode as srd
5e6fa9cc 23
f559daba
GS
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
9ade72a2
GS
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
f559daba 34_TIME_ZERO = 1.125 # zero data bit, in ms
074cab87 35_TIME_STOP = 0.562 # stop bit, in ms
f559daba 36
21cda951
UH
37class SamplerateError(Exception):
38 pass
39
34ed4b3f
GS
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
5e6fa9cc 48class Decoder(srd.Decoder):
5844bb0f 49 api_version = 3
00962e76
UH
50 id = 'ir_nec'
51 name = 'IR NEC'
52 longname = 'IR NEC'
53 desc = 'NEC infrared remote control protocol.'
5e6fa9cc
GY
54 license = 'gplv2+'
55 inputs = ['logic']
6cbba91f 56 outputs = []
d6d8a8a4 57 tags = ['IR']
6a15597a 58 channels = (
5e6fa9cc 59 {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
bee57ee8
UH
60 )
61 options = (
62 {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
302266c0 63 'values': ('auto', 'active-low', 'active-high')},
fb1870b0 64 {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
17e0ba22
GS
65 {'id': 'extended', 'desc': 'Extended NEC Protocol',
66 'default': 'no', 'values': ('yes', 'no')},
bee57ee8
UH
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'),
e144452b 81 ('warning', 'Warning'),
bee57ee8 82 )
5e6fa9cc 83 annotation_rows = (
34ed4b3f
GS
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,)),
5e6fa9cc
GY
88 )
89
5e6fa9cc
GY
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
17e0ba22 96 def putd(self, data, bit_count):
70835fd4 97 name = self.state.title()
34ed4b3f
GS
98 d = {'ADDRESS': Ann.ADDR, 'ADDRESS#': Ann.ADDR_INV,
99 'COMMAND': Ann.CMD, 'COMMAND#': Ann.CMD_INV}
70835fd4
UH
100 s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'],
101 'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']}
17e0ba22 102 fmt = '{{}}: 0x{{:0{}X}}'.format(bit_count // 4)
34ed4b3f 103 self.putx([d[self.state], [
17e0ba22
GS
104 fmt.format(name, data),
105 fmt.format(s[self.state][0], data),
106 fmt.format(s[self.state][1], data),
34ed4b3f
GS
107 s[self.state][1],
108 ]])
70835fd4
UH
109
110 def putstop(self, ss):
111 self.put(ss, ss + self.stop, self.out_ann,
34ed4b3f 112 [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
70835fd4
UH
113
114 def putpause(self, p):
115 self.put(self.ss_start, self.ss_other_edge, self.out_ann,
34ed4b3f
GS
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 ]])
70835fd4 124
12fecc8f
UH
125 def putremote(self):
126 dev = address.get(self.addr, 'Unknown device')
d478372a
GS
127 buttons = command.get(self.addr, {})
128 btn = buttons.get(self.cmd, ['Unknown', 'Unk'])
34ed4b3f
GS
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 ]])
12fecc8f 134
92b7b49f 135 def __init__(self):
10aeb8ea
GS
136 self.reset()
137
138 def reset(self):
5e6fa9cc 139 self.state = 'IDLE'
12fecc8f 140 self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
025c728e 141 self.data = []
12fecc8f 142 self.addr = self.cmd = None
5e6fa9cc
GY
143
144 def start(self):
5e6fa9cc 145 self.out_ann = self.register(srd.OUTPUT_ANN)
5844bb0f 146
5e6fa9cc
GY
147 def metadata(self, key, value):
148 if key == srd.SRD_CONF_SAMPLERATE:
149 self.samplerate = value
b3f83fda
GS
150
151 def calc_rate(self):
9ade72a2 152 self.tolerance = _TIME_TOL / 100
f559daba
GS
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
5e6fa9cc 159
82ea183f
GM
160 def compare_with_tolerance(self, measured, base):
161 return (measured >= base * (1 - self.tolerance)
162 and measured <= base * (1 + self.tolerance))
163
70835fd4 164 def handle_bit(self, tick):
5bb61a25 165 ret = None
82ea183f 166 if self.compare_with_tolerance(tick, self.dazero):
5e6fa9cc 167 ret = 0
82ea183f 168 elif self.compare_with_tolerance(tick, self.daone):
5e6fa9cc 169 ret = 1
5bb61a25 170 if ret in (0, 1):
34ed4b3f 171 self.putb([Ann.BIT, ['{:d}'.format(ret)]])
025c728e 172 self.data.append(ret)
5e6fa9cc 173 self.ss_bit = self.samplenum
5e6fa9cc 174
17e0ba22 175 def data_ok(self, check, want_len):
d478372a 176 name = self.state.title()
025c728e
GS
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
17e0ba22
GS
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:
12fecc8f 186 if self.state == 'ADDRESS':
025c728e 187 self.addr = normal
12fecc8f 188 if self.state == 'COMMAND':
025c728e 189 self.cmd = normal
17e0ba22 190 self.putd(show, want_len)
70835fd4 191 self.ss_start = self.samplenum
17e0ba22
GS
192 if is_ext_addr:
193 self.data = []
194 self.ss_bit = self.ss_start = self.samplenum
70835fd4 195 return True
24490b8a 196 self.putd(show, want_len)
d478372a 197 if check and not valid:
025c728e
GS
198 warn_show = bitpack(self.data)
199 self.putx([Ann.WARN, ['{} error: 0x{:04X}'.format(name, warn_show)]])
025c728e 200 self.data = []
5e6fa9cc 201 self.ss_bit = self.ss_start = self.samplenum
d478372a 202 return valid
5e6fa9cc 203
5844bb0f 204 def decode(self):
21cda951
UH
205 if not self.samplerate:
206 raise SamplerateError('Cannot decode without samplerate.')
b3f83fda 207 self.calc_rate()
fb1870b0
GS
208
209 cd_count = None
210 if self.options['cd_freq']:
211 cd_count = int(self.samplerate / self.options['cd_freq']) + 1
1865f48d
PM
212 prev_ir = None
213
302266c0
B
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
17e0ba22
GS
220 self.is_extended = self.options['extended'] == 'yes'
221 want_addr_len = 16 if self.is_extended else 8
fb1870b0 222
5844bb0f 223 while True:
fb1870b0
GS
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:
34ed4b3f 238 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
fb1870b0 239 if self.matched[0]:
025c728e 240 cur_ir = active
fb1870b0
GS
241 if cur_ir == prev_ir:
242 continue
243 prev_ir = cur_ir
244 self.ir = cur_ir
245 else:
34ed4b3f 246 (self.ir,) = self.wait({Pin.IR: 'e'})
00962e76 247
025c728e 248 if self.ir != active:
85f616ed
B
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.
70835fd4 252 self.ss_other_edge = self.samplenum
85f616ed
B
253 if self.state != 'STOP':
254 continue
5e6fa9cc 255
24490b8a
GS
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()
73fc79e0
UH
260
261 # State machine.
262 if self.state == 'IDLE':
24490b8a 263 if self.compare_with_tolerance(width, self.lc):
70835fd4 264 self.putpause('Long')
34ed4b3f 265 self.putx([Ann.LEADER_CODE, ['Leader code', 'Leader', 'LC', 'L']])
12fecc8f 266 self.ss_remote = self.ss_start
025c728e 267 self.data = []
73fc79e0 268 self.state = 'ADDRESS'
24490b8a 269 elif self.compare_with_tolerance(width, self.rc):
70835fd4
UH
270 self.putpause('Short')
271 self.putstop(self.samplenum)
272 self.samplenum += self.stop
34ed4b3f 273 self.putx([Ann.REPEAT_CODE, ['Repeat code', 'Repeat', 'RC', 'R']])
025c728e 274 self.data = []
73fc79e0
UH
275 self.ss_bit = self.ss_start = self.samplenum
276 elif self.state == 'ADDRESS':
24490b8a 277 self.handle_bit(width)
17e0ba22
GS
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#'
70835fd4 281 elif self.state == 'ADDRESS#':
24490b8a 282 self.handle_bit(width)
025c728e 283 if len(self.data) == 16:
24490b8a
GS
284 self.data_ok(True, 8)
285 self.state = 'COMMAND'
73fc79e0 286 elif self.state == 'COMMAND':
24490b8a 287 self.handle_bit(width)
025c728e 288 if len(self.data) == 8:
17e0ba22 289 self.data_ok(False, 8)
d478372a 290 self.state = 'COMMAND#'
70835fd4 291 elif self.state == 'COMMAND#':
24490b8a 292 self.handle_bit(width)
025c728e 293 if len(self.data) == 16:
24490b8a
GS
294 self.data_ok(True, 8)
295 self.state = 'STOP'
70835fd4
UH
296 elif self.state == 'STOP':
297 self.putstop(self.ss_bit)
12fecc8f 298 self.putremote()
70835fd4
UH
299 self.ss_bit = self.ss_start = self.samplenum
300 self.state = 'IDLE'