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