forked from DreamSourceLab/DSView
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecoder.py
More file actions
435 lines (398 loc) · 14.1 KB
/
decoder.py
File metadata and controls
435 lines (398 loc) · 14.1 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
try:
import sigrokdecode
except ModuleNotFoundError:
class FakeSigrokDecode:
pass
sigrokdecode = FakeSigrokDecode()
setattr(sigrokdecode, "OUTPUT_ANN", 0)
class FakeDecoder:
pass
sigrokdecode.Decoder = FakeDecoder
from dataclasses import dataclass
from typing import List, Dict, Optional
from . import frame
from . import record
import re
def _get_annotation_index(annotations, name):
for index, annotation in enumerate(annotations):
if annotation[0] == name:
return index
raise RuntimeError(f"Unknown annotation {repr(name)}: {repr(annotations)}")
_FRAME_TYPE_DESC: Dict[str, str] = {
frame_class.get_kebab_case_description(): frame_class.DESCRIPTION
for frame_class in frame.Frame.SUBCLASSES + [frame.Frame]
}
_ANNOTATIONS = (
("sync", "Sync"),
("frame-start", "Frame Start"),
("frame-header", "Frame Header"),
("frame-data", "Frame Data"),
("frame-checksum", "Frame Checksum"),
*[(f"frame-type-{id_str}", desc) for id_str, desc in _FRAME_TYPE_DESC.items()],
*[
(f"sender-record-{record_class.__name__.lower()}", record_class.DESCRIPTION)
for record_class in record.Record.DIRECTORY_TO_RECORD.values()
],
("sender-record-unknown", "Unknown Record"),
("sender-warning", "Sender Warning"),
("receiver-xon", "Receiver XON"),
("receiver-xoff", "Receiver XOFF"),
("receiver-ack", "Receiver ACK"),
("receiver-nack", "Receiver NACK"),
("receiver-warning", "Receiver Warning"),
)
class Decoder(sigrokdecode.Decoder):
api_version = 3
id = "casio_digital_diary"
name = "Casio Digital Diary"
longname = "Casio Digital Diary"
desc = "Casio Digital Diary serial communication protocol"
license = "gplv2+"
inputs = ["uart"]
outputs = []
channels = tuple()
optional_channels = tuple()
options = (
{
"id": "sender",
"desc": "Sender of data",
"default": "TX",
"values": ("TX", "RX"),
},
{
"id": "receiver",
"desc": "Receiver of data",
"default": "RX",
"values": ("TX", "RX"),
},
)
annotations = _ANNOTATIONS
annotation_rows = (
(
"sender",
"Sender",
(
_get_annotation_index(annotations, "sync"),
_get_annotation_index(annotations, "frame-start"),
_get_annotation_index(annotations, "frame-header"),
_get_annotation_index(annotations, "frame-data"),
_get_annotation_index(annotations, "frame-checksum"),
),
),
(
"frame",
"Frame",
tuple(
_get_annotation_index(_ANNOTATIONS, f"frame-type-{id_str}")
for id_str in _FRAME_TYPE_DESC.keys()
),
),
(
"record",
"Record",
tuple(
_get_annotation_index(
_ANNOTATIONS, f"sender-record-{record_class.__name__.lower()}"
)
for record_class in record.Record.DIRECTORY_TO_RECORD.values()
)
+ (_get_annotation_index(_ANNOTATIONS, "sender-record-unknown"),),
),
(
"sender-warning",
"Sender Warning",
(_get_annotation_index(annotations, "sender-warning"),),
),
(
"receiver",
"Receiver",
(
_get_annotation_index(annotations, "receiver-xon"),
_get_annotation_index(annotations, "receiver-xoff"),
_get_annotation_index(annotations, "receiver-ack"),
_get_annotation_index(annotations, "receiver-nack"),
),
),
(
"receiver-warning",
"Receiver Warning",
(_get_annotation_index(annotations, "receiver-warning"),),
),
)
binary = tuple()
tags = ["PC"]
_record_state: str
_frame_builder: frame.FrameBuilder
_chunk_startsample: int
##
## Private
##
# Receiver
def _decode_receiver(self, startsample: int, endsample: int, data) -> None:
if data == 0x11:
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "receiver-xon"),
["XON"],
],
)
return
if data == 0x13:
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "receiver-xoff"),
["XOFF"],
],
)
return
if data == 0x23:
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "receiver-ack"),
["Ack"],
],
)
return
if data == 0x3F:
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "receiver-nack"),
["NACK"],
],
)
return
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "receiver-warning"),
["?"],
],
)
# Sender
def _decode_sender_sync_or_frame(
self, startsample: int, endsample: int, data
) -> bool:
# Sync 1/2
if data == ord("\r"):
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "sync"),
["Sync 1/2"],
],
)
self._sender_decode_function = self._decode_sender_sync
return True
# Frame start
if data == ord(":"):
self._frame_startsample = startsample
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "frame-start"),
["Frame Start"],
],
)
self._sender_decode_function = self._decode_sender_frame
return True
return False
def _decode_sender_sync(self, startsample: int, endsample: int, data) -> bool:
if data is ord("\n"):
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "sync"),
["Sync 2/2"],
],
)
self._sender_decode_function = self._decode_sender_sync_or_frame
return True
return False
def _decode_hex(self, data) -> Optional[int]:
if not hasattr(self, "_hex_high_value"):
self._hex_high_value = chr(data)
return None
else:
hex_value = int(self._hex_high_value + chr(data), 16)
delattr(self, "_hex_high_value")
return hex_value
def _decode_record(self, startsample: int, endsample: int, decoded_frame) -> None:
if self._record_state == "directory_or_record":
if isinstance(decoded_frame, frame.Directory):
self._record_state = "start"
self._record_directory_type = type(decoded_frame)
return
else:
self._record_state = "start"
if self._record_state == "start":
self._record_startsample = startsample
self._record_state = "frames"
self._record_frames: List[frame.Frame] = []
if self._record_state == "frames":
if isinstance(decoded_frame, frame.EndOfRecord):
if self._record_directory_type in record.Record.DIRECTORY_TO_RECORD:
record_class = record.Record.DIRECTORY_TO_RECORD[
self._record_directory_type
]
decoded_record = record_class.from_frames(self._record_frames)
decoded_str = str(decoded_record)
annotation = (
f"sender-record-{type(decoded_record).__name__.lower()}"
)
self.put(
self._record_startsample,
endsample,
self.out_ann,
[
_get_annotation_index(
self.annotations,
annotation,
),
[decoded_str],
],
)
else:
decoded_str = "Unknown Record: " + ", ".join(
str(f) for f in self._record_frames
)
annotation = "sender-record-unknown"
self.put(
self._record_startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "sender-warning"),
[decoded_str],
],
)
self._record_state = "directory_or_record"
else:
self._record_frames.append(decoded_frame)
def _decode_sender_frame(self, startsample: int, endsample: int, data) -> bool:
value = self._decode_hex(data)
if value is not None:
(chunk_desc, decoded_frame) = self._frame_builder.add_data(value)
self.put(
self._chunk_startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "frame-header"),
[f"{chunk_desc}: " + hex(value)],
],
)
if decoded_frame is not None:
if not decoded_frame.is_checksum_valid():
self.put(
self._chunk_startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "sender-warning"),
["Bad Checksum"],
],
)
if type(decoded_frame) is frame.Frame:
self.put(
self._frame_startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "sender-warning"),
[f"Unknown {decoded_frame}"],
],
)
else:
self.put(
self._frame_startsample,
endsample,
self.out_ann,
[
_get_annotation_index(
self.annotations,
f"frame-type-{decoded_frame.get_kebab_case_description()}",
),
[repr(str(decoded_frame))[1:-1]],
],
)
self._decode_record(self._frame_startsample, endsample, decoded_frame)
self._frame_builder = frame.FrameBuilder()
self._sender_decode_function = self._decode_sender_sync_or_frame
else:
self._chunk_startsample = startsample
return True
def _decode_sender(self, startsample: int, endsample: int, data) -> None:
if self._sender_decode_function(startsample, endsample, data):
return
# Warning
self.put(
startsample,
endsample,
self.out_ann,
[
_get_annotation_index(self.annotations, "sender-warning"),
["?"],
],
)
self._sender_decode_function = self._decode_sender_sync_or_frame
##
## Public
##
def __init__(self) -> None:
self.reset()
def start(self) -> None:
"""
This function is called before the beginning of the decoding. This is the
place to register() the output types, check the user-supplied PD options for
validity, and so on.
"""
self.out_ann = self.register(sigrokdecode.OUTPUT_ANN)
def reset(self):
"""
This function is called before the beginning of the decoding. This is the
place to reset variables internal to your protocol decoder to their initial
state, such as state machines and counters.
"""
self._sender_decode_function = self._decode_sender_sync_or_frame
self._frame_builder = frame.FrameBuilder()
self._record_state = "directory_or_record"
def decode(self, startsample: int, endsample: int, data) -> None:
"""
In stacked decoders, this is a function that is called by the
libsigrokdecode backend whenever it has a chunk of data for the protocol
decoder to handle.
"""
ptype, rxtx, pdata = data
if ptype != "DATA":
return
datavalue = pdata[0]
if rxtx == 0:
if self.options["sender"] == "RX":
self._decode_sender(startsample, endsample, datavalue)
if self.options["receiver"] == "RX":
self._decode_receiver(startsample, endsample, datavalue)
elif rxtx == 1:
if self.options["sender"] == "TX":
self._decode_sender(startsample, endsample, datavalue)
if self.options["receiver"] == "TX":
self._decode_receiver(startsample, endsample, datavalue)