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