]> sigrok.org Git - libsigrokdecode.git/blame - decoders/cec/pd.py
Add HDMI CEC protocol decoder.
[libsigrokdecode.git] / decoders / cec / pd.py
CommitLineData
fb248c04
JS
1##
2## This file is part of the libsigrokdecode project.
3##
4## Copyright (C) 2018 Jorge Solla Rubiales <jorgesolla@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, see <http://www.gnu.org/licenses/>.
18##
19
20import sigrokdecode as srd
21from .protocoldata import *
22
23# Pulse types
24class Pulse:
25 INVALID, START, ZERO, ONE = range(4)
26
27# Protocol stats
28class Stat:
29 WAIT_START, GET_BITS, WAIT_EOM, WAIT_ACK = range(4)
30
31# Pulse times in milliseconds
32timing = {
33 Pulse.START: {
34 'low': { 'min': 3.5, 'max': 3.9 },
35 'total': { 'min': 4.3, 'max': 4.7 }
36 },
37 Pulse.ZERO: {
38 'low': { 'min': 1.3, 'max': 1.7 },
39 'total': { 'min': 2.05, 'max': 2.75 }
40 },
41 Pulse.ONE: {
42 'low': { 'min': 0.4, 'max': 0.8 },
43 'total': { 'min': 2.05, 'max': 2.75 }
44 }
45}
46
47class ChannelError(Exception):
48 pass
49
50class Decoder(srd.Decoder):
51 api_version = 3
52 id = 'cec'
53 name = 'CEC'
54 longname = 'HDMI-CEC'
55 desc = 'HDMI Consumer Electronics Control (CEC) protocol.'
56 license = 'gplv2+'
57 inputs = ['logic']
58 outputs = ['cec']
59 channels = (
60 {'id': 'cec', 'name': 'CEC', 'desc': 'CEC bus data'},
61 )
62 annotations = (
63 ('st', 'Start'),
64 ('eom-0', 'End of message'),
65 ('eom-1', 'Message continued'),
66 ('nack', 'ACK not set'),
67 ('ack', 'ACK set'),
68 ('bits', 'Bits'),
69 ('bytes', 'Bytes'),
70 ('frames', 'Frames'),
71 ('sections', 'Sections'),
72 ('warnings', 'Warnings')
73 )
74 annotation_rows = (
75 ('bits', 'Bits', (0, 1, 2, 3, 4, 5)),
76 ('bytes', 'Bytes', (6,)),
77 ('frames', 'Frames', (7,)),
78 ('sections', 'Sections', (8,)),
79 ('warnings', 'Warnings', (9,))
80 )
81
82 def __init__(self):
83 self.reset()
84
85 def precalculate(self):
86 # Restrict max length of ACK/NACK labels to 2 BIT pulses.
87 bit_time = timing[Pulse.ZERO]['total']['min']
88 bit_time = bit_time * 2
89 self.max_ack_len_samples = round((bit_time / 1000) * self.samplerate)
90
91 def reset(self):
92 self.stat = Stat.WAIT_START
93 self.samplerate = None
94 self.fall_start = None
95 self.fall_end = None
96 self.rise = None
97 self.reset_frame_vars()
98
99 def reset_frame_vars(self):
100 self.eom = None
101 self.bit_count = 0
102 self.byte_count = 0
103 self.byte = 0
104 self.byte_start = None
105 self.frame_start = None
106 self.frame_end = None
107 self.is_nack = 0
108 self.cmd_bytes = []
109
110 def metadata(self, key, value):
111 if key == srd.SRD_CONF_SAMPLERATE:
112 self.samplerate = value
113 self.precalculate()
114
115 def set_stat(self, stat):
116 self.stat = stat
117
118 def handle_frame(self, is_nack):
119 if self.fall_start is None or self.fall_end is None:
120 return
121
122 i = 0
123 str = ''
124 while i < len(self.cmd_bytes):
125 str += '{:02x}'.format(self.cmd_bytes[i]['val'])
126 if i != (len(self.cmd_bytes) - 1):
127 str += ':'
128 i += 1
129
130 self.put(self.frame_start, self.frame_end, self.out_ann, [7, [str]])
131
132 i = 0
133 operands = 0
134 str = ''
135 while i < len(self.cmd_bytes):
136 if i == 0: # Parse header
137 (src, dst) = decode_header(self.cmd_bytes[i]['val'])
138 str = 'HDR: ' + src + ', ' + dst
139 elif i == 1: # Parse opcode
140 str += ' | OPC: ' + decode_opcode(self.cmd_bytes[i]['val'])
141 else: # Parse operands
142 if operands == 0:
143 str += ' | OPS: '
144 operands += 1
145 str += '0x{:02x}'.format(self.cmd_bytes[i]['val'])
146 if i != len(self.cmd_bytes) - 1:
147 str += ', '
148 i += 1
149
150 # Header only commands are PINGS
151 if i == 1:
152 if self.eom:
153 str += ' | OPC: PING'
154 else:
155 str += ' | OPC: NONE. Aborted cmd'
156
157 # Add extra information (ack of the command from the destination)
158 if is_nack:
159 str += ' | R: NACK'
160 else:
161 str += ' | R: ACK'
162
163 self.put(self.frame_start, self.frame_end, self.out_ann, [8, [str]])
164
165 def process(self):
166 zero_time = ((self.rise - self.fall_start) / self.samplerate) * 1000.0
167 total_time = ((self.fall_end - self.fall_start) / self.samplerate) * 1000.0
168 pulse = Pulse.INVALID
169
170 # VALIDATION: Identify pulse based on length of the low period
171 for key in timing:
172 if zero_time >= timing[key]['low']['min'] and zero_time <= timing[key]['low']['max']:
173 pulse = key
174 break
175
176 # VALIDATION: Invalid pulse
177 if pulse == Pulse.INVALID:
178 self.set_stat(Stat.WAIT_START)
179 self.put(self.fall_start, self.fall_end, self.out_ann, [9, ['Invalid pulse: Wrong timing']])
180 return
181
182 # VALIDATION: If waiting for start, discard everything else
183 if self.stat == Stat.WAIT_START and pulse != Pulse.START:
184 self.put(self.fall_start, self.fall_end, self.out_ann, [9, ['Expected START: BIT found']])
185 return
186
187 # VALIDATION: If waiting for ACK or EOM, only BIT pulses (0/1) are expected
188 if (self.stat == Stat.WAIT_ACK or self.stat == Stat.WAIT_EOM) and pulse == Pulse.START:
189 self.put(self.fall_start, self.fall_end, self.out_ann, [9, ['Expected BIT: START received)']])
190 self.set_stat(Stat.WAIT_START)
191
192 # VALIDATION: ACK bit pulse remains high till the next frame (if any): Validate only min time of the low period
193 if self.stat == Stat.WAIT_ACK and pulse != Pulse.START:
194 if total_time < timing[pulse]['total']['min']:
195 pulse = Pulse.INVALID
196 self.put(self.fall_start, self.fall_end, self.out_ann, [9, ['ACK pulse below minimun time']])
197 self.set_stat(Stat.WAIT_START)
198 return
199
200 # VALIDATION / PING FRAME DETECTION: Initiator doesn't sets the EOM = 1 but stops sending when ack doesn't arrive
201 if self.stat == Stat.GET_BITS and pulse == Pulse.START:
202 # Make sure we received a complete byte to consider it a valid ping
203 if self.bit_count == 0:
204 self.handle_frame(self.is_nack)
205 else:
206 self.put(self.frame_start, self.samplenum, self.out_ann, [9, ['ERROR: Incomplete byte received']])
207
208 # Set wait start so we receive next frame
209 self.set_stat(Stat.WAIT_START)
210
211 # VALIDATION: Check timing of the BIT (0/1) pulse in any other case (not waiting for ACK)
212 if self.stat != Stat.WAIT_ACK and pulse != Pulse.START:
213 if total_time < timing[pulse]['total']['min'] or total_time > timing[pulse]['total']['max']:
214 self.put(self.fall_start, self.fall_end, self.out_ann, [9, ['Bit pulse exceeds total pulse timespan']])
215 pulse = Pulse.INVALID
216 self.set_stat(Stat.WAIT_START)
217 return
218
219 if pulse == Pulse.ZERO:
220 bit = 0
221 elif pulse == Pulse.ONE:
222 bit = 1
223
224 # STATE: WAIT START
225 if self.stat == Stat.WAIT_START:
226 self.set_stat(Stat.GET_BITS)
227 self.reset_frame_vars()
228 self.put(self.fall_start, self.fall_end, self.out_ann, [0, ['ST']])
229
230 # STATE: GET BITS
231 elif self.stat == Stat.GET_BITS:
232 # Reset stats on first bit
233 if self.bit_count == 0:
234 self.byte_start = self.fall_start
235 self.byte = 0
236
237 # If 1st byte of the datagram save its sample num
238 if len(self.cmd_bytes) == 0:
239 self.frame_start = self.fall_start
240
241 self.byte += (bit << (7 - self.bit_count))
242 self.bit_count += 1
243 self.put(self.fall_start, self.fall_end, self.out_ann, [5, [str(bit)]])
244
245 if self.bit_count == 8:
246 self.bit_count = 0
247 self.byte_count += 1
248 self.set_stat(Stat.WAIT_EOM)
249 self.put(self.byte_start, self.samplenum, self.out_ann, [6, ['0x{:02x}'.format(self.byte)]])
250 self.cmd_bytes.append({'st': self.byte_start, 'ed': self.samplenum, 'val': self.byte})
251
252 # STATE: WAIT EOM
253 elif self.stat == Stat.WAIT_EOM:
254 self.eom = bit
255 self.frame_end = self.fall_end
256
257 if self.eom:
258 self.put(self.fall_start, self.fall_end, self.out_ann, [2, ['EOM=Y']])
259 else:
260 self.put(self.fall_start, self.fall_end, self.out_ann, [1, ['EOM=N']])
261
262 self.set_stat(Stat.WAIT_ACK)
263
264 # STATE: WAIT ACK
265 elif self.stat == Stat.WAIT_ACK:
266 # If a frame with broadcast destination is being sent, the ACK is
267 # inverted: a 0 is considered a NACK, therefore we invert the value
268 # of the bit here, so we match the real meaning of it.
269 if (self.cmd_bytes[0]['val'] & 0x0F) == 0x0F:
270 bit = ~bit & 0x01
271
272 if (self.fall_end - self.fall_start) > self.max_ack_len_samples:
273 ann_end = self.fall_start + self.max_ack_len_samples
274 else:
275 ann_end = self.fall_end
276
277 if bit:
278 # Any NACK detected in the frame is enough to consider the
279 # whole frame NACK'd.
280 self.is_nack = 1
281 self.put(self.fall_start, ann_end, self.out_ann, [3, ['NACK']])
282 else:
283 self.put(self.fall_start, ann_end, self.out_ann, [4, ['ACK']])
284
285 # After ACK bit, wait for new datagram or continue reading current
286 # one based on EOM value.
287 if self.eom or self.is_nack:
288 self.set_stat(Stat.WAIT_START)
289 self.handle_frame(self.is_nack)
290 else:
291 self.set_stat(Stat.GET_BITS)
292
293 def start(self):
294 self.out_ann = self.register(srd.OUTPUT_ANN)
295
296 def decode(self):
297 if not self.samplerate:
298 raise SamplerateError('Cannot decode without samplerate.')
299
300 # Wait for first falling edge.
301 self.wait({0: 'f'})
302 self.fall_end = self.samplenum
303
304 while True:
305 self.wait({0: 'r'})
306 self.rise = self.samplenum
307
308 if self.stat == Stat.WAIT_ACK:
309 self.wait([{0: 'f'}, {'skip': self.max_ack_len_samples}])
310 else:
311 self.wait([{0: 'f'}])
312
313 self.fall_start = self.fall_end
314 self.fall_end = self.samplenum
315 self.process()
316
317 # If there was a timeout while waiting for ACK: RESYNC.
318 # Note: This is an expected situation as no new falling edge will
319 # happen until next frame is transmitted.
320 if self.matched == (False, True):
321 self.wait({0: 'f'})
322 self.fall_end = self.samplenum