summaryrefslogtreecommitdiff
path: root/decoders/em4100/pd.py
blob: e1b931e2ded2c8d5225488f8a15bf43a96029a23 (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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2015 Benjamin Larsson <benjamin@southpole.se>
##
## 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 data 2 of the License, or
## (at your option) any later data.
##
## 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, write to the Free Software
## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
##

import sigrokdecode as srd

class SamplerateError(Exception):
    pass

class Decoder(srd.Decoder):
    api_version = 2
    id = 'em4100'
    name = 'EM4100'
    longname = 'RFID EM4100'
    desc = 'EM4100 100-150kHz RFID protocol.'
    license = 'gplv2+'
    inputs = ['logic']
    outputs = ['em4100']
    channels = (
        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
    )
    options = (
        {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-high',
            'values': ('active-low', 'active-high')},
        {'id': 'datarate' , 'desc': 'Data rate', 'default': '64',
            'values': ('64', '32', '16')},
#        {'id': 'coding', 'desc': 'Bit coding', 'default': 'biphase',
#            'values': ('biphase', 'manchester', 'psk')},
        {'id': 'coilfreq', 'desc': 'Coil frequency', 'default': '125000'},
    )
    annotations = (
        ('bit', 'Bit'),
        ('header', 'Header'),
        ('version-customer', 'Version/customer'),
        ('data', 'Data'),
        ('rowparity-ok', 'Row parity OK'),
        ('rowparity-err', 'Row parity error'),
        ('colparity-ok', 'Column parity OK'),
        ('colparity-err', 'Column parity error'),
        ('stopbit', 'Stop bit'),
        ('tag', 'Tag'),
    )
    annotation_rows = (
        ('bits', 'Bits', (0,)),
        ('fields', 'Fields', (1, 2, 3, 4, 5, 6, 7, 8)),
        ('tags', 'Tags', (9,)),
    )

    def __init__(self, **kwargs):
        self.samplerate = None
        self.oldpin = None
        self.last_samplenum = None
        self.lastlast_samplenum = None
        self.last_edge = 0
        self.bit_width = 0
        self.halfbit_limit = 0
        self.oldpp = 0
        self.oldpl = 0
        self.oldsamplenum = 0
        self.last_bit_pos = 0
        self.first_start = 0
        self.first_one = 0
        self.state = 'HEADER'
        self.data = 0
        self.data_bits = 0
        self.data_start = 0
        self.data_parity = 0
        self.payload_cnt = 0
        self.data_col_parity = [0, 0, 0, 0, 0, 0]
        self.col_parity = [0, 0, 0, 0, 0, 0]
        self.tag = 0
        self.all_row_parity_ok = True
        self.col_parity_pos = []

    def metadata(self, key, value):
        if key == srd.SRD_CONF_SAMPLERATE:
            self.samplerate = value
        self.bit_width = (self.samplerate / (int(self.options['coilfreq']))) * int(self.options['datarate'])
        self.halfbit_limit = self.bit_width/2 + self.bit_width/4
        self.polarity = 0 if self.options['polarity'] == 'active-low' else 1

    def start(self):
        self.out_ann = self.register(srd.OUTPUT_ANN)

    def add_bit(self, bit, bit_start, bit_stop):
        if self.state == 'HEADER':
            if bit == 1:
                if self.first_one > 0:
                    self.first_one += 1
                if self.first_one == 9:
                    self.put(int(self.first_start), int(bit_stop), self.out_ann,
                             [1, ['Header', 'Head', 'He', 'H']])
                    self.first_one = 0
                    self.state = 'PAYLOAD'
                    return
                if self.first_one == 0:
                    self.first_one = 1
                    self.first_start = bit_start

            if bit == 0:
                self.first_one = 0
            return

        if self.state == 'PAYLOAD':
            self.payload_cnt += 1
            if self.data_bits == 0:
                self.data_start = bit_start
                self.data = 0
                self.data_parity = 0
            self.data_bits += 1
            if self.data_bits == 5:
                s = 'Version/customer' if self.payload_cnt <= 10 else 'Data'
                c = 2 if self.payload_cnt <= 10 else 3
                self.put(int(self.data_start), int(bit_start), self.out_ann,
                         [c, [s + ': %X' % self.data, '%X' % self.data]])
                s = 'OK' if self.data_parity == bit else 'ERROR'
                c = 4 if s == 'OK' else 5
                if s == 'ERROR':
                    self.all_row_parity_ok = False
                self.put(int(bit_start), int(bit_stop), self.out_ann,
                         [c, ['Row parity: ' + s, 'RP: ' + s, 'RP', 'R']])
                self.tag = (self.tag << 4) | self.data
                self.data_bits = 0
                if self.payload_cnt == 50:
                    self.state = 'TRAILER'
                    self.payload_cnt = 0

            self.data_parity ^= bit
            self.data_col_parity[self.data_bits] ^= bit
            self.data = (self.data << 1) | bit
            return

        if self.state == 'TRAILER':
            self.payload_cnt += 1
            if self.data_bits == 0:
                self.data_start = bit_start
                self.data = 0
                self.data_parity = 0
            self.data_bits += 1
            self.col_parity[self.data_bits] = bit
            self.col_parity_pos.append([int(bit_start), int(bit_stop)])

            if self.data_bits == 5:
                self.put(int(bit_start), int(bit_stop), self.out_ann,
                         [8, ['Stop bit', 'SB', 'S']])

                for i in range(1, 5):
                    s = 'OK' if self.data_col_parity[i] == \
                                self.col_parity[i] else 'ERROR'
                    c = 6 if s == 'OK' else 7
                    self.put(self.col_parity_pos[i - 1][0],
                             self.col_parity_pos[i - 1][1], self.out_ann,
                             [c, ['Column parity %d: %s' % (i, s),
                                  'CP%d: %s' % (i, s), 'CP%d' % i, 'C']])

                # Emit an annotation for valid-looking tags.
                all_col_parity_ok = (self.data_col_parity[1:5] == self.col_parity[1:5])
                if all_col_parity_ok and self.all_row_parity_ok:
                    self.put(int(self.first_start), int(bit_stop), self.out_ann,
                             [9, ['Tag: %010X' % self.tag, 'Tag', 'T']])

                self.tag = 0
                self.data_bits = 0

                if self.payload_cnt == 5:
                    self.state = 'HEADER'
                    self.payload_cnt = 0
                    self.data_col_parity = [0, 0, 0, 0, 0, 0]
                    self.col_parity = [0, 0, 0, 0, 0, 0]
                    self.col_parity_pos = []
                    self.all_row_parity_ok = True

    def putbit(self, bit, bit_start, bit_stop):
        self.put(int(bit_start), int(bit_stop), self.out_ann,
                 [0, [str(bit)]])
        self.add_bit(bit, bit_start, bit_stop)

    def manchester_decode(self, samplenum, pl, pp, pin):
        bit_start = 0
        bit_stop = 0
        bit = self.oldpin ^ self.polarity
        if pl > self.halfbit_limit:
            samples = samplenum - self.oldsamplenum
            t = samples / self.samplerate

            if self.oldpl > self.halfbit_limit:
                bit_start = int(self.oldsamplenum - self.oldpl/2)
                bit_stop = int(samplenum - pl/2)
                self.putbit(bit, bit_start, bit_stop)
            if self.oldpl <= self.halfbit_limit:
                bit_start = int(self.oldsamplenum - self.oldpl)
                bit_stop = int(samplenum - pl/2)
                self.putbit(bit, bit_start, bit_stop)
            self.last_bit_pos = int(samplenum - pl/2)

        if pl < self.halfbit_limit:
            samples = samplenum - self.oldsamplenum
            t = samples / self.samplerate

            if self.oldpl > self.halfbit_limit:
                bit_start = self.oldsamplenum - self.oldpl/2
                bit_stop = int(samplenum)
                self.putbit(bit, bit_start, bit_stop)
                self.last_bit_pos = int(samplenum)
            if self.oldpl <= self.halfbit_limit:
                if self.last_bit_pos <= self.oldsamplenum - self.oldpl:
                    bit_start = self.oldsamplenum - self.oldpl
                    bit_stop = int(samplenum)
                    self.putbit(bit, bit_start, bit_stop)
                    self.last_bit_pos = int(samplenum)

    def decode(self, ss, es, data):
        if not self.samplerate:
            raise SamplerateError('Cannot decode without samplerate.')
        for (samplenum, (pin,)) in data:
            # Ignore identical samples early on (for performance reasons).
            if self.oldpin == pin:
                continue

            if self.oldpin is None:
                self.oldpin = pin
                self.last_samplenum = samplenum
                self.lastlast_samplenum = samplenum
                self.last_edge = samplenum
                self.oldpl = 0
                self.oldpp = 0
                self.oldsamplenum = 0
                self.last_bit_pos = 0
                continue

            if self.oldpin != pin:
                pl = samplenum - self.oldsamplenum
                pp = pin

                self.manchester_decode(samplenum, pl, pp, pin)

                self.oldpl = pl
                self.oldpp = pp
                self.oldsamplenum = samplenum
                self.oldpin = pin