]> sigrok.org Git - libsigrokdecode.git/blob - decoders/lin/pd.py
add LIN protocol decoder
[libsigrokdecode.git] / decoders / lin / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2018 Stephan Thiele <stephan.thiele@mailbox.org>
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
22 class LinFsm:
23     class State:
24         WaitForBreak = 'WAIT FOR BREAK'
25         Sync = 'SYNC'
26         Pid = 'PID'
27         Data = 'DATA'
28         Checksum = 'CHECKSUM'
29         Error = 'ERROR'
30
31     def transit(self, target_state):
32         if not self._transition_allowed(target_state):
33             return False
34         self.state = target_state
35         return True
36
37     def _transition_allowed(self, target_state):
38         if target_state == LinFsm.State.Error:
39             return True
40         for s in self.allowed_state[self.state]:
41             if s == target_state:
42                 return True
43         return False
44
45     def reset(self):
46         self.state = LinFsm.State.WaitForBreak
47
48     def __init__(self):
49         self.allowed_state = dict()
50         self.allowed_state[LinFsm.State.WaitForBreak] = (LinFsm.State.Sync,)
51         self.allowed_state[LinFsm.State.Sync]         = (LinFsm.State.Pid,)
52         self.allowed_state[LinFsm.State.Pid]          = (LinFsm.State.Data,)
53         self.allowed_state[LinFsm.State.Data]         = (LinFsm.State.Data, LinFsm.State.Checksum)
54         self.allowed_state[LinFsm.State.Checksum]     = (LinFsm.State.WaitForBreak,)
55         self.allowed_state[LinFsm.State.Error]        = (LinFsm.State.Sync,)
56
57         self.state = None
58         self.reset()
59
60 class Decoder(srd.Decoder):
61     api_version = 3
62     id = 'lin'
63     name = 'LIN'
64     longname = 'Local Interconnect Network'
65     desc = 'Local Interconnect Network (LIN) protocol.'
66     license = 'gplv2+'
67     inputs = ['uart']
68     outputs = ['lin']
69     options = (
70         {'id': 'version', 'desc': 'Protocol version', 'default': 2, 'values': (1, 2)},
71     )
72     annotations = (
73         ('data', 'LIN data'),
74         ('control', 'Protocol info'),
75         ('error', 'Error descriptions'),
76         ('inline_error', 'Protocol violations and errors'),
77     )
78     annotation_rows = (
79         ('data', 'Data', (0, 1, 3)),
80         ('error', 'Error', (2,)),
81     )
82
83     def __init__(self):
84         self.reset()
85
86     def reset(self):
87         self.fsm = LinFsm()
88         self.lin_header = []
89         self.lin_rsp = []
90         self.lin_version = None
91         self.out_ann = None
92         self.ss_block = None
93         self.es_block = None
94
95     def start(self):
96         self.out_ann = self.register(srd.OUTPUT_ANN)
97         self.lin_version = self.options['version']
98
99     def putx(self, data):
100         self.put(self.ss_block, self.es_block, self.out_ann, data)
101
102     def wipe_break_null_byte(self, value):
103         # Upon a break condition a null byte is received which must be ignored.
104         if self.fsm.state != LinFsm.State.WaitForBreak and self.fsm.state != LinFsm.State.Error:
105             if len(self.lin_rsp):
106                 value = self.lin_rsp.pop()[2]
107             else:
108                 self.lin_header.pop()
109
110         if value != 0:
111             self.fsm.transit(LinFsm.State.Error)
112             self.handle_error()
113             return False
114
115         return True
116
117     def handle_wait_for_break(self, value):
118         self.wipe_break_null_byte(value)
119
120     def handle_break(self, value):
121         if self.fsm.state != LinFsm.State.WaitForBreak and self.fsm.state != LinFsm.State.Error:
122             if self.wipe_break_null_byte(value):
123                 self.fsm.transit(LinFsm.State.Checksum)
124                 self.handle_checksum()
125
126         self.fsm.reset()
127         self.fsm.transit(LinFsm.State.Sync)
128
129         data = [1, ['Break condition', 'Break', 'Brk', 'B']]
130         self.put(self.ss_block, self.es_block, self.out_ann, data)
131
132     def handle_sync(self, value):
133         self.fsm.transit(LinFsm.State.Pid)
134         self.lin_header.append((self.ss_block, self.es_block, value))
135
136     def handle_pid(self, value):
137         self.fsm.transit(LinFsm.State.Data)
138         self.lin_header.append((self.ss_block, self.es_block, value))
139
140     def handle_data(self, value):
141         self.lin_rsp.append((self.ss_block, self.es_block, value))
142
143     def handle_checksum(self):
144         sync = self.lin_header.pop(0) if len(self.lin_header) else None
145
146         self.put(sync[0], sync[1], self.out_ann, [0, ['Sync', 'S']])
147
148         if sync[2] != 0x55:
149             self.put(sync[0], sync[1], self.out_ann,
150                      [2, ['Sync is not 0x55', 'Not 0x55', '!= 0x55']])
151
152         pid = self.lin_header.pop(0) if len(self.lin_header) else None
153         checksum = self.lin_rsp.pop() if len(self.lin_rsp) else None
154
155         if pid:
156             id = pid[2] & 0x3F
157             parity = pid[2] >> 6
158
159             expected_parity = self.calc_parity(pid[2])
160             parity_valid = parity == expected_parity
161
162             if not parity_valid:
163                 self.put(pid[0], pid[1], self.out_ann, [2, ['P != %d' % expected_parity]])
164
165             ann_class = 0 if parity_valid else 3
166             self.put(pid[0], pid[1], self.out_ann, [ann_class, [
167                 'ID: %02X Parity: %d (%s)' % (id, parity, 'ok' if parity_valid else 'bad'),
168                 'ID: 0x%02X' % id, 'I: %d' % id
169             ]])
170
171         if len(self.lin_rsp):
172             checksum_valid = self.checksum_is_valid(pid[2], self.lin_rsp, checksum[2])
173
174             for b in self.lin_rsp:
175                 self.put(b[0], b[1], self.out_ann, [0, ['Data: 0x%02X' % b[2], 'D: 0x%02X' % b[2]]])
176
177             ann_class = 0 if checksum_valid else 3
178             self.put(checksum[0], checksum[1], self.out_ann,
179                  [ann_class, ['Checksum: 0x%02X' % checksum[2], 'Checksum', 'Chk', 'C']])
180
181             if not checksum_valid:
182                 self.put(checksum[0], checksum[1], self.out_ann, [2, ['Checksum invalid']])
183         else:
184             pass # No response.
185
186         self.lin_header.clear()
187         self.lin_rsp.clear()
188
189     def handle_error(self):
190         self.putx([3, ['Error', 'Err', 'E']])
191
192     def checksum_is_valid(self, pid, data, checksum):
193         if self.lin_version == 2:
194             id = pid & 0x3F
195
196             if id != 60 and id != 61:
197                 checksum += pid
198
199         for d in data:
200             checksum += d[2]
201
202         carry_bits = int(checksum / 256)
203         checksum += carry_bits
204
205         return checksum & 0xFF == 0xFF
206
207     @staticmethod
208     def calc_parity(pid):
209         id = [((pid & 0x3F) >> i) & 1 for i in range(8)]
210
211         p0 = id[0] ^ id[1] ^ id[2] ^ id[4]
212         p1 = not (id[1] ^ id[3] ^ id[4] ^ id[5])
213
214         return (p0 << 0) | (p1 << 1)
215
216     def decode(self, ss, es, data):
217         ptype, rxtx, pdata = data
218
219         self.ss_block, self.es_block = ss, es
220
221         # Ignore all UART packets except the actual data packets or BREAK.
222         if ptype == 'BREAK':
223             self.handle_break(pdata)
224         if ptype != 'DATA':
225             return
226
227         # We're only interested in the byte value (not individual bits).
228         pdata = pdata[0]
229
230         # Short LIN overview:
231         #  - Message begins with a BREAK (0x00) for at least 13 bittimes.
232         #  - Break is always followed by a SYNC byte (0x55).
233         #  - Sync byte is followed by a PID byte (Protected Identifier).
234         #  - PID byte is followed by 1 - 8 data bytes and a final checksum byte.
235
236         if   self.fsm.state == LinFsm.State.Error:        self.handle_error()
237         elif self.fsm.state == LinFsm.State.WaitForBreak: self.handle_wait_for_break(pdata)
238         elif self.fsm.state == LinFsm.State.Sync:         self.handle_sync(pdata)
239         elif self.fsm.state == LinFsm.State.Pid:          self.handle_pid(pdata)
240         elif self.fsm.state == LinFsm.State.Data:         self.handle_data(pdata)
241         elif self.fsm.state == LinFsm.State.Checksum:     self.handle_checksum()