summaryrefslogtreecommitdiff
path: root/decoders/ir_rc5/pd.py
blob: 0b39e709698f935610fa30d475b35c42b8ee0ff4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Uwe Hermann <uwe@hermann-uwe.de>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##

import sigrokdecode as srd
from .lists import *

class SamplerateError(Exception):
    pass

class Decoder(srd.Decoder):
    api_version = 3
    id = 'ir_rc5'
    name = 'IR RC-5'
    longname = 'IR RC-5'
    desc = 'RC-5 infrared remote control protocol.'
    license = 'gplv2+'
    inputs = ['logic']
    outputs = ['ir_rc5']
    channels = (
        {'id': 'ir', 'name': 'IR', 'desc': 'IR data line'},
    )
    options = (
        {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
            'values': ('active-low', 'active-high')},
        {'id': 'protocol', 'desc': 'Protocol type', 'default': 'standard',
            'values': ('standard', 'extended')},
    )
    annotations = (
        ('bit', 'Bit'),
        ('startbit1', 'Startbit 1'),
        ('startbit2', 'Startbit 2'),
        ('togglebit-0', 'Toggle bit 0'),
        ('togglebit-1', 'Toggle bit 1'),
        ('address', 'Address'),
        ('command', 'Command'),
    )
    annotation_rows = (
        ('bits', 'Bits', (0,)),
        ('fields', 'Fields', (1, 2, 3, 4, 5, 6)),
    )

    def __init__(self):
        self.samplerate = None
        self.samplenum = None
        self.edges, self.bits, self.ss_es_bits = [], [], []
        self.state = 'IDLE'

    def start(self):
        self.out_ann = self.register(srd.OUTPUT_ANN)
        self.old_ir = 1 if self.options['polarity'] == 'active-low' else 0

    def metadata(self, key, value):
        if key == srd.SRD_CONF_SAMPLERATE:
            self.samplerate = value
            # One bit: 1.78ms (one half low, one half high).
            self.halfbit = int((self.samplerate * 0.00178) / 2.0)

    def putb(self, bit1, bit2, data):
        ss, es = self.ss_es_bits[bit1][0], self.ss_es_bits[bit2][1]
        self.put(ss, es, self.out_ann, data)

    def handle_bits(self):
        a, c, b = 0, 0, self.bits
        # Individual raw bits.
        for i in range(14):
            if i == 0:
                ss = max(0, self.bits[0][0] - self.halfbit)
            else:
                ss = self.ss_es_bits[i - 1][1]
            es = self.bits[i][0] + self.halfbit
            self.ss_es_bits.append([ss, es])
            self.putb(i, i, [0, ['%d' % self.bits[i][1]]])
        # Bits[0:0]: Startbit 1
        s = ['Startbit1: %d' % b[0][1], 'SB1: %d' % b[0][1], 'SB1', 'S1', 'S']
        self.putb(0, 0, [1, s])
        # Bits[1:1]: Startbit 2
        ann_idx = 2
        s = ['Startbit2: %d' % b[1][1], 'SB2: %d' % b[1][1], 'SB2', 'S2', 'S']
        if self.options['protocol'] == 'extended':
            s = ['CMD[6]#: %d' % b[1][1], 'C6#: %d' % b[1][1], 'C6#', 'C#', 'C']
            ann_idx = 6
        self.putb(1, 1, [ann_idx, s])
        # Bits[2:2]: Toggle bit
        s = ['Togglebit: %d' % b[2][1], 'Toggle: %d' % b[2][1],
             'TB: %d' % b[2][1], 'TB', 'T']
        self.putb(2, 2, [3 if b[2][1] == 0 else 4, s])
        # Bits[3:7]: Address (MSB-first)
        for i in range(5):
            a |= (b[3 + i][1] << (4 - i))
        x = system.get(a, ['Unknown', 'Unk'])
        s = ['Address: %d (%s)' % (a, x[0]), 'Addr: %d (%s)' % (a, x[1]),
             'Addr: %d' % a, 'A: %d' % a, 'A']
        self.putb(3, 7, [5, s])
        # Bits[8:13]: Command (MSB-first)
        for i in range(6):
            c |= (b[8 + i][1] << (5 - i))
        if self.options['protocol'] == 'extended':
            inverted_bit6 = 1 if b[1][1] == 0 else 0
            c |= (inverted_bit6 << 6)
        cmd_type = 'VCR' if x[1] in ('VCR1', 'VCR2') else 'TV'
        x = command[cmd_type].get(c, ['Unknown', 'Unk'])
        s = ['Command: %d (%s)' % (c, x[0]), 'Cmd: %d (%s)' % (c, x[1]),
             'Cmd: %d' % c, 'C: %d' % c, 'C']
        self.putb(8, 13, [6, s])

    def edge_type(self):
        # Categorize according to distance from last edge (short/long).
        distance = self.samplenum - self.edges[-1]
        s, l, margin = self.halfbit, self.halfbit * 2, int(self.halfbit / 2)
        if distance in range(l - margin, l + margin + 1):
            return 'l'
        elif distance in range(s - margin, s + margin + 1):
            return 's'
        else:
            return 'e' # Error, invalid edge distance.

    def reset_decoder_state(self):
        self.edges, self.bits, self.ss_es_bits = [], [], []
        self.state = 'IDLE'

    def decode(self):
        if not self.samplerate:
            raise SamplerateError('Cannot decode without samplerate.')
        while True:

            (self.ir,) = self.wait({'skip': 1})

            # Wait for any edge (rising or falling).
            if self.old_ir == self.ir:
                continue

            # State machine.
            if self.state == 'IDLE':
                self.edges.append(self.samplenum)
                self.bits.append([self.samplenum, 1])
                self.state = 'MID1'
                self.old_ir = self.ir
                continue
            edge = self.edge_type()
            if edge == 'e':
                self.reset_decoder_state() # Reset state machine upon errors.
                continue
            if self.state == 'MID1':
                self.state = 'START1' if edge == 's' else 'MID0'
                bit = None if edge == 's' else 0
            elif self.state == 'MID0':
                self.state = 'START0' if edge == 's' else 'MID1'
                bit = None if edge == 's' else 1
            elif self.state == 'START1':
                if edge == 's':
                    self.state = 'MID1'
                bit = 1 if edge == 's' else None
            elif self.state == 'START0':
                if edge == 's':
                    self.state = 'MID0'
                bit = 0 if edge == 's' else None

            self.edges.append(self.samplenum)
            if bit is not None:
                self.bits.append([self.samplenum, bit])

            if len(self.bits) == 14:
                self.handle_bits()
                self.reset_decoder_state()

            self.old_ir = self.ir