-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdlp6500.py
2318 lines (1870 loc) · 92.6 KB
/
dlp6500.py
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Control the Light Crafter 6500DLP evaluation module, or other DMD's relying on the DLPC900 controller over USB.
The code is based around the dlp6500 class, which builds the command packets to be sent to the DMD.
Currently, this code only supports Windows. Extensions to Linux can be accomplished by implementing two functions,
_send_raw_packet() and _get_device(). This would likely also require importing a Linux compatible HID module.
Although Texas Instruments has an SDK for this evaluation module (http://www.ti.com/tool/DLP-ALC-LIGHTCRAFTER-SDK),
it is not very well documented, and we had difficulty building it. Further, it is intended to produce a static library
which cannot be used with e.g. python and the ctypes library as a dll could be.
This DMD control code was originally based on refactoring https://github.com/mazurenko/Lightcrafter6500DMDControl.
The combine_patterns() function was inspired by https://github.com/csi-dcsc/Pycrafter6500.
"""
from collections.abc import Sequence
from typing import Union, Optional
import sys
import time
from struct import pack, unpack
import numpy as np
from copy import deepcopy
import datetime
from argparse import ArgumentParser
# for dealing with configuration files
import json
import zarr
from warnings import warn
from pathlib import Path
from numcodecs import packbits
try:
import pywinusb.hid as pyhid
except ImportError:
pyhid = None
warn("pywinusb could not be imported")
##############################################
# compress DMD pattern data
##############################################
def combine_patterns(patterns: np.ndarray,
bit_depth: int = 1):
"""
Given a series of binary patterns, combine these into 24 bit RGB images to send to DMD. For binary patterns,
the DMD supports sending a group of up to 24 patterns as an RGB image, with each bit of the 24 bit
RGB values giving the pattern for one image.
:param patterns: nimgs x ny x nx array of uint8
:param bit_depth: 1
:return combined_patterns:
"""
if bit_depth != 1:
raise NotImplementedError('not implemented')
if not np.all(np.logical_or(patterns == 0, patterns == 1)):
raise ValueError('patterns must be binary')
combined_patterns = []
# determine number of compressed images and create them
n_combined_patterns = int(np.ceil(len(patterns) / 24))
for num_pat in range(n_combined_patterns):
combined_pattern_current = np.zeros((3, patterns.shape[1], patterns.shape[2]), dtype=np.uint8)
for ii in range(np.min([24, len(patterns) - 24*num_pat])):
# first 8 patterns encoded in B byte of color image, next 8 in G, last 8 in R
if ii < 8:
combined_pattern_current[2, :, :] += patterns[ii + 24*num_pat, :, :] * 2**ii
elif ii >= 8 and ii < 16:
combined_pattern_current[1, :, :] += patterns[ii + 24*num_pat, :, :] * 2**(ii-8)
elif ii >= 16 and ii < 24:
combined_pattern_current[0, :, :] += patterns[ii + 24*num_pat, :, :] * 2**(ii-16)
combined_patterns.append(combined_pattern_current)
return combined_patterns
def split_combined_patterns(combined_patterns) -> np.ndarray:
"""
Split binary patterns which have been combined into a single uint8 RGB image back to separate images.
:param combined_patterns: 3 x Ny x Nx uint8 array representing up to 24 combined patterns. Actually
will accept input of arbitrary dimensions as long as first dimension has size 3.
:return: 24 x Ny x Nx array. This will always have a first dimension of size 24 because the number of
zero patterns at the end is ambiguous.
"""
patterns = np.zeros((24,) + combined_patterns.shape[1:], dtype=np.uint8)
for ii in range(8):
patterns[ii] = (combined_patterns[2] & 2**ii) >> ii
for ii in range(8, 16):
patterns[ii] = (combined_patterns[1] & 2 ** (ii-8)) >> (ii-8)
for ii in range(16, 24):
patterns[ii] = (combined_patterns[0] & 2 ** (ii - 16)) >> (ii+8)
return patterns
def encode_erle(pattern: np.ndarray) -> list:
"""
Encode a 24bit pattern in enhanced run length encoding (ERLE).
ERLE is similar to RLE, but now the number of repeats byte is given by either one or two bytes.
specification:
ctrl byte 1, ctrl byte 2, ctrl byte 3, description
0 , 0 , n/a , end of image
0 , 1 , n , copy n pixels from the same position on the previous line
0 , n>1 , n/a , n uncompressed RGB pixels follow
n>1 , n/a , n/a , repeat following pixel n times
:param pattern: uint8 3 x Ny x Nx array of RGB values, or Ny x Nx array
:return pattern_compressed:
"""
# pattern must be uint8
if pattern.dtype != np.uint8:
raise ValueError('pattern must be of type uint8')
# if 2D pattern, expand this to RGB with pattern in B layer and RG=0
if pattern.ndim == 2:
pattern = np.concatenate((np.zeros((1,) + pattern.shape, dtype=np.uint8),
np.zeros((1,) + pattern.shape, dtype=np.uint8),
np.array(pattern[None, :, :], copy=True)), axis=0)
if pattern.ndim != 3 and pattern.shape[0] != 3:
raise ValueError("Image data is wrong shape. Must be 3 x ny x nx, with RGB values in each layer.")
pattern_compressed = []
_, ny, nx = pattern.shape
# todo: not sure if this is allowed to cross row_rgb boundaries? If so, could pattern.ravel() instead of looping
# todo: don't think above suggestion works, but if last n pixels of above row_rgb are same as first n of this one
# todo: then with ERLE encoding I can use \x00\x01 Hex(n). But checking this may not be so easy. Right now
# todo: only implemented if entire rows are the same!
# todo: erle and rle are different enough probably should split apart more
# loop over pattern rows
for ii in range(pattern.shape[1]):
row_rgb = pattern[:, ii, :]
# if this row_rgb is the same as the last row_rgb, can communicate this by sending length of row_rgb
# and then \x00\x01 (copy n pixels from previous line)
# todo: can also do this for shorter sequences than the entire row_rgb
if ii > 0 and np.array_equal(row_rgb, pattern[:, ii - 1, :]):
msb, lsb = erle_len2bytes(nx)
pattern_compressed += [0x00, 0x01, msb, lsb]
else:
# find points along row where pixel value changes
# for RGB image, change happens when ANY pixel value changes
value_changed = np.sum(np.abs(np.diff(row_rgb, axis=1)), axis=0) != 0
# also need to include zero, as this will need to be encoded.
# add one to index to get position of first new value instead of last old value
inds_change = np.concatenate((np.array([0]), np.where(value_changed)[0] + 1))
# get lengths for each repeat, including last one which extends until end of the line
run_lens = np.concatenate((np.array(inds_change[1:] - inds_change[:-1]),
np.array([nx - inds_change[-1]])))
# now build compressed list
for jj, rlen in zip(inds_change, run_lens):
v = row_rgb[:, jj]
length_bytes = erle_len2bytes(rlen)
pattern_compressed += length_bytes + [v[0], v[1], v[2]]
# bytes indicating image end
pattern_compressed += [0x00, 0x01, 0x00]
return pattern_compressed
def encode_rle(pattern: np.ndarray) -> list:
"""
Compress pattern use run length encoding (RLE)
row_rgb length encoding (RLE). Information is encoded as number of repeats
of a given value and values. In RLE the number of repeats is given by a single byte.
e.g. AAABBCCCCD = 3A2B4C1D
The DMD uses a '24bit RGB' encoding scheme, meaning four bits represent each piece of information. The first byte
(i.e. the control byte) gives the length, and the next three give the values for RGB.
The only exceptions occur when the control byte is 0x00, in this case there are several options. If the next byte
is 0x00 this indicates 'end of line', if it is 0x01 this indicates 'end of image', and if it is any other number n,
then this indicates the following 3*n bytes are uncompressed
i.e. \x00 \x03 \xAB\xCD\xEF \x11\x22\x33 \x44\x55\x66 -> \xAB\xCD\xEF \x11\x22\x33 \x44\x55\x66
specification:
ctrl byte 1, color byte, description
0 , 0 , end of line
0 , 1 , end of image (required)
0 , n>=2 , n uncompressed RGB pixels follow
n>0 , n/a , repeat following RGB pixel n times
:param pattern:
:return pattern_compressed:
"""
if pattern.dtype != np.uint8:
raise ValueError('pattern must be of type uint8')
# if 2D pattern, expand this to RGB with pattern in B layer and RG=0
if pattern.ndim == 2:
pattern = np.concatenate((np.zeros((1,) + pattern.shape, dtype=np.uint8),
np.zeros((1,) + pattern.shape, dtype=np.uint8),
np.array(pattern[None, :, :], copy=True)), axis=0)
if pattern.ndim != 3 and pattern.shape[0] != 3:
raise ValueError("Image data is wrong shape. Must be 3 x ny x nx, with RGB values in each layer.")
pattern_compressed = []
_, ny, nx = pattern.shape
# loop over pattern rows
for ii in range(pattern.shape[1]):
row_rgb = pattern[:, ii, :]
# if this row_rgb is the same as the last row_rgb, can communicate this by sending length of row_rgb
# and then \x00\x01 (copy n pixels from previous line)
# todo: can also do this for shorter sequences than the entire row_rgb
if ii > 0 and np.array_equal(row_rgb, pattern[:, ii - 1, :]):
msb, lsb = erle_len2bytes(nx)
pattern_compressed += [0x00, 0x01, msb, lsb]
else:
# find points along row where pixel value changes
# for RGB image, change happens when ANY pixel value changes
value_changed = np.sum(np.abs(np.diff(row_rgb, axis=1)), axis=0) != 0
# also need to include zero, as this will need to be encoded.
# add one to index to get position of first new value instead of last old value
inds_change = np.concatenate((np.array([0]), np.where(value_changed)[0] + 1))
# get lengths for each repeat, including last one which extends until end of the line
run_lens = np.concatenate((np.array(inds_change[1:] - inds_change[:-1]),
np.array([nx - inds_change[-1]])))
# now build compressed list
for jj, rlen in zip(inds_change, run_lens):
v = row_rgb[:, jj]
if rlen <= 255:
pattern_compressed += [rlen, v[0], v[1], v[2]]
else: # if run is longer than one byte, need to break it up
counter = 0
while counter < rlen:
end_pt = np.min([counter + 255, rlen]) - 1
current_len = end_pt - counter + 1
pattern_compressed += [current_len, v[0], v[1], v[2]]
counter = end_pt + 1
# todo: do I need an end of line character?
# todo: is this correct for RLE?
# bytes indicating image end
pattern_compressed += [0x00]
return pattern_compressed
def decode_erle(dmd_size,
pattern_bytes: list):
"""
Decode pattern from ERLE or RLE.
:param dmd_size: [ny, nx]
:param pattern_bytes: list of bytes representing encoded pattern
:return rgb_pattern:
"""
ii = 0 # counter tracking position in compressed byte array
line_no = 0 # counter tracking line number
line_pos = 0 # counter tracking next position to write in line
current_line = np.zeros((3, dmd_size[1]), dtype=np.uint8)
rgb_pattern = np.zeros((3, 0, dmd_size[1]), dtype=np.uint8)
# todo: maybe should rewrite popping everything to avoid dealing with at least one counter?
while ii < len(pattern_bytes):
# reset each new line
if line_pos == dmd_size[1]:
rgb_pattern = np.concatenate((rgb_pattern, current_line[:, None, :]), axis=1)
current_line = np.zeros((3, dmd_size[1]), dtype=np.uint8)
line_pos = 0
line_no += 1
elif line_pos >= dmd_size[1]:
raise ValueError("While reading line %d, length of line exceeded expected value" % line_no)
# end of image denoted by single 0x00 byte
if ii == len(pattern_bytes) - 1:
if pattern_bytes[ii] == 0:
break
else:
raise ValueError('Image not terminated with 0x00')
# control byte of zero indicates special response
if pattern_bytes[ii] == 0:
# end of line
if pattern_bytes[ii + 1] == 0:
ii += 1
continue
# copy bytes from previous lines
elif pattern_bytes[ii + 1] == 1:
if pattern_bytes[ii + 2] < 128:
n_to_copy = pattern_bytes[ii + 2]
ii += 3
else:
n_to_copy = erle_bytes2len(pattern_bytes[ii + 2:ii + 4])
ii += 4
# copy bytes from same position in previous line
current_line[:, line_pos:line_pos + n_to_copy] = \
rgb_pattern[:, line_no-1, line_pos:line_pos + n_to_copy]
line_pos += n_to_copy
# next n bytes unencoded
else:
if pattern_bytes[ii + 1] < 128:
n_unencoded = pattern_bytes[ii + 1]
ii += 2
else:
n_unencoded = erle_bytes2len(pattern_bytes[ii + 1:ii + 3])
ii += 3
for jj in range(n_unencoded):
current_line[0, line_pos + jj] = int(pattern_bytes[ii + 3*jj])
current_line[1, line_pos + jj] = int(pattern_bytes[ii + 3*jj + 1])
current_line[2, line_pos + jj] = int(pattern_bytes[ii + 3*jj + 2])
ii += 3 * n_unencoded
line_pos += n_unencoded
continue
# control byte != 0, regular decoding
# get block len
if pattern_bytes[ii] < 128:
block_len = pattern_bytes[ii]
ii += 1
else:
block_len = erle_bytes2len(pattern_bytes[ii:ii + 2])
ii += 2
# write values to lists for rgb colors
current_line[0, line_pos:line_pos + block_len] = np.asarray([pattern_bytes[ii]] * block_len, dtype=np.uint8)
current_line[1, line_pos:line_pos + block_len] = np.asarray([pattern_bytes[ii + 1]] * block_len, dtype=np.uint8)
current_line[2, line_pos:line_pos + block_len] = np.asarray([pattern_bytes[ii + 2]] * block_len, dtype=np.uint8)
ii += 3
line_pos += block_len
return rgb_pattern
def erle_len2bytes(length: int) -> list:
"""
Encode a length between 0-2**15-1 as 1 or 2 bytes for use in erle encoding format.
Do this in the following way: if length < 128, encode as one byte
If length > 128, then encode as two bits. Create the least significant byte (LSB) as follows: set the most
significant bit as 1 (this is a flag indicating two bytes are being used), then use the least signifcant 7 bits
from length. Construct the most significant byte (MSB) by throwing away the 7 bits already encoded in the LSB.
i.e.
lsb = (length & 0x7F) | 0x80
msb = length >> 7
:param length: integer 0-(2**15-1)
:return len_bytes:
"""
# check input
if isinstance(length, float):
if length.is_integer():
length = int(length)
else:
raise TypeError('length must be convertible to integer.')
if length < 0 or length > 2 ** 15 - 1:
raise ValueError('length is negative or too large to be encoded.')
# main function
if length < 128:
len_bytes = [length]
else:
# i.e. lsb is formed by taking the 7 least significant bits and extending to 8 bits by adding
# a 1 in the msb position
lsb = (length & 0x7F) | 0x80
# second byte obtained by throwing away first 7 bits and keeping what remains
msb = length >> 7
len_bytes = [lsb, msb]
return len_bytes
def erle_bytes2len(byte_list: list) -> int:
"""
Convert a 1 or 2 byte list in little endian order to length
:param list byte_list: [byte] or [lsb, msb]
:return length:
"""
if len(byte_list) == 1:
length = byte_list[0]
else:
lsb, msb = byte_list
length = (msb << 7) + (lsb - 0x80)
return length
##############################################
# firmware configuration
##############################################
def validate_channel_map(cm: dict) -> (bool, str):
"""
check that channel_map is of the correct format
:param cm: dictionary defining channels
:return success, message:
"""
for ch in list(cm.keys()):
modes = list(cm[ch].keys())
if "default" not in modes:
return False, f"'default' not present in channel '{ch:s}'"
for m in modes:
f_inds = cm[ch][m]
if not isinstance(f_inds, (np.ndarray, list)):
return False, f"firmware indices wrong type for channel '{ch:s}', mode '{m:s}'"
if isinstance(f_inds, np.ndarray) and f_inds.ndim != 1:
return False, f"firmware indices array with wrong dimension, '{ch:s}', mode '{m:s}'"
return True, "array validated"
def save_config_file(fname: str,
pattern_data: Sequence[dict],
channel_map: Optional[dict] = None,
firmware_patterns: Optional[np.ndarray] = None,
hid_path: Optional[str] = None,
use_zarr: bool = True):
"""
Save DMD firmware configuration data to zarr or json file
:param fname: file name to save
:param pattern_data: list of dictionary objects, where each dictionary gives information about the corresponding
firmware pattern. The structure of these dictionaries is arbitrary, to support different types of user defined
patterns.
:param channel_map: a dictionary where the top level keys specify a general mode, e.g. "SIM" or "widefield".
channel_map[mode] is a dictionary with entries corresponding to collections of patterns. For example, mode "SIM"
might have pattern collections "blue" and "red". channel_map[mode][channels] is an array of firmware
indices specifying which patterns are displayed using the given mode and channel
>>> channel_map = {"SIM": {"blue": np.arange(9).astype(int),
>>> "red": np.arange(9, 18).astype(int)
>>> }
>>> }
:param firmware_patterns: 3D array of size npatterns x ny x nx
:param hid_path: HID device path allowing the user to address a specific DMD
:param use_zarr: whether to save configuration file as zarr or json
:return:
"""
tstamp = datetime.datetime.now().strftime("%Y_%m_%d_%H;%M;%S")
# ensure no numpy arrays in pattern_data
pattern_data_list = deepcopy(pattern_data)
for p in pattern_data_list:
for k, v in p.items():
if isinstance(v, np.ndarray):
p[k] = v.tolist()
# ensure no numpy arrays in channel map
channel_map_list = None
if channel_map is not None:
valid, error = validate_channel_map(channel_map)
if not valid:
raise ValueError(f"channel_map validation failed with error '{error:s}'")
# numpy arrays are not seriablizable ... so avoid these
channel_map_list = deepcopy(channel_map)
for _, current_ch_dict in channel_map_list.items():
for m, v in current_ch_dict.items():
if isinstance(v, np.ndarray):
current_ch_dict[m] = v.tolist()
if use_zarr:
z = zarr.open(fname, "w")
if firmware_patterns is not None:
z.array("firmware_patterns",
firmware_patterns.astype(bool),
compressor=packbits.PackBits(),
dtype=bool,
chunks=(1, firmware_patterns.shape[-2], firmware_patterns.shape[-1]))
z.attrs["timestamp"] = tstamp
z.attrs["hid_path"] = hid_path
z.attrs["firmware_pattern_data"] = pattern_data_list
z.attrs["channel_map"] = channel_map_list
else:
if firmware_patterns is not None:
warn("firmware_patterns were provided but json configuration file was selected."
" Use zarr instead to save firmware patterns")
with open(fname, "w") as f:
json.dump({"timestamp": tstamp,
"firmware_pattern_data": pattern_data_list,
"channel_map": channel_map_list,
"hid_path": hid_path}, f, indent="\t")
def load_config_file(fname: Union[str, Path]):
"""
Load DMD firmware data from json configuration file
:param fname: configuration file path
:return pattern_data, channel_map, firmware_patterns, tstamp:
"""
fname = Path(fname)
if fname.suffix == ".json":
with open(fname, "r") as f:
data = json.load(f)
tstamp = data["timestamp"]
pattern_data = data["firmware_pattern_data"]
channel_map = data["channel_map"]
firmware_patterns = None
try:
hid_path = data["hid_path"]
except KeyError:
hid_path = None
elif fname.suffix == ".zarr":
z = zarr.open(fname, "r")
tstamp = z.attrs["timestamp"]
pattern_data = z.attrs["firmware_pattern_data"]
channel_map = z.attrs["channel_map"]
try:
hid_path = z.attrs["hid_path"]
except KeyError:
hid_path = None
try:
firmware_patterns = z["firmware_patterns"]
except ValueError:
firmware_patterns = None
else:
raise ValueError(f"fname suffix was '{fname.suffix:s}' but must be '.json' or '.zarr'")
# convert entries to numpy arrays
for p in pattern_data:
for k, v in p.items():
if isinstance(v, list) and len(v) > 1:
p[k] = np.atleast_1d(v)
if channel_map is not None:
# validate channel map
valid, error = validate_channel_map(channel_map)
if not valid:
raise ValueError(f"channel_map validation failed with error '{error:s}'")
# convert entries to numpy arrays
for ch, presets in channel_map.items():
for mode_name, m in presets.items():
presets[mode_name] = np.atleast_1d(m)
return pattern_data, channel_map, firmware_patterns, hid_path, tstamp
def get_preset_info(inds: Sequence,
pattern_data: Sequence[dict]) -> dict:
"""
Get useful data from preset
:param inds: firmware pattern indices
:param pattern_data: pattern data for each firmware pattern
:return pd_all: pattern data dictionary. Dictionary keys will be the same those in each element of pattern_data,
and values will aggregate the information from pattern data
"""
pd = [pattern_data[ii] for ii in inds]
pd_all = {}
for k in pd[0].keys():
pd_all[k] = [p[k] for p in pd]
return pd_all
##############################################
# dlp6500 DMD
##############################################
class dlpc900_dmd:
"""
Base class for communicating with any DMD using the DLPC900 controller, including the DLP6500 and DLP9000.
OS specific code should only appear in private functions _get_device(), _send_raw_packet(), and __del__()
"""
width = None # pixels
height = None # pixels
pitch = None # um
dual_controller = None
# these used internally
_dmd = None
_response = []
# USB packet length not including report_id_byte
_packet_length_bytes = 64
max_lut_index = 511
min_time_us = 105
_max_cmd_payload = 504
dmd_type_code = {0: "unknown",
1: "DLP6500",
2: "DLP9000",
3: "DLP670S",
4: "DLP500YX",
5: "DLP5500"
}
pattern_modes = {'video': 0x00,
'pre-stored': 0x01,
'video-pattern': 0x02,
'on-the-fly': 0x03
}
compression_modes = {'none': 0x00,
'rle': 0x01,
'erle': 0x02
}
# tried to match with the TI GUI names where possible
# see TI "DLPC900 Programmer's Guide", dlpu018.pdf, appendix A for reference
# available at http://www.ti.com/product/DLPC900/technicaldocuments
command_dict = {'Read_Error_Code': 0x0100,
'Read_Error_Description': 0x0101,
'Get_Hardware_Status': 0x1A0A,
'Get_System_Status': 0x1A0B,
'Get_Main_Status': 0x1A0C,
'Get_Firmware_Version': 0x0205,
'Get_Firmware_Type': 0x0206,
'Get_Firmware_Batch_File_Name': 0x1A14,
'Execute_Firmware_Batch_File': 0x1A15,
'Set_Firmware_Batch_Command_Delay_Time': 0x1A16,
'PAT_START_STOP': 0x1A24,
'DISP_MODE': 0x1A1B,
'MBOX_DATA': 0x1A34,
'PAT_CONFIG': 0x1A31,
'PATMEM_LOAD_INIT_MASTER': 0x1A2A,
'PATMEM_LOAD_DATA_MASTER': 0x1A2B,
'PATMEM_LOAD_INIT_SECONDARY': 0x1A2C,
'PATMEM_LOAD_DATA_SECONDARY': 0x1A2D,
'TRIG_OUT1_CTL': 0x1A1D,
'TRIG_OUT2_CTL': 0x1A1E,
'TRIG_IN1_CTL': 0x1A35,
'TRIG_IN2_CTL': 0x1A36,
}
err_dictionary = {0: 'no error',
1: 'batch file checksum error',
2: 'device failure',
3: 'invalid command number',
4: 'incompatible controller/dmd',
5: 'command not allowed in current mode',
6: 'invalid command parameter',
7: 'item referred by the parameter is not present',
8: 'out of resource (RAM/flash)',
9: 'invalid BMP compression type',
10: 'pattern bit number out of range',
11: 'pattern BMP not present in flash',
12: 'pattern dark time is out of range',
13: 'signal delay parameter is out of range',
14: 'pattern exposure time is out of range',
15: 'pattern number is out of range',
16: 'invalid pattern definition',
17: 'pattern image memory address is out of range',
255: 'internal error'
}
status_strs = ['DMD micromirrors are parked',
'sequencer is running normally',
'video is frozen',
'external video source is locked',
'port 1 syncs valid',
'port 2 syncs valid',
'reserved',
'reserved'
]
hw_status_strs = ['internal initialization success',
'incompatible controller or DMD',
'DMD rest controller error',
'forced swap error',
'slave controller present',
'reserved',
'sequence abort status error',
'sequencer error'
]
def __init__(self,
vendor_id: int = 0x0451,
product_id: int = 0xc900,
debug: bool = True,
firmware_pattern_info: Optional[list] = None,
presets: Optional[dict] = None,
config_file: Optional[Union[str, Path]] = None,
firmware_patterns: Optional[np.ndarray] = None,
initialize: bool = True,
dmd_index: int = 0,
hid_path: Optional[str] = None,
platform: Optional[str] = None):
"""
Get instance of DLP LightCrafter evaluation module (DLP6500 or DLP9000). This is the base class which os
dependent classes should inherit from. The derived classes only need to implement _get_device and
_send_raw_packet.
Note that DMD can be instantiated before being loaded. In this case, use the constructor with initialize=False
and later call initialize() method with the desired arguments.
:param vendor_id: vendor id, used to find DMD USB device
:param product_id: product id, used to find DMD USB device
:param bool debug: If True, will print output of commands.
:param firmware_pattern_info:
:param presets: dictionary of presets
:param config_file: either provide config file or provide firmware_pattern_info, presets, and firmware_patterns
:param firmware_patterns: npatterns x ny x nx array of patterns stored in DMD firmware. NOTE, this class
does not deal with loading or reading patterns from the firmware. Do this with the TI GUI
:param initialize: whether to connect to the DMD. In certain cases it is convenient to create this object
before connecting to the DMD, if e.g. we want to pass the DMD to another class, but we don't know what
DMD index we want yet
:param dmd_index: If multiple DMD's are attached, choose this one. Indexing starts at zero
:param hid_path: for more stable identification of a single DMD on multi-DMD systems, provide the hid path.
This can be obtained from a winusb.hid HIDDevice using the device_path attribute. If an HID path is provided,
it overrides the dmd_index argument.
:param platform:
"""
if config_file is not None and (firmware_pattern_info is not None or
presets is not None or
firmware_patterns is not None):
raise ValueError("both config_file and either firmware_pattern_info, presets, or firmware_patterns"
" were provided. But if config file is provided, these other settings should not be"
" set directly.")
# load configuration file
if config_file is not None:
firmware_pattern_info, presets, firmware_patterns, hid_path_config, _ = load_config_file(config_file)
if hid_path_config is not None:
if hid_path is not None:
warn("hid_path was provided as argument, so value loaded from configuration file will be ignored")
else:
hid_path = hid_path_config
if firmware_pattern_info is None:
firmware_pattern_info = []
if presets is None:
presets = {}
# todo: is there a way to read these out from DMD itself?
if firmware_patterns is not None:
firmware_patterns = np.array(firmware_patterns)
self.firmware_indices = np.arange(len(firmware_patterns))
else:
self.firmware_indices = None
# set firmware pattern info
self.firmware_pattern_info = firmware_pattern_info
self.presets = presets
self.firmware_patterns = firmware_patterns
# on-the-fly patterns
self.on_the_fly_patterns = None
self.debug = debug
# info to find device
self.vendor_id = vendor_id
self.product_id = product_id
self.dmd_index = dmd_index
self._hid_path = hid_path
# get platform
if platform is None:
self._platform = sys.platform
else:
self._platform = platform
self.initialized = initialize
if self.initialized:
self._get_device()
def __del__(self):
if self._platform == "win32":
try:
self._dmd.close()
except AttributeError:
pass # this will fail if object destroyed before being initialized
def initialize(self, **kwargs):
self.__init__(initialize=True, **kwargs)
# sending and receiving commands, operating system dependence
def _get_device(self):
"""
Return handle to DMD. This command can contain OS dependent implementation
:return:
"""
if self._platform == "win32":
if self._hid_path is None:
devices = pyhid.HidDeviceFilter(vendor_id=self.vendor_id,
product_id=self.product_id).get_devices()
devices = [d for d in devices if d.product_name == "DLPC900"]
if len(devices) <= self.dmd_index:
raise ValueError(f"Not enough DMD's detected for dmd_index={self.dmd_index:d}."
f"Only {len(devices):d} DMD's were detected.")
self._dmd = devices[self.dmd_index]
self._hid_path = self._dmd.device_path
else:
self._dmd = pyhid.HidDevice(self._hid_path)
self._dmd.open()
# strip off first return byte and add rest to self._response
self._dmd.set_raw_data_handler(lambda data: self._response.append(data[1:]))
elif self._platform == "none":
pass
else:
raise NotImplementedError(f"Platform was '{self._platform:s}', "
f"but DMD control is only implemented on 'win32'")
def _send_raw_packet(self,
buffer,
listen_for_reply: bool = False,
timeout: float = 5):
"""
Send a single USB packet. This command can contain OS dependent implementations
:param buffer: list of bytes to send to device
:param listen_for_reply: whether to listen for a reply
:param timeout: timeout in seconds
:return reply: a list of bytes
"""
# one interesting issue is it seems on linux the report ID byte is stripped
# by the driver, so we would not need to worry about it here. For windows, we must handle manually.
if self._platform == "win32":
# ensure packet is correct length
assert len(buffer) == self._packet_length_bytes
report_id_byte = [0x00]
# clear reply buffer before sending
self._response = []
# send
reports = self._dmd.find_output_reports()
reports[0].send(report_id_byte + buffer)
# only wait for a reply if necessary
if listen_for_reply:
tstart = time.time()
while self._response == []:
time.sleep(0.1)
tnow = time.time()
if timeout is not None:
if (tnow - tstart) > timeout:
print('read command timed out')
break
if self._response != []:
reply = deepcopy(self._response[0])
else:
reply = []
return reply
else:
raise NotImplementedError("DMD control is only implemented on windows")
def send_raw_command(self,
buffer,
listen_for_reply: bool = False,
timeout: float = 5):
"""
Send a raw command over USB, possibly including multiple packets. In contrast to send_command,
this function does not generate the required header data. It deals with splitting
one command into multiple packets and appropriately padding the supplied buffer.
This command should not be operating system dependent. All operating system dependence should be
in _send_raw_packet()
:param buffer: buffer to send. List of bytes.
:param listen_for_reply: Boolean. Whether to wait for a reply form USB device
:param timeout: time to wait for reply, in seconds
:return: reply: a list of lists of bytes. Each list represents the response for a separate packet.
"""
reply = []
# handle sending multiple packets if necessary
data_counter = 0
while data_counter < len(buffer):
# ensure data is correct length
data_counter_next = data_counter + self._packet_length_bytes
data_to_send = buffer[data_counter:data_counter_next]
if len(data_to_send) < self._packet_length_bytes:
# pad with zeros if necessary
data_to_send += [0x00] * (self._packet_length_bytes - len(data_to_send))
packet_reply = self._send_raw_packet(data_to_send, listen_for_reply, timeout)
reply += packet_reply
# increment for next packet
data_counter = data_counter_next
return reply
def send_command(self,
rw_mode: str,
reply: bool,
command: int,
data=(),
sequence_byte=0x00):
"""
Send USB command to DMD
DMD uses little endian byte order. They also use the convention that, when converting from binary to hex
the MSB is the rightmost. i.e. \b11000000 = \x03.
:param rw_mode: 'r' for read, or 'w' for write
:param reply: boolean
:param command: two byte integer
:param data: data to be transmitted. List of integers, where each integer gives a byte
:param sequence_byte: integer
:return response_buffer:
"""
# construct header, 4 bytes long
# first byte is flag byte
flagstring = ''
if rw_mode == 'r':
flagstring += '1'
elif rw_mode == 'w':
flagstring += '0'
else:
raise ValueError("flagstring should be 'r' or 'w' but was '%s'" % flagstring)
# second bit is reply
if reply:
flagstring += '1'
else:
flagstring += '0'
# third bit is error bit
flagstring += '0'
# fourth and fifth reserved
flagstring += '00'
# 6-8 destination
flagstring += '000'
# first byte
flag_byte = int(flagstring, 2)
# second byte is sequence byte. This is used only to identify responses to given commands.
# third and fourth are length of payload, respectively LSB and MSB bytes
len_payload = len(data) + 2
len_lsb, len_msb = unpack('BB', pack('H', len_payload))
# get USB command bytes
cmd_lsb, cmd_msb = unpack('BB', pack('H', command))
# this does not exactly correspond with what TI calls the header. It is a combination of
# the report id_byte, the header, and the USB command bytes
header = [flag_byte, sequence_byte, len_lsb, len_msb, cmd_lsb, cmd_msb]
buffer = header + list(data)
# print commands during debugging
if self.debug:
# get command name if possible
# header
print('header: ' + bin(header[0]), end=' ')
for ii in range(1, len(header)):
print("0x%0.2X" % header[ii], end=' ')
print('')
# get command name, if possible
for k, v in self.command_dict.items():