]> sigrok.org Git - libsigrokdecode.git/blob - decoders/nrf24l01/pd.py
2337d4b6d01faed86c778e4b49ff89cbdebb9b4b
[libsigrokdecode.git] / decoders / nrf24l01 / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2014 Jens Steinhauser <jens.steinhauser@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, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 ##
20
21 import sigrokdecode as srd
22
23 class ChannelError(Exception):
24     pass
25
26 regs = {
27 #   addr: ('name',        size)
28     0x00: ('CONFIG',      1),
29     0x01: ('EN_AA',       1),
30     0x02: ('EN_RXADDR',   1),
31     0x03: ('SETUP_AW',    1),
32     0x04: ('SETUP_RETR',  1),
33     0x05: ('RF_CH',       1),
34     0x06: ('RF_SETUP',    1),
35     0x07: ('STATUS',      1),
36     0x08: ('OBSERVE_TX',  1),
37     0x09: ('RPD',         1),
38     0x0a: ('RX_ADDR_P0',  5),
39     0x0b: ('RX_ADDR_P1',  5),
40     0x0c: ('RX_ADDR_P2',  1),
41     0x0d: ('RX_ADDR_P3',  1),
42     0x0e: ('RX_ADDR_P4',  1),
43     0x0f: ('RX_ADDR_P5',  1),
44     0x10: ('TX_ADDR',     5),
45     0x11: ('RX_PW_P0',    1),
46     0x12: ('RX_PW_P1',    1),
47     0x13: ('RX_PW_P2',    1),
48     0x14: ('RX_PW_P3',    1),
49     0x15: ('RX_PW_P4',    1),
50     0x16: ('RX_PW_P5',    1),
51     0x17: ('FIFO_STATUS', 1),
52     0x1c: ('DYNPD',       1),
53     0x1d: ('FEATURE',     1),
54 }
55
56 xn297_regs = {
57     0x19: ('DEMOD_CAL',   5),
58     0x1e: ('RF_CAL',      7),
59     0x1f: ('BB_CAL',      5),
60 }
61
62 class Decoder(srd.Decoder):
63     api_version = 2
64     id = 'nrf24l01'
65     name = 'nRF24L01(+)'
66     longname = 'Nordic Semiconductor nRF24L01/nRF24L01+'
67     desc = '2.4GHz transceiver chip.'
68     license = 'gplv2+'
69     inputs = ['spi']
70     outputs = ['nrf24l01']
71     options = (
72         {'id': 'chip', 'desc': 'Chip type',
73             'default': 'nrf24l01', 'values': ('nrf24l01', 'xn297')},
74     )
75     annotations = (
76         # Sent from the host to the chip.
77         ('cmd', 'Commands sent to the device'),
78         ('tx-data', 'Payload sent to the device'),
79
80         # Returned by the chip.
81         ('register', 'Registers read from the device'),
82         ('rx-data', 'Payload read from the device'),
83
84         ('warning', 'Warnings'),
85     )
86     ann_cmd = 0
87     ann_tx = 1
88     ann_reg = 2
89     ann_rx = 3
90     ann_warn = 4
91     annotation_rows = (
92         ('commands', 'Commands', (ann_cmd, ann_tx)),
93         ('responses', 'Responses', (ann_reg, ann_rx)),
94         ('warnings', 'Warnings', (ann_warn,)),
95     )
96
97     def __init__(self, **kwargs):
98         self.next()
99         self.requirements_met = True
100         self.cs_was_released = False
101
102     def start(self):
103         self.out_ann = self.register(srd.OUTPUT_ANN)
104         if self.options['chip'] == 'xn297':
105             regs.update(xn297_regs)
106
107     def warn(self, pos, msg):
108         '''Put a warning message 'msg' at 'pos'.'''
109         self.put(pos[0], pos[1], self.out_ann, [self.ann_warn, [msg]])
110
111     def putp(self, pos, ann, msg):
112         '''Put an annotation message 'msg' at 'pos'.'''
113         self.put(pos[0], pos[1], self.out_ann, [ann, [msg]])
114
115     def next(self):
116         '''Resets the decoder after a complete command was decoded.'''
117         # 'True' for the first byte after CS went low.
118         self.first = True
119
120         # The current command, and the minimum and maximum number
121         # of data bytes to follow.
122         self.cmd = None
123         self.min = 0
124         self.max = 0
125
126         # Used to collect the bytes after the command byte
127         # (and the start/end sample number).
128         self.mb = []
129         self.mb_s = -1
130         self.mb_e = -1
131
132     def mosi_bytes(self):
133         '''Returns the collected MOSI bytes of a multi byte command.'''
134         return [b[0] for b in self.mb]
135
136     def miso_bytes(self):
137         '''Returns the collected MISO bytes of a multi byte command.'''
138         return [b[1] for b in self.mb]
139
140     def decode_command(self, pos, b):
141         '''Decodes the command byte 'b' at position 'pos' and prepares
142         the decoding of the following data bytes.'''
143         c = self.parse_command(b)
144         if c is None:
145             self.warn(pos, 'unknown command')
146             return
147
148         self.cmd, self.dat, self.min, self.max = c
149
150         if self.cmd in ('W_REGISTER', 'ACTIVATE'):
151             # Don't output anything now, the command is merged with
152             # the data bytes following it.
153             self.mb_s = pos[0]
154         else:
155             self.putp(pos, self.ann_cmd, self.format_command())
156
157     def format_command(self):
158         '''Returns the label for the current command.'''
159         if self.cmd == 'R_REGISTER':
160             reg = regs[self.dat][0] if self.dat in regs else 'unknown register'
161             return 'Cmd R_REGISTER "{}"'.format(reg)
162         else:
163             return 'Cmd {}'.format(self.cmd)
164
165     def parse_command(self, b):
166         '''Parses the command byte.
167
168         Returns a tuple consisting of:
169         - the name of the command
170         - additional data needed to dissect the following bytes
171         - minimum number of following bytes
172         - maximum number of following bytes
173         '''
174
175         if (b & 0xe0) in (0b00000000, 0b00100000):
176             c = 'R_REGISTER' if not (b & 0xe0) else 'W_REGISTER'
177             d = b & 0x1f
178             m = regs[d][1] if d in regs else 1
179             return (c, d, 1, m)
180         if b == 0b01010000:
181             # nRF24L01 only
182             return ('ACTIVATE', None, 1, 1)
183         if b == 0b01100001:
184             return ('R_RX_PAYLOAD', None, 1, 32)
185         if b == 0b01100000:
186             return ('R_RX_PL_WID', None, 1, 1)
187         if b == 0b10100000:
188             return ('W_TX_PAYLOAD', None, 1, 32)
189         if b == 0b10110000:
190             return ('W_TX_PAYLOAD_NOACK', None, 1, 32)
191         if (b & 0xf8) == 0b10101000:
192             return ('W_ACK_PAYLOAD', b & 0x07, 1, 32)
193         if b == 0b11100001:
194             return ('FLUSH_TX', None, 0, 0)
195         if b == 0b11100010:
196             return ('FLUSH_RX', None, 0, 0)
197         if b == 0b11100011:
198             return ('REUSE_TX_PL', None, 0, 0)
199         if b == 0b11111111:
200             return ('NOP', None, 0, 0)
201
202     def decode_register(self, pos, ann, regid, data):
203         '''Decodes a register.
204
205         pos   -- start and end sample numbers of the register
206         ann   -- is the annotation number that is used to output the register.
207         regid -- may be either an integer used as a key for the 'regs'
208                  dictionary, or a string directly containing a register name.'
209         data  -- is the register content.
210         '''
211
212         if type(regid) == int:
213             # Get the name of the register.
214             if regid not in regs:
215                 self.warn(pos, 'unknown register')
216                 return
217             name = regs[regid][0]
218         else:
219             name = regid
220
221         # Multi byte register come LSByte first.
222         data = reversed(data)
223
224         if self.cmd == 'W_REGISTER' and ann == self.ann_cmd:
225             # The 'W_REGISTER' command is merged with the following byte(s).
226             label = '{}: {}'.format(self.format_command(), name)
227         else:
228             label = 'Reg {}'.format(name)
229
230         self.decode_mb_data(pos, ann, data, label, True)
231
232     def decode_mb_data(self, pos, ann, data, label, always_hex):
233         '''Decodes the data bytes 'data' of a multibyte command at position
234         'pos'. The decoded data is prefixed with 'label'. If 'always_hex' is
235         True, all bytes are decoded as hex codes, otherwise only non
236         printable characters are escaped.'''
237
238         if always_hex:
239             def escape(b):
240                 return '{:02X}'.format(b)
241         else:
242             def escape(b):
243                 c = chr(b)
244                 if not str.isprintable(c):
245                     return '\\x{:02X}'.format(b)
246                 return c
247
248         data = ''.join([escape(b) for b in data])
249         text = '{} = "{}"'.format(label, data)
250         self.putp(pos, ann, text)
251
252     def finish_command(self, pos):
253         '''Decodes the remaining data bytes at position 'pos'.'''
254
255         if self.cmd == 'R_REGISTER':
256             self.decode_register(pos, self.ann_reg,
257                                  self.dat, self.miso_bytes())
258         elif self.cmd == 'W_REGISTER':
259             self.decode_register(pos, self.ann_cmd,
260                                  self.dat, self.mosi_bytes())
261         elif self.cmd == 'R_RX_PAYLOAD':
262             self.decode_mb_data(pos, self.ann_rx,
263                                 self.miso_bytes(), 'RX payload', False)
264         elif (self.cmd == 'W_TX_PAYLOAD' or
265               self.cmd == 'W_TX_PAYLOAD_NOACK'):
266             self.decode_mb_data(pos, self.ann_tx,
267                                 self.mosi_bytes(), 'TX payload', False)
268         elif self.cmd == 'W_ACK_PAYLOAD':
269             lbl = 'ACK payload for pipe {}'.format(self.dat)
270             self.decode_mb_data(pos, self.ann_tx,
271                                 self.mosi_bytes(), lbl, False)
272         elif self.cmd == 'R_RX_PL_WID':
273             msg = 'Payload width = {}'.format(self.mb[0][1])
274             self.putp(pos, self.ann_reg, msg)
275         elif self.cmd == 'ACTIVATE':
276             self.putp(pos, self.ann_cmd, self.format_command())
277             if self.mosi_bytes()[0] != 0x73:
278                 self.warn(pos, 'wrong data for "ACTIVATE" command')
279
280     def decode(self, ss, es, data):
281         if not self.requirements_met:
282             return
283
284         ptype, data1, data2 = data
285
286         if ptype == 'CS-CHANGE':
287             if data1 is None:
288                 if data2 is None:
289                     self.requirements_met = False
290                     raise ChannelError('CS# pin required.')
291                 elif data2 == 1:
292                     self.cs_was_released = True
293
294             if data1 == 0 and data2 == 1:
295                 # Rising edge, the complete command is transmitted, process
296                 # the bytes that were send after the command byte.
297                 if self.cmd:
298                     # Check if we got the minimum number of data bytes
299                     # after the command byte.
300                     if len(self.mb) < self.min:
301                         self.warn((ss, ss), 'missing data bytes')
302                     elif self.mb:
303                         self.finish_command((self.mb_s, self.mb_e))
304
305                 self.next()
306                 self.cs_was_released = True
307         elif ptype == 'DATA' and self.cs_was_released:
308             mosi, miso = data1, data2
309             pos = (ss, es)
310
311             if miso is None or mosi is None:
312                 self.requirements_met = False
313                 raise ChannelError('Both MISO and MOSI pins required.')
314
315             if self.first:
316                 self.first = False
317                 # First MOSI byte is always the command.
318                 self.decode_command(pos, mosi)
319                 # First MISO byte is always the status register.
320                 self.decode_register(pos, self.ann_reg, 'STATUS', [miso])
321             else:
322                 if not self.cmd or len(self.mb) >= self.max:
323                     self.warn(pos, 'excess byte')
324                 else:
325                     # Collect the bytes after the command byte.
326                     if self.mb_s == -1:
327                         self.mb_s = ss
328                     self.mb_e = es
329                     self.mb.append((mosi, miso))