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