]> sigrok.org Git - libsigrokdecode.git/blob - decoders/cc1101/pd.py
cc1101: Use namedtuple to increase readability a bit.
[libsigrokdecode.git] / decoders / cc1101 / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2019 Marco Geisler <m-sigrok@mageis.de>
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 collections import namedtuple
22 from .lists import *
23
24 ANN_STROBE, ANN_SINGLE_READ, ANN_SINGLE_WRITE, ANN_BURST_READ, \
25     ANN_BURST_WRITE, ANN_STATUS_READ, ANN_STATUS, ANN_WARN = range(8)
26
27 Pos = namedtuple('Pos', ['ss', 'es'])
28 Data = namedtuple('Data', ['mosi', 'miso'])
29
30 class Decoder(srd.Decoder):
31     api_version = 3
32     id = 'cc1101'
33     name = 'CC1101'
34     longname = 'Texas Instruments CC1101'
35     desc = 'Low-power sub-1GHz RF transceiver chip.'
36     license = 'gplv2+'
37     inputs = ['spi']
38     outputs = []
39     tags = ['IC', 'Wireless/RF']
40     annotations = (
41         ('strobe', 'Command strobe'),
42         ('single_read', 'Single register read'),
43         ('single_write', 'Single register write'),
44         ('burst_read', 'Burst register read'),
45         ('burst_write', 'Burst register write'),
46         ('status', 'Status register'),
47         ('warning', 'Warning'),
48     )
49     annotation_rows = (
50         ('cmd', 'Commands', (ANN_STROBE,)),
51         ('data', 'Data', (ANN_SINGLE_READ, ANN_SINGLE_WRITE, ANN_BURST_READ,
52                             ANN_BURST_WRITE, ANN_STATUS_READ)),
53         ('status', 'Status register', (ANN_STATUS,)),
54         ('warnings', 'Warnings', (ANN_WARN,)),
55     )
56
57     def __init__(self):
58         self.reset()
59
60     def reset(self):
61         self.next()
62         self.requirements_met = True
63         self.cs_was_released = False
64
65     def start(self):
66         self.out_ann = self.register(srd.OUTPUT_ANN)
67
68     def warn(self, pos, msg):
69         '''Put a warning message 'msg' at 'pos'.'''
70         self.put(pos.ss, pos.es, self.out_ann, [ANN_WARN, [msg]])
71
72     def putp(self, pos, ann, msg):
73         '''Put an annotation message 'msg' at 'pos'.'''
74         self.put(pos.ss, pos.es, self.out_ann, [ann, [msg]])
75
76     def putp2(self, pos, ann, msg1, msg2):
77         '''Put an annotation message 'msg' at 'pos'.'''
78         self.put(pos.ss, pos.es, self.out_ann, [ann, [msg1, msg2]])
79
80     def next(self):
81         '''Resets the decoder after a complete command was decoded.'''
82         # 'True' for the first byte after CS# went low.
83         self.first = True
84
85         # The current command, and the minimum and maximum number
86         # of data bytes to follow.
87         self.cmd = None
88         self.min = 0
89         self.max = 0
90
91         # Used to collect the bytes after the command byte
92         # (and the start/end sample number).
93         self.mb = []
94         self.ss_mb = -1
95         self.es_mb = -1
96
97     def mosi_bytes(self):
98         '''Returns the collected MOSI bytes of a multi byte command.'''
99         return [b.mosi for b in self.mb]
100
101     def miso_bytes(self):
102         '''Returns the collected MISO bytes of a multi byte command.'''
103         return [b.miso for b in self.mb]
104
105     def decode_command(self, pos, b):
106         '''Decodes the command byte 'b' at position 'pos' and prepares
107         the decoding of the following data bytes.'''
108         c = self.parse_command(b)
109         if c is None:
110             self.warn(pos, 'unknown command')
111             return
112
113         self.cmd, self.dat, self.min, self.max = c
114
115         if self.cmd == 'Strobe':
116             self.putp(pos, ANN_STROBE, self.format_command())
117         else:
118             # Don't output anything now, the command is merged with
119             # the data bytes following it.
120             self.ss_mb = pos.ss
121
122     def format_command(self):
123         '''Returns the label for the current command.'''
124         if self.cmd in ('Read', 'Burst read', 'Write', 'Burst write', 'Status read'):
125             return self.cmd
126         if self.cmd == 'Strobe':
127             reg = strobes.get(self.dat, 'unknown strobe')
128             return '{} {}'.format(self.cmd, reg)
129         else:
130             return 'TODO Cmd {}'.format(self.cmd)
131
132     def parse_command(self, b):
133         '''Parses the command byte.
134
135         Returns a tuple consisting of:
136         - the name of the command
137         - additional data needed to dissect the following bytes
138         - minimum number of following bytes
139         - maximum number of following bytes (None for infinite)
140         '''
141
142         addr = b & 0x3F
143         if (addr < 0x30) or (addr == 0x3E) or (addr == 0x3F):
144             if (b & 0xC0) == 0x00:
145                 return ('Write', addr, 1, 1)
146             if (b & 0xC0) == 0x40:
147                 return ('Burst write', addr, 1, 99999)
148             if (b & 0xC0) == 0x80:
149                 return ('Read', addr, 1, 1)
150             if (b & 0xC0) == 0xC0:
151                 return ('Burst read', addr, 1, 99999)
152             else:
153                 self.warn(pos, 'unknown address/command combination')
154         else:
155             if (b & 0x40) == 0x00:
156                 return ('Strobe', addr, 0, 0)
157             if (b & 0xC0) == 0xC0:
158                 return ('Status read', addr, 1, 99999)
159             else:
160                 self.warn(pos, 'unknown address/command combination')
161
162     def decode_reg(self, pos, ann, regid, data):
163         '''Decodes a register.
164
165         pos   -- start and end sample numbers of the register
166         ann   -- the annotation number that is used to output the register.
167         regid -- may be either an integer used as a key for the 'regs'
168                  dictionary, or a string directly containing a register name.'
169         data  -- the register content.
170         '''
171
172         if type(regid) == int:
173             # Get the name of the register.
174             if regid not in regs:
175                 self.warn(pos, 'unknown register')
176                 return
177             name = '{} ({:02X})'.format(regs[regid], regid)
178         else:
179             name = regid
180
181         if regid == 'STATUS' and ann == ANN_STATUS:
182             label = 'Status'
183             self.decode_status_reg(pos, ann, data, label)
184         else:
185             if self.cmd in ('Write', 'Read', 'Status read', 'Burst read', 'Burst write'):
186                 label = '{}: {}'.format(self.format_command(), name)
187             else:
188                 label = 'Reg ({}) {}'.format(self.cmd, name)
189             self.decode_mb_data(pos, ann, data, label)
190
191     def decode_status_reg(self, pos, ann, data, label):
192         '''Decodes the data bytes 'data' of a status register at position
193         'pos'. The decoded data is prefixed with 'label'.'''
194         status = data[0]
195         # bit 7 --> CHIP_RDYn
196         if status & 0b10000000 == 0b10000000:
197             longtext_chiprdy = 'CHIP_RDYn is high! '
198         else:
199             longtext_chiprdy = ''
200         # bits 6:4 --> STATE
201         state = (status & 0x70) >> 4
202         longtext_state = 'STATE is {}, '.format(status_reg_states[state])
203         # bits 3:0 --> FIFO_BYTES_AVAILABLE
204         fifo_bytes = status & 0x0F
205         if self.cmd in ('Single read', 'Status read', 'Burst read'):
206             longtext_fifo = '{} bytes available in RX FIFO'.format(fifo_bytes)
207         else:
208             longtext_fifo = '{} bytes free in TX FIFO'.format(fifo_bytes)
209
210         text = '{} = {:02X}'.format(label, status)
211         longtext = ''.join([text, '; ', longtext_chiprdy, longtext_state, longtext_fifo])
212         self.putp2(pos, ann, longtext, text)
213
214     def decode_mb_data(self, pos, ann, data, label):
215         '''Decodes the data bytes 'data' of a multibyte command at position
216         'pos'. The decoded data is prefixed with 'label'.'''
217
218         def escape(b):
219             return '{:02X}'.format(b)
220
221         data = ' '.join([escape(b) for b in data])
222         text = '{} = {}'.format(label, data)
223         self.putp(pos, ann, text)
224
225     def finish_command(self, pos):
226         '''Decodes the remaining data bytes at position 'pos'.'''
227
228         if self.cmd == 'Write':
229             self.decode_reg(pos, ANN_SINGLE_WRITE, self.dat, self.mosi_bytes())
230         elif self.cmd == 'Burst write':
231             self.decode_reg(pos, ANN_BURST_WRITE, self.dat, self.mosi_bytes())
232         elif self.cmd == 'Read':
233             self.decode_reg(pos, ANN_SINGLE_READ, self.dat, self.miso_bytes())
234         elif self.cmd == 'Burst read':
235             self.decode_reg(pos, ANN_BURST_READ, self.dat, self.miso_bytes())
236         elif self.cmd == 'Strobe':
237             self.decode_reg(pos, ANN_STROBE, self.dat, self.mosi_bytes())
238         elif self.cmd == 'Status read':
239             self.decode_reg(pos, ANN_STATUS_READ, self.dat, self.miso_bytes())
240         else:
241             self.warn(pos, 'unhandled command')
242
243     def decode(self, ss, es, data):
244         if not self.requirements_met:
245             return
246
247         ptype, data1, data2 = data
248
249         if ptype == 'CS-CHANGE':
250             if data1 is None:
251                 if data2 is None:
252                     self.requirements_met = False
253                     raise ChannelError('CS# pin required.')
254                 elif data2 == 1:
255                     self.cs_was_released = True
256
257             if data1 == 0 and data2 == 1:
258                 # Rising edge, the complete command is transmitted, process
259                 # the bytes that were sent after the command byte.
260                 if self.cmd:
261                     # Check if we got the minimum number of data bytes
262                     # after the command byte.
263                     if len(self.mb) < self.min:
264                         self.warn((ss, ss), 'missing data bytes')
265                     elif self.mb:
266                         self.finish_command(Pos(self.ss_mb, self.es_mb))
267
268                 self.next()
269                 self.cs_was_released = True
270
271         elif ptype == 'DATA' and self.cs_was_released:
272             mosi, miso = data1, data2
273             pos = Pos(ss, es)
274
275             if miso is None or mosi is None:
276                 self.requirements_met = False
277                 raise ChannelError('Both MISO and MOSI pins required.')
278
279             if self.first:
280                 self.first = False
281                 # First MOSI byte is always the command.
282                 self.decode_command(pos, mosi)
283                 # First MISO byte is always the status register.
284                 self.decode_reg(pos, ANN_STATUS, 'STATUS', [miso])
285             else:
286                 if not self.cmd or len(self.mb) >= self.max:
287                     self.warn(pos, 'excess byte')
288                 else:
289                     # Collect the bytes after the command byte.
290                     if self.ss_mb == -1:
291                         self.ss_mb = ss
292                     self.es_mb = es
293                     self.mb.append(Data(mosi, miso))