]> sigrok.org Git - libsigrokdecode.git/blob - decoders/ir_nec/pd.py
2e547d5a793b5978e069fee99b6c5cd905da0acc
[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 import sigrokdecode as srd
21 from .lists import *
22
23 class SamplerateError(Exception):
24     pass
25
26 class Pin:
27     IR, = range(1)
28
29 class 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
34 class Decoder(srd.Decoder):
35     api_version = 3
36     id = 'ir_nec'
37     name = 'IR NEC'
38     longname = 'IR NEC'
39     desc = 'NEC infrared remote control protocol.'
40     license = 'gplv2+'
41     inputs = ['logic']
42     outputs = []
43     tags = ['IR']
44     channels = (
45         {'id': 'ir', 'name': 'IR', 'desc': 'Data line'},
46     )
47     options = (
48         {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
49             'values': ('active-low', 'active-high')},
50         {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
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'),
65         ('warning', 'Warning'),
66     )
67     annotation_rows = (
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,)),
72     )
73
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
80     def putd(self, data):
81         name = self.state.title()
82         d = {'ADDRESS': Ann.ADDR, 'ADDRESS#': Ann.ADDR_INV,
83              'COMMAND': Ann.CMD, 'COMMAND#': Ann.CMD_INV}
84         s = {'ADDRESS': ['ADDR', 'A'], 'ADDRESS#': ['ADDR#', 'A#'],
85              'COMMAND': ['CMD', 'C'], 'COMMAND#': ['CMD#', 'C#']}
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         ]])
92
93     def putstop(self, ss):
94         self.put(ss, ss + self.stop, self.out_ann,
95                  [Ann.STOP_BIT, ['Stop bit', 'Stop', 'St', 'S']])
96
97     def putpause(self, p):
98         self.put(self.ss_start, self.ss_other_edge, self.out_ann,
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         ]])
107
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'])
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         ]])
120
121     def __init__(self):
122         self.reset()
123
124     def reset(self):
125         self.state = 'IDLE'
126         self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
127         self.data = self.count = self.active = None
128         self.addr = self.cmd = None
129
130     def start(self):
131         self.out_ann = self.register(srd.OUTPUT_ANN)
132
133     def metadata(self, key, value):
134         if key == srd.SRD_CONF_SAMPLERATE:
135             self.samplerate = value
136         self.tolerance = 0.05 # +/-5%
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
141         self.stop = int(self.samplerate * 0.000652) - 1 # 0.652ms
142
143     def compare_with_tolerance(self, measured, base):
144         return (measured >= base * (1 - self.tolerance)
145                 and measured <= base * (1 + self.tolerance))
146
147     def handle_bit(self, tick):
148         ret = None
149         if self.compare_with_tolerance(tick, self.dazero):
150             ret = 0
151         elif self.compare_with_tolerance(tick, self.daone):
152             ret = 1
153         if ret in (0, 1):
154             self.putb([Ann.BIT, ['{:d}'.format(ret)]])
155             self.data |= (ret << self.count) # LSB-first
156             self.count = self.count + 1
157         self.ss_bit = self.samplenum
158
159     def data_ok(self):
160         ret, name = (self.data >> 8) & (self.data & 0xff), self.state.title()
161         if self.count == 8:
162             if self.state == 'ADDRESS':
163                 self.addr = self.data
164             if self.state == 'COMMAND':
165                 self.cmd = self.data
166             self.putd(self.data)
167             self.ss_start = self.samplenum
168             return True
169         if ret == 0:
170             self.putd(self.data >> 8)
171         else:
172             self.putx([Ann.WARN, ['{} error: 0x{:04X}'.format(name, self.data)]])
173         self.data = self.count = 0
174         self.ss_bit = self.ss_start = self.samplenum
175         return ret == 0
176
177     def decode(self):
178         if not self.samplerate:
179             raise SamplerateError('Cannot decode without samplerate.')
180
181         cd_count = None
182         if self.options['cd_freq']:
183             cd_count = int(self.samplerate / self.options['cd_freq']) + 1
184         prev_ir = None
185
186         self.active = 0 if self.options['polarity'] == 'active-low' else 1
187
188         while True:
189             # Detect changes in the presence of an active input signal.
190             # The decoder can either be fed an already filtered RX signal
191             # or optionally can detect the presence of a carrier. Periods
192             # of inactivity (signal changes slower than the carrier freq,
193             # if specified) pass on the most recently sampled level. This
194             # approach works for filtered and unfiltered input alike, and
195             # only slightly extends the active phase of input signals with
196             # carriers included by one period of the carrier frequency.
197             # IR based communication protocols can cope with this slight
198             # inaccuracy just fine by design. Enabling carrier detection
199             # on already filtered signals will keep the length of their
200             # active period, but will shift their signal changes by one
201             # carrier period before they get passed to decoding logic.
202             if cd_count:
203                 (cur_ir,) = self.wait([{Pin.IR: 'e'}, {'skip': cd_count}])
204                 if self.matched[0]:
205                     cur_ir = self.active
206                 if cur_ir == prev_ir:
207                     continue
208                 prev_ir = cur_ir
209                 self.ir = cur_ir
210             else:
211                 (self.ir,) = self.wait({Pin.IR: 'e'})
212
213             if self.ir != self.active:
214                 # Save the non-active edge, then wait for the next edge.
215                 self.ss_other_edge = self.samplenum
216                 continue
217
218             b = self.samplenum - self.ss_bit
219
220             # State machine.
221             if self.state == 'IDLE':
222                 if self.compare_with_tolerance(b, self.lc):
223                     self.putpause('Long')
224                     self.putx([Ann.LEADER_CODE, ['Leader code', 'Leader', 'LC', 'L']])
225                     self.ss_remote = self.ss_start
226                     self.data = self.count = 0
227                     self.state = 'ADDRESS'
228                 elif self.compare_with_tolerance(b, self.rc):
229                     self.putpause('Short')
230                     self.putstop(self.samplenum)
231                     self.samplenum += self.stop
232                     self.putx([Ann.REPEAT_CODE, ['Repeat code', 'Repeat', 'RC', 'R']])
233                     self.data = self.count = 0
234                 self.ss_bit = self.ss_start = self.samplenum
235             elif self.state == 'ADDRESS':
236                 self.handle_bit(b)
237                 if self.count == 8:
238                     self.state = 'ADDRESS#' if self.data_ok() else 'IDLE'
239             elif self.state == 'ADDRESS#':
240                 self.handle_bit(b)
241                 if self.count == 16:
242                     self.state = 'COMMAND' if self.data_ok() else 'IDLE'
243             elif self.state == 'COMMAND':
244                 self.handle_bit(b)
245                 if self.count == 8:
246                     self.state = 'COMMAND#' if self.data_ok() else 'IDLE'
247             elif self.state == 'COMMAND#':
248                 self.handle_bit(b)
249                 if self.count == 16:
250                     self.state = 'STOP' if self.data_ok() else 'IDLE'
251             elif self.state == 'STOP':
252                 self.putstop(self.ss_bit)
253                 self.putremote()
254                 self.ss_bit = self.ss_start = self.samplenum
255                 self.state = 'IDLE'