]> sigrok.org Git - libsigrokdecode.git/blame - decoders/ir_nec/pd.py
ir_nec: use common helper for bit accumulation
[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
21cda951
UH
24class SamplerateError(Exception):
25 pass
26
34ed4b3f
GS
27class Pin:
28 IR, = range(1)
29
30class Ann:
31 BIT, AGC, LONG_PAUSE, SHORT_PAUSE, STOP_BIT, \
32 LEADER_CODE, ADDR, ADDR_INV, CMD, CMD_INV, REPEAT_CODE, \
33 REMOTE, WARN = range(13)
34
5e6fa9cc 35class Decoder(srd.Decoder):
5844bb0f 36 api_version = 3
00962e76
UH
37 id = 'ir_nec'
38 name = 'IR NEC'
39 longname = 'IR NEC'
40 desc = 'NEC infrared remote control protocol.'
5e6fa9cc
GY
41 license = 'gplv2+'
42 inputs = ['logic']
6cbba91f 43 outputs = []
d6d8a8a4 44 tags = ['IR']
6a15597a 45 channels = (
5e6fa9cc 46 {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
bee57ee8
UH
47 )
48 options = (
49 {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
50 'values': ('active-low', 'active-high')},
fb1870b0 51 {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
bee57ee8
UH
52 )
53 annotations = (
54 ('bit', 'Bit'),
55 ('agc-pulse', 'AGC pulse'),
56 ('longpause', 'Long pause'),
57 ('shortpause', 'Short pause'),
58 ('stop-bit', 'Stop bit'),
59 ('leader-code', 'Leader code'),
60 ('addr', 'Address'),
61 ('addr-inv', 'Address#'),
62 ('cmd', 'Command'),
63 ('cmd-inv', 'Command#'),
64 ('repeat-code', 'Repeat code'),
65 ('remote', 'Remote'),
e144452b 66 ('warning', 'Warning'),
bee57ee8 67 )
5e6fa9cc 68 annotation_rows = (
34ed4b3f
GS
69 ('bits', 'Bits', (Ann.BIT, Ann.AGC, Ann.LONG_PAUSE, Ann.SHORT_PAUSE, Ann.STOP_BIT)),
70 ('fields', 'Fields', (Ann.LEADER_CODE, Ann.ADDR, Ann.ADDR_INV, Ann.CMD, Ann.CMD_INV, Ann.REPEAT_CODE)),
71 ('remote-vals', 'Remote', (Ann.REMOTE,)),
72 ('warnings', 'Warnings', (Ann.WARN,)),
5e6fa9cc
GY
73 )
74
5e6fa9cc
GY
75 def putx(self, data):
76 self.put(self.ss_start, self.samplenum, self.out_ann, data)
77
78 def putb(self, data):
79 self.put(self.ss_bit, self.samplenum, self.out_ann, data)
80
70835fd4
UH
81 def putd(self, data):
82 name = self.state.title()
34ed4b3f
GS
83 d = {'ADDRESS': Ann.ADDR, 'ADDRESS#': Ann.ADDR_INV,
84 'COMMAND': Ann.CMD, 'COMMAND#': Ann.CMD_INV}
70835fd4
UH
85 s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'],
86 'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']}
34ed4b3f
GS
87 self.putx([d[self.state], [
88 '{}: 0x{:02X}'.format(name, data),
89 '{}: 0x{:02X}'.format(s[self.state][0], data),
90 '{}: 0x{:02X}'.format(s[self.state][1], data),
91 s[self.state][1],
92 ]])
70835fd4
UH
93
94 def putstop(self, ss):
95 self.put(ss, ss + self.stop, self.out_ann,
34ed4b3f 96 [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
70835fd4
UH
97
98 def putpause(self, p):
99 self.put(self.ss_start, self.ss_other_edge, self.out_ann,
34ed4b3f
GS
100 [Ann.AGC, ['AGC pulse', 'AGC', 'A']])
101 idx = Ann.LONG_PAUSE if p == 'Long' else Ann.SHORT_PAUSE
102 self.put(self.ss_other_edge, self.samplenum, self.out_ann, [idx, [
103 '{} pause'.format(p),
104 '{}-pause'.format(p[0]),
105 '{}P'.format(p[0]),
106 'P',
107 ]])
70835fd4 108
12fecc8f
UH
109 def putremote(self):
110 dev = address.get(self.addr, 'Unknown device')
d478372a
GS
111 buttons = command.get(self.addr, {})
112 btn = buttons.get(self.cmd, ['Unknown', 'Unk'])
34ed4b3f
GS
113 self.put(self.ss_remote, self.ss_bit + self.stop, self.out_ann, [Ann.REMOTE, [
114 '{}: {}'.format(dev, btn[0]),
115 '{}: {}'.format(dev, btn[1]),
116 '{}'.format(btn[1]),
117 ]])
12fecc8f 118
92b7b49f 119 def __init__(self):
10aeb8ea
GS
120 self.reset()
121
122 def reset(self):
5e6fa9cc 123 self.state = 'IDLE'
12fecc8f 124 self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
025c728e 125 self.data = []
12fecc8f 126 self.addr = self.cmd = None
5e6fa9cc
GY
127
128 def start(self):
5e6fa9cc 129 self.out_ann = self.register(srd.OUTPUT_ANN)
5844bb0f 130
5e6fa9cc
GY
131 def metadata(self, key, value):
132 if key == srd.SRD_CONF_SAMPLERATE:
133 self.samplerate = value
b3f83fda
GS
134
135 def calc_rate(self):
82ea183f 136 self.tolerance = 0.05 # +/-5%
73fc79e0
UH
137 self.lc = int(self.samplerate * 0.0135) - 1 # 13.5ms
138 self.rc = int(self.samplerate * 0.01125) - 1 # 11.25ms
139 self.dazero = int(self.samplerate * 0.001125) - 1 # 1.125ms
140 self.daone = int(self.samplerate * 0.00225) - 1 # 2.25ms
70835fd4 141 self.stop = int(self.samplerate * 0.000652) - 1 # 0.652ms
5e6fa9cc 142
82ea183f
GM
143 def compare_with_tolerance(self, measured, base):
144 return (measured >= base * (1 - self.tolerance)
145 and measured <= base * (1 + self.tolerance))
146
70835fd4 147 def handle_bit(self, tick):
5bb61a25 148 ret = None
82ea183f 149 if self.compare_with_tolerance(tick, self.dazero):
5e6fa9cc 150 ret = 0
82ea183f 151 elif self.compare_with_tolerance(tick, self.daone):
5e6fa9cc 152 ret = 1
5bb61a25 153 if ret in (0, 1):
34ed4b3f 154 self.putb([Ann.BIT, ['{:d}'.format(ret)]])
025c728e 155 self.data.append(ret)
5e6fa9cc 156 self.ss_bit = self.samplenum
5e6fa9cc 157
d478372a
GS
158 def data_ok(self, check):
159 name = self.state.title()
025c728e
GS
160 normal, inverted = bitpack(self.data[:8]), bitpack(self.data[8:])
161 valid = (normal ^ inverted) == 0xff
162 show = inverted if self.state.endswith('#') else normal
163 if len(self.data) == 8:
12fecc8f 164 if self.state == 'ADDRESS':
025c728e 165 self.addr = normal
12fecc8f 166 if self.state == 'COMMAND':
025c728e
GS
167 self.cmd = normal
168 self.putd(show)
70835fd4
UH
169 self.ss_start = self.samplenum
170 return True
d478372a 171 if check and not valid:
025c728e
GS
172 warn_show = bitpack(self.data)
173 self.putx([Ann.WARN, ['{} error: 0x{:04X}'.format(name, warn_show)]])
d478372a 174 else:
025c728e
GS
175 self.putd(show)
176 self.data = []
5e6fa9cc 177 self.ss_bit = self.ss_start = self.samplenum
d478372a 178 return valid
5e6fa9cc 179
5844bb0f 180 def decode(self):
21cda951
UH
181 if not self.samplerate:
182 raise SamplerateError('Cannot decode without samplerate.')
b3f83fda 183 self.calc_rate()
fb1870b0
GS
184
185 cd_count = None
186 if self.options['cd_freq']:
187 cd_count = int(self.samplerate / self.options['cd_freq']) + 1
1865f48d
PM
188 prev_ir = None
189
025c728e 190 active = 0 if self.options['polarity'] == 'active-low' else 1
fb1870b0 191
5844bb0f 192 while True:
fb1870b0
GS
193 # Detect changes in the presence of an active input signal.
194 # The decoder can either be fed an already filtered RX signal
195 # or optionally can detect the presence of a carrier. Periods
196 # of inactivity (signal changes slower than the carrier freq,
197 # if specified) pass on the most recently sampled level. This
198 # approach works for filtered and unfiltered input alike, and
199 # only slightly extends the active phase of input signals with
200 # carriers included by one period of the carrier frequency.
201 # IR based communication protocols can cope with this slight
202 # inaccuracy just fine by design. Enabling carrier detection
203 # on already filtered signals will keep the length of their
204 # active period, but will shift their signal changes by one
205 # carrier period before they get passed to decoding logic.
206 if cd_count:
34ed4b3f 207 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
fb1870b0 208 if self.matched[0]:
025c728e 209 cur_ir = active
fb1870b0
GS
210 if cur_ir == prev_ir:
211 continue
212 prev_ir = cur_ir
213 self.ir = cur_ir
214 else:
34ed4b3f 215 (self.ir,) = self.wait({Pin.IR: 'e'})
00962e76 216
025c728e 217 if self.ir != active:
5844bb0f 218 # Save the non-active edge, then wait for the next edge.
70835fd4 219 self.ss_other_edge = self.samplenum
5e6fa9cc
GY
220 continue
221
73fc79e0
UH
222 b = self.samplenum - self.ss_bit
223
224 # State machine.
225 if self.state == 'IDLE':
82ea183f 226 if self.compare_with_tolerance(b, self.lc):
70835fd4 227 self.putpause('Long')
34ed4b3f 228 self.putx([Ann.LEADER_CODE, ['Leader code', 'Leader', 'LC', 'L']])
12fecc8f 229 self.ss_remote = self.ss_start
025c728e 230 self.data = []
73fc79e0 231 self.state = 'ADDRESS'
82ea183f 232 elif self.compare_with_tolerance(b, self.rc):
70835fd4
UH
233 self.putpause('Short')
234 self.putstop(self.samplenum)
235 self.samplenum += self.stop
34ed4b3f 236 self.putx([Ann.REPEAT_CODE, ['Repeat code', 'Repeat', 'RC', 'R']])
025c728e 237 self.data = []
73fc79e0
UH
238 self.ss_bit = self.ss_start = self.samplenum
239 elif self.state == 'ADDRESS':
70835fd4 240 self.handle_bit(b)
025c728e 241 if len(self.data) == 8:
d478372a
GS
242 self.data_ok(False)
243 self.state = 'ADDRESS#'
70835fd4
UH
244 elif self.state == 'ADDRESS#':
245 self.handle_bit(b)
025c728e 246 if len(self.data) == 16:
d478372a 247 self.state = 'COMMAND' if self.data_ok(True) else 'IDLE'
73fc79e0 248 elif self.state == 'COMMAND':
70835fd4 249 self.handle_bit(b)
025c728e 250 if len(self.data) == 8:
d478372a
GS
251 self.data_ok(False)
252 self.state = 'COMMAND#'
70835fd4
UH
253 elif self.state == 'COMMAND#':
254 self.handle_bit(b)
025c728e 255 if len(self.data) == 16:
d478372a 256 self.state = 'STOP' if self.data_ok(True) else 'IDLE'
70835fd4
UH
257 elif self.state == 'STOP':
258 self.putstop(self.ss_bit)
12fecc8f 259 self.putremote()
70835fd4
UH
260 self.ss_bit = self.ss_start = self.samplenum
261 self.state = 'IDLE'