-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdriveboard.py
1567 lines (1397 loc) · 57.9 KB
/
driveboard.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
# -*- coding: UTF-8 -*-
import os
import io
import sys
import time
import json
import copy
import base64
import threading
import itertools
import serial
import serial.tools.list_ports
import datetime
import platform
from config import conf, write_config_fields
if not conf['mill_mode']:
try:
from PIL import Image
except ImportError:
print("Pillow module missing, raster mode will fail.")
__author__ = 'Stefan Hechenberger <[email protected]>'
################ SENDING PROTOCOL
CMD_STOP = chr(1)
CMD_RESUME = chr(2)
CMD_STATUS = chr(3)
CMD_SUPERSTATUS = chr(4)
CMD_CHUNK_PROCESSED = chr(5)
CMD_RASTER_DATA_START = chr(16)
CMD_RASTER_DATA_END = chr(17)
STATUS_END = chr(6)
CMD_NONE = "A"
CMD_LINE = "B"
CMD_DWELL = "C"
CMD_RASTER = "D"
CMD_REF_RELATIVE = "E"
CMD_REF_ABSOLUTE = "F"
CMD_REF_STORE = "G"
CMD_REF_RESTORE = "H"
CMD_HOMING = "I"
CMD_OFFSET_STORE = "J"
CMD_OFFSET_RESTORE = "K"
CMD_AIR_ENABLE = "L"
CMD_AIR_DISABLE = "M"
CMD_AUX_ENABLE = "N"
CMD_AUX_DISABLE = "O"
PARAM_TARGET_X = "x"
PARAM_TARGET_Y = "y"
PARAM_TARGET_Z = "z"
PARAM_FEEDRATE = "f"
PARAM_INTENSITY = "s"
PARAM_DURATION = "d"
PARAM_PIXEL_WIDTH = "p"
PARAM_OFFSET_X = "h"
PARAM_OFFSET_Y = "i"
PARAM_OFFSET_Z = "j"
################
################ RECEIVING PROTOCOL
# status: error flags
ERROR_SERIAL_STOP_REQUEST = '!'
ERROR_RX_BUFFER_OVERFLOW = '"'
ERROR_LIMIT_HIT_X1 = '$'
ERROR_LIMIT_HIT_X2 = '%'
ERROR_LIMIT_HIT_Y1 = '&'
ERROR_LIMIT_HIT_Y2 = '*'
ERROR_LIMIT_HIT_Z1 = '+'
ERROR_LIMIT_HIT_Z2 = '-'
ERROR_INVALID_MARKER = '#'
ERROR_INVALID_DATA = ':'
ERROR_INVALID_COMMAND = '<'
ERROR_INVALID_PARAMETER ='>'
ERROR_TRANSMISSION_ERROR ='='
# status: info flags
INFO_IDLE_YES = 'A'
INFO_DOOR_OPEN = 'B'
INFO_CHILLER_OFF = 'C'
# status: info params
INFO_POS_X = 'x'
INFO_POS_Y = 'y'
INFO_POS_Z = 'z'
INFO_VERSION = 'v'
INFO_BUFFER_UNDERRUN = 'w'
INFO_STACK_CLEARANCE = 'u'
INFO_HELLO = '~'
INFO_OFFSET_X = 'a'
INFO_OFFSET_Y = 'b'
INFO_OFFSET_Z = 'c'
# INFO_TARGET_X = 'd'
# INFO_TARGET_Y = 'e'
# INFO_TARGET_Z = 'f'
INFO_FEEDRATE = 'g'
INFO_INTENSITY = 'h'
INFO_DURATION = 'i'
INFO_PIXEL_WIDTH = 'j'
INFO_DEBUG = 'k'
################
# reverse lookup for commands, for debugging
# NOTE: have to be in sync with above definitions
markers_tx = {
chr(1): "CMD_STOP",
chr(2): "CMD_RESUME",
chr(3): "CMD_STATUS",
chr(4): "CMD_SUPERSTATUS",
chr(5): "CMD_CHUNK_PROCESSED",
chr(16): "CMD_RASTER_DATA_START",
chr(17): "CMD_RASTER_DATA_END",
chr(6): "STATUS_END",
"A": "CMD_NONE",
"B": "CMD_LINE",
"C": "CMD_DWELL",
"D": "CMD_RASTER",
"E": "CMD_REF_RELATIVE",
"F": "CMD_REF_ABSOLUTE",
"G": "CMD_REF_STORE",
"H": "CMD_REF_RESTORE",
"I": "CMD_HOMING",
"J": "CMD_OFFSET_STORE",
"K": "CMD_OFFSET_RESTORE",
"L": "CMD_AIR_ENABLE",
"M": "CMD_AIR_DISABLE",
"N": "CMD_AUX_ENABLE",
"O": "CMD_AUX_DISABLE",
"x": "PARAM_TARGET_X",
"y": "PARAM_TARGET_Y",
"z": "PARAM_TARGET_Z",
"f": "PARAM_FEEDRATE",
"s": "PARAM_INTENSITY",
"d": "PARAM_DURATION",
"p": "PARAM_PIXEL_WIDTH",
"h": "PARAM_OFFSET_X",
"i": "PARAM_OFFSET_Y",
"j": "PARAM_OFFSET_Z",
}
markers_rx = {
chr(1): "CMD_STOP",
chr(2): "CMD_RESUME",
chr(3): "CMD_STATUS",
chr(4): "CMD_SUPERSTATUS",
chr(5): "CMD_CHUNK_PROCESSED",
chr(16): "CMD_RASTER_DATA_START",
chr(17): "CMD_RASTER_DATA_END",
chr(6): "STATUS_END",
# status: error flags
'!': "ERROR_SERIAL_STOP_REQUEST",
'"': "ERROR_RX_BUFFER_OVERFLOW",
'$': "ERROR_LIMIT_HIT_X1",
'%': "ERROR_LIMIT_HIT_X2",
'&': "ERROR_LIMIT_HIT_Y1",
'*': "ERROR_LIMIT_HIT_Y2",
'+': "ERROR_LIMIT_HIT_Z1",
'-': "ERROR_LIMIT_HIT_Z2",
'#': "ERROR_INVALID_MARKER",
':': "ERROR_INVALID_DATA",
'<': "ERROR_INVALID_COMMAND",
'>': "ERROR_INVALID_PARAMETER",
'=': "ERROR_TRANSMISSION_ERROR",
# status: info flags
'A': "INFO_IDLE_YES",
'B': "INFO_DOOR_OPEN",
'C': "INFO_CHILLER_OFF",
# status: info params
'x': "INFO_POS_X",
'y': "INFO_POS_Y",
'z': "INFO_POS_Z",
'v': "INFO_VERSION",
'w': "INFO_BUFFER_UNDERRUN",
'u': "INFO_STACK_CLEARANCE",
'~': "INFO_HELLO",
'a': "INFO_OFFSET_X",
'b': "INFO_OFFSET_Y",
'c': "INFO_OFFSET_Z",
# 'd': "INFO_TARGET_X",
# 'e': "INFO_TARGET_Y",
# 'f': "INFO_TARGET_Z",
'g': "INFO_FEEDRATE",
'h': "INFO_INTENSITY",
'i': "INFO_DURATION",
'j': "INFO_PIXEL_WIDTH",
'k': "INFO_DEBUG",
}
SerialLoop = None
fallback_msg_thread = None
class SerialLoopClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.device = None
self.tx_buffer = []
self.tx_pos = 0
# TX_CHUNK_SIZE - this is the number of bytes to be
# written to the device in one go. It needs to match the device.
self.TX_CHUNK_SIZE = 16
self.RX_CHUNK_SIZE = 32
self.FIRMBUF_SIZE = 256 # needs to match device firmware
self.firmbuf_used = 0
# used for calculating percentage done
self.job_size = 0
# status flags
self._status = {} # last complete status frame
self._s = {} # status fram currently assembling
self.reset_status()
self._paused = False
self.request_stop = False
self.request_resume = False
self.request_status = 2 # 0: no request, 1: normal request, 2: super request
self.pdata_count = 0
self.pdata_nums = [128, 128, 128, 192]
threading.Thread.__init__(self)
self.stop_processing = False
self.deamon = True # kill thread when main thread exits
# lock mechanism for chared data
# see: http://effbot.org/zone/thread-synchronization.htm
self.lock = threading.Lock()
def reset_status(self):
self._status = {
'ready': False, # is hardware idle (and not stop mode)
'serial': False, # is serial connected
'appver':conf['version'],
'firmver': None,
'paused': False,
'pos':[0.0, 0.0, 0.0],
'underruns': 0, # how many times machine is waiting for serial data
'stackclear': 999999, # minimal stack clearance (must stay above 0)
'progress': 1.0,
### stop conditions
# indicated when key present
'stops': {},
# possible keys:
# x1, x2, y1, y2, z1, z2,
# requested, buffer, marker, data, command, parameter, transmission
'info':{},
# possible keys: door, chiller
### super
'offset': [0.0, 0.0, 0.0],
# 'pos_target': [0.0, 0.0, 0.0],
'feedrate': 0.0,
'intensity': 0.0,
'duration': 0.0,
'pixelwidth': 0.0
}
self._s = copy.deepcopy(self._status)
def send_command(self, command):
self.tx_buffer.append(ord(command))
self.job_size += 1
def send_param(self, param, val):
# num to be [-134217.728, 134217.727], [-2**27, 2**27-1]
# three decimals are retained
num = int(round(((val+134217.728)*1000)))
char0 = (num&127)+128
char1 = ((num&(127<<7))>>7)+128
char2 = ((num&(127<<14))>>14)+128
char3 = ((num&(127<<21))>>21)+128
self.tx_buffer.append(char0)
self.tx_buffer.append(char1)
self.tx_buffer.append(char2)
self.tx_buffer.append(char3)
self.tx_buffer.append(ord(param))
self.job_size += 5
def send_raster_data(self, data, start, end):
count = 2
with self.lock:
self.tx_buffer.append(ord(CMD_RASTER_DATA_START))
for val in itertools.islice(data, start, end):
with self.lock:
self.tx_buffer.append(int((255 - val)/2) + 128)
count += 1
with self.lock:
self.tx_buffer.append(ord(CMD_RASTER_DATA_END))
self.job_size += count
def run(self):
"""Main loop of the serial thread."""
# last_write = 0
last_status_request = 0
disable_computer_sleep()
while True:
if self.stop_processing:
enable_computer_sleep()
break
with self.lock:
# read/write
if self.device:
try:
self._serial_read()
# (1/0.008)*16 = 2000 bytes/s
# for raster we need: 10(10000/60.0) = 1660 bytes/s
self._serial_write()
# if time.time()-last_write > 0.01:
# sys.stdout.write('~')
# last_write = time.time()
except BaseException as e:
self.stop_processing = True
self._status['serial'] = False
self._status['ready'] = False
if e is OSError:
print("ERROR: serial got disconnected 1.")
elif e is ValueError:
print("ERROR: serial got disconnected 2.")
else:
print('ERROR: unknown serial error')
print(str(e))
else:
self.stop_processing = True
self._status['serial'] = False
self._status['ready'] = False
print("ERROR: serial got disconnected 3.")
# status request
if time.time()-last_status_request > 0.5:
if self._status['ready']:
self.request_status = 2 # ready -> super request
else:
self.request_status = 1 # processing -> normal request
last_status_request = time.time()
# flush stdout, so print shows up timely
sys.stdout.flush()
time.sleep(0.004) # 250 Hz
def _serial_read(self):
chunk = self.device.read(self.RX_CHUNK_SIZE)
if conf['print_serial_data'] and chunk != b'':
timestamp = datetime.datetime.now().strftime('%H:%M:%S.%f')[:-4]
print(timestamp + ' Receiving: ' + prettify_serial(chunk, markers=markers_rx))
for data_num in chunk:
data_char = chr(data_num)
if data_num < 32: ### flow
if data_char == CMD_CHUNK_PROCESSED:
self.firmbuf_used -= self.TX_CHUNK_SIZE
if self.firmbuf_used < 0:
print("ERROR: firmware buffer tracking too low")
elif data_char == STATUS_END:
# status frame complete, compile status
self._status, self._s = self._s, self._status # flip
self._status['paused'] = self._paused
self._status['serial'] = bool(self.device)
if self.job_size == 0:
self._status['progress'] = 1.0
else:
self._status['progress'] = \
round(self.tx_pos/float(self.job_size),3)
self._s['stops'].clear()
self._s['info'].clear()
self._s['ready'] = False
self._s['underruns'] = self._status['underruns']
self._s['stackclear'] = self._status['stackclear']
elif 31 < data_num < 65: ### stop error markers
# chr is in [!-@], process flag
if data_char == ERROR_LIMIT_HIT_X1:
self._s['stops']['x1'] = True
elif data_char == ERROR_LIMIT_HIT_X2:
self._s['stops']['x2'] = True
elif data_char == ERROR_LIMIT_HIT_Y1:
self._s['stops']['y1'] = True
elif data_char == ERROR_LIMIT_HIT_Y2:
self._s['stops']['y2'] = True
elif data_char == ERROR_LIMIT_HIT_Z1:
self._s['stops']['z1'] = True
elif data_char == ERROR_LIMIT_HIT_Z2:
self._s['stops']['z2'] = True
elif data_char == ERROR_SERIAL_STOP_REQUEST:
self._s['stops']['requested'] = True
print("INFO firmware: stop request")
elif data_char == ERROR_RX_BUFFER_OVERFLOW:
self._s['stops']['buffer'] = True
print("ERROR firmware: rx buffer overflow")
elif data_char == ERROR_INVALID_MARKER:
self._s['stops']['marker'] = True
print("ERROR firmware: invalid marker")
elif data_char == ERROR_INVALID_DATA:
self._s['stops']['data'] = True
print("ERROR firmware: invalid data")
elif data_char == ERROR_INVALID_COMMAND:
self._s['stops']['command'] = True
print("ERROR firmware: invalid command")
elif data_char == ERROR_INVALID_PARAMETER:
self._s['stops']['parameter'] = True
print("ERROR firmware: invalid parameter")
elif data_char == ERROR_TRANSMISSION_ERROR:
self._s['stops']['transmission'] = True
print("ERROR firmware: transmission")
else:
print("ERROR: invalid stop error marker")
# in stop mode, print recent transmission, unless stop request, or limit
if data_char != ERROR_SERIAL_STOP_REQUEST and \
data_char != ERROR_LIMIT_HIT_X1 and \
data_char != ERROR_LIMIT_HIT_X2 and \
data_char != ERROR_LIMIT_HIT_Y1 and \
data_char != ERROR_LIMIT_HIT_Y2 and \
data_char != ERROR_LIMIT_HIT_Z1 and \
data_char != ERROR_LIMIT_HIT_Z2:
recent_data = self.tx_buffer[max(0,self.tx_pos-128):self.tx_pos]
print("RECENT TX BUFFER:")
for data_num in recent_data:
data_char = chr(data_num)
if data_char in markers_tx:
print("\t%s" % (markers_tx[data_char]))
elif 127 < data_num < 256:
print("\t(data byte)")
else:
print("\t(invalid)")
print("----------------")
# stop mode housekeeping
self.tx_buffer = []
self.tx_pos = 0
self.job_size = 0
self._paused = False
self.device.flushOutput()
self.pdata_count = 0
self._s['ready'] = True # ready but in stop mode
elif 64 < data_num < 91: # info flags
# data_char is in [A-Z], info flag
if data_char == INFO_IDLE_YES:
if not self.tx_buffer:
self._s['ready'] = True
elif data_char == INFO_DOOR_OPEN:
self._s['info']['door'] = True
elif data_char == INFO_CHILLER_OFF:
self._s['info']['chiller'] = True
else:
print("ERROR: invalid info flag")
sys.stdout.write('(',data_char,',',data_num,')')
self.pdata_count = 0
elif 96 < data_num < 123: # parameter
# data_char is in [a-z], process parameter
num = ((((self.pdata_nums[3]-128)*2097152
+ (self.pdata_nums[2]-128)*16384
+ (self.pdata_nums[1]-128)*128
+ (self.pdata_nums[0]-128) )- 134217728)/1000.0)
if data_char == INFO_POS_X:
self._s['pos'][0] = num
elif data_char == INFO_POS_Y:
self._s['pos'][1] = num
elif data_char == INFO_POS_Z:
self._s['pos'][2] = num
elif data_char == INFO_VERSION:
num = str(int(num)/100.0)
self._s['firmver'] = num
elif data_char == INFO_BUFFER_UNDERRUN:
self._s['underruns'] = num
elif data_char == INFO_DEBUG:
# available for custom debugging messaging
pass
# super status
elif data_char == INFO_OFFSET_X:
self._s['offset'][0] = num
elif data_char == INFO_OFFSET_Y:
self._s['offset'][1] = num
elif data_char == INFO_OFFSET_Z:
self._s['offset'][2] = num
elif data_char == INFO_FEEDRATE:
self._s['feedrate'] = num
elif data_char == INFO_INTENSITY:
self._s['intensity'] = 100*num/255
elif data_char == INFO_DURATION:
self._s['duration'] = num
elif data_char == INFO_PIXEL_WIDTH:
self._s['pixelwidth'] = num
elif data_char == INFO_STACK_CLEARANCE:
self._s['stackclear'] = num
else:
print("ERROR: invalid param")
self.pdata_count = 0
self.pdata_nums = [128, 128, 128, 192]
elif data_num > 127: ### data
# data_char is in [128,255]
if self.pdata_count < 4:
self.pdata_nums[self.pdata_count] = data_num
self.pdata_count += 1
else:
print("ERROR: invalid data")
else:
print(data_num)
print(data_char)
print("ERROR: invalid marker")
self.pdata_count = 0
def _serial_write(self):
### sending super commands (handled in serial rx interrupt)
if self.request_status == 1:
self._send_char(CMD_STATUS)
self.request_status = 0
elif self.request_status == 2:
self._send_char(CMD_SUPERSTATUS)
self.request_status = 0
if self.request_stop:
self._send_char(CMD_STOP)
self.request_stop = False
if self.request_resume:
self._send_char(CMD_RESUME)
self.firmbuf_used = 0 # a resume resets the hardware's rx buffer
self.request_resume = False
self.reset_status()
self.request_status = 2 # super request
### send buffer chunk
if self.tx_buffer and len(self.tx_buffer) > self.tx_pos:
if not self._paused:
if (self.FIRMBUF_SIZE - self.firmbuf_used) > self.TX_CHUNK_SIZE:
try:
# to_send = ''.join(islice(self.tx_buffer, 0, self.TX_CHUNK_SIZE))
to_send = self.tx_buffer[self.tx_pos:self.tx_pos+self.TX_CHUNK_SIZE]
expectedSent = len(to_send)
if conf['print_serial_data']:
timestamp = datetime.datetime.now().strftime('%H:%M:%S.%f')[:-4]
print(timestamp + ' Sending: ' + prettify_serial(to_send, markers=markers_tx))
# by protocol duplicate every char
to_send_double = []
for n in to_send:
to_send_double.append(n)
to_send_double.append(n)
to_send = to_send_double
#
t_prewrite = time.time()
actuallySent = self.device.write(to_send)
if actuallySent != expectedSent*2:
print("ERROR: write did not complete")
assumedSent = 0
else:
assumedSent = expectedSent
self.firmbuf_used += assumedSent
if self.firmbuf_used > self.FIRMBUF_SIZE:
print("ERROR: firmware buffer tracking too high")
if time.time() - t_prewrite > 0.1:
print("WARN: write delay 1")
except serial.SerialTimeoutException:
assumedSent = 0
print("ERROR: writeTimeoutError 2")
except BaseException as e:
print('ERROR: unknown error')
print(str(e))
self.tx_pos += assumedSent
else:
if self.tx_buffer: # job finished sending
self.job_size = 0
self.tx_buffer = []
self.tx_pos = 0
def _send_char(self, char):
try:
t_prewrite = time.time()
if conf['print_serial_data']:
timestamp = datetime.datetime.now().strftime('%H:%M:%S.%f')[:-4]
print(timestamp + ' Sending: ' + prettify_serial(ord(char), markers=markers_tx))
self.device.write([ord(char),ord(char)]) # by protocol send twice
if time.time() - t_prewrite > 0.1:
pass
except serial.SerialTimeoutException:
print("ERROR: writeTimeoutError 1")
###########################################################################
### API ###################################################################
###########################################################################
def prettify_serial(chunk, markers=markers_tx):
string = ''
if not hasattr(prettify_serial, "tx_pdata_nums"):
prettify_serial.rx_pdata_nums = [128, 128, 128, 192]
prettify_serial.rx_pdata_count = 0
prettify_serial.tx_pdata_nums = [128, 128, 128, 192]
prettify_serial.tx_pdata_count = 0
prettify_serial.tx_rasterstream = False
prettify_serial.tx_rastercount = 0
if isinstance(chunk, int):
chunk = [chunk] # make integer inputs iterable
for i in range(len(chunk)):
data = chunk[i]
if data >= 128:
string += str(data) + ' '
if (markers == markers_tx) and prettify_serial.tx_rasterstream:
prettify_serial.tx_rastercount += 1
elif markers == markers_tx:
prettify_serial.tx_pdata_nums[prettify_serial.tx_pdata_count] = data
prettify_serial.tx_pdata_count += 1
elif markers == markers_rx:
prettify_serial.rx_pdata_nums[prettify_serial.rx_pdata_count] = data
prettify_serial.rx_pdata_count += 1
elif (data < 128):
if (markers == markers_tx) and (markers[chr(data)] not in ["CMD_STATUS", "CMD_SUPERSTATUS"]):
prettify_serial.tx_pdata_count = 0
prettify_serial.tx_pdata_nums = [128, 128, 128, 192]
elif (markers[chr(data)] not in ["CMD_CHUNK_PROCESSED"]):
prettify_serial.rx_pdata_count = 0
prettify_serial.rx_pdata_nums = [128, 128, 128, 192]
if markers[chr(data)] == 'CMD_RASTER_DATA_START':
prettify_serial.tx_rasterstream = True
prettify_serial.tx_rastercount = 0
elif markers[chr(data)] == 'CMD_RASTER_DATA_END':
prettify_serial.tx_rasterstream = False
string += '(' + str(prettify_serial.tx_rastercount) + ') '
string += markers[chr(data)] + ', '
if prettify_serial.tx_pdata_count == 4:
num = ((((prettify_serial.tx_pdata_nums[3]-128)*2097152
+ (prettify_serial.tx_pdata_nums[2]-128)*16384
+ (prettify_serial.tx_pdata_nums[1]-128)*128
+ (prettify_serial.tx_pdata_nums[0]-128) )- 134217728)/1000.0)
prettify_serial.tx_pdata_count = 0
prettify_serial.tx_pdata_nums = [128, 128, 128, 192]
string += '(' + str(num) + ') '
elif prettify_serial.rx_pdata_count == 4:
num = ((((prettify_serial.rx_pdata_nums[3]-128)*2097152
+ (prettify_serial.rx_pdata_nums[2]-128)*16384
+ (prettify_serial.rx_pdata_nums[1]-128)*128
+ (prettify_serial.rx_pdata_nums[0]-128) )- 134217728)/1000.0)
prettify_serial.rx_pdata_count = 0
prettify_serial.rx_pdata_nums = [128, 128, 128, 192]
string += '(' + str(num) + ') '
if len(string) >= 2 and string[-2] == ',':
string = string[:-2]
elif len(string) >= 1 and string[-1] == ' ':
string = string[:-1]
return string
def find_controller(baudrate=conf['baudrate'], verbose=True):
iterator = sorted(serial.tools.list_ports.comports())
# look for Arduinos
arduinos = []
for port, desc, hwid in iterator:
if "uino" in desc:
arduinos.append(port)
# check these arduinos for driveboard firmware, take first
for port in arduinos:
try:
s = serial.Serial(port=port, baudrate=baudrate, timeout=2.0)
lasaur_hello = s.read(8)
if lasaur_hello.find(ord(INFO_HELLO)) > -1:
s.close()
return port
s.close()
except serial.SerialException:
pass
# check all comports for driveboard firmware
for port, desc, hwid in iterator:
try:
s = serial.Serial(port=port, baudrate=baudrate, timeout=2.0)
lasaur_hello = s.read(8)
if lasaur_hello.find(ord(INFO_HELLO)) > -1:
s.close()
return port
s.close()
except serial.SerialException:
pass
# handle the case Arduino without firmware
if arduinos:
return arduinos[0]
# none found
if verbose:
print("ERROR: No controller found.")
return None
def connect(port=conf['serial_port'], baudrate=conf['baudrate'], verbose=True):
global SerialLoop
if not SerialLoop:
SerialLoop = SerialLoopClass()
# Create serial device with read timeout set to 0.
# This results in the read() being non-blocking.
# Write on the other hand uses a large timeout but should not be blocking
# much because we ask it only to write TX_CHUNK_SIZE at a time.
# BUG WARNING: the pyserial write function does not report how
# many bytes were actually written if this is different from requested.
# Work around: use a big enough timeout and a small enough chunk size.
try:
if conf['usb_reset_hack']:
import flash
flash.usb_reset_hack()
# connect
SerialLoop.device = serial.Serial(port, baudrate, timeout=0, writeTimeout=4)
if conf['hardware'] == 'standard':
# clear throat
# Toggle DTR to reset Arduino
SerialLoop.device.setDTR(False)
time.sleep(1)
SerialLoop.device.flushInput()
SerialLoop.device.setDTR(True)
# for good measure
SerialLoop.device.flushOutput()
else:
import flash
flash.reset_atmega()
time.sleep(0.5)
SerialLoop.device.flushInput()
SerialLoop.device.flushOutput()
start = time.time()
while True:
if time.time() - start > 2:
if verbose:
print("ERROR: Cannot get 'hello' from controller")
raise serial.SerialException
data = SerialLoop.device.read(1)
if data.find(ord(INFO_HELLO)) > -1:
if verbose:
print("Controller says Hello!")
print("Connected on serial port: %s" % (port))
break
SerialLoop.start() # this calls run() in a thread
except serial.SerialException:
SerialLoop = None
if verbose:
print("ERROR: Cannot connect serial on port: %s" % (port))
else:
if verbose:
print("ERROR: disconnect first")
def connect_withfind(port=conf['serial_port'], baudrate=conf['baudrate'], verbose=True):
connect(port=port, baudrate=baudrate, verbose=verbose)
if not connected():
# try finding driveboard
if verbose:
print("WARN: Cannot connect to configured serial port.")
print("INFO: Trying to find port.")
serialfindresult = find_controller(verbose=verbose)
if serialfindresult:
if verbose:
print("INFO: Hardware found at %s." % serialfindresult)
connect(port=serialfindresult, baudrate=baudrate, verbose=verbose)
if not connected(): # special case arduino found, but no firmware
yesno = input("Firmware appears to be missing. Want to flash-upload it (Y/N)? ")
if yesno in ('Y', 'y'):
ret = flash(serial_port=serialfindresult)
if ret == 0:
connect(port=serialfindresult, baudrate=baudrate, verbose=verbose)
if connected():
if verbose:
print("INFO: Connected at %s." % serialfindresult)
conf['serial_port'] = serialfindresult
write_config_fields({'serial_port':serialfindresult})
else:
if verbose:
print("-----------------------------------------------------------------------------")
print("How to configure:")
print("https://github.com/nortd/driveboardapp/blob/master/docs/configure.md")
print("-----------------------------------------------------------------------------")
def connected():
global SerialLoop
return SerialLoop and bool(SerialLoop.device)
def close():
global SerialLoop
if SerialLoop:
if SerialLoop.device:
SerialLoop.device.flushOutput()
SerialLoop.device.flushInput()
ret = True
else:
ret = False
if SerialLoop.is_alive():
SerialLoop.stop_processing = True
SerialLoop.join()
else:
ret = False
SerialLoop = None
return ret
def flash(serial_port=conf['serial_port'], firmware=conf['firmware']):
import flash
reconnect = False
if connected():
close()
reconnect = True
ret = flash.flash_upload(serial_port=serial_port, firmware=firmware)
if reconnect:
connect()
if ret != 0:
print("ERROR: flash failed")
return ret
def build():
import build
ret = build.build_all()
if ret != 0:
print("ERROR: build_all failed")
return ret
def reset():
import flash
reconnect = False
if connected():
close()
reconnect = True
flash.reset_atmega()
if reconnect:
connect()
def status():
"""Get status."""
if connected():
global SerialLoop
with SerialLoop.lock:
stats = copy.deepcopy(SerialLoop._status)
stats['serial'] = connected() # make sure serial flag is up-to-date
return stats
else:
return {'serial':False, 'ready':False}
def homing():
"""Run homing cycle."""
global SerialLoop
with SerialLoop.lock:
if SerialLoop._status['ready'] or SerialLoop._status['stops']:
SerialLoop.request_resume = True # to recover from a stop mode
SerialLoop.send_command(CMD_HOMING)
else:
print("WARN: ignoring homing command while job running")
def feedrate(val):
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_param(PARAM_FEEDRATE, val)
def intensity(val):
global SerialLoop
with SerialLoop.lock:
val = max(min(255*val/100, 255), 0)
SerialLoop.send_param(PARAM_INTENSITY, val)
def duration(val):
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_param(PARAM_DURATION, val)
def pixelwidth(val):
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_param(PARAM_PIXEL_WIDTH, val)
def relative():
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_command(CMD_REF_RELATIVE)
def absolute():
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_command(CMD_REF_ABSOLUTE)
def move(x=None, y=None, z=None):
global SerialLoop
with SerialLoop.lock:
if x is not None:
SerialLoop.send_param(PARAM_TARGET_X, x)
if y is not None:
SerialLoop.send_param(PARAM_TARGET_Y, y)
if z is not None:
SerialLoop.send_param(PARAM_TARGET_Z, z)
SerialLoop.send_command(CMD_LINE)
def supermove(x=None, y=None, z=None):
"""Moves in machine coordinates bypassing any offsets."""
global SerialLoop
with SerialLoop.lock:
# clear offset
SerialLoop.send_command(CMD_OFFSET_STORE)
SerialLoop.send_command(CMD_REF_STORE)
SerialLoop.send_command(CMD_REF_ABSOLUTE)
if x is not None:
SerialLoop.send_param(PARAM_OFFSET_X, 0)
if y is not None:
SerialLoop.send_param(PARAM_OFFSET_Y, 0)
if z is not None:
SerialLoop.send_param(PARAM_OFFSET_Z, 0)
SerialLoop.send_command(CMD_REF_RESTORE)
# move
if x is not None:
SerialLoop.send_param(PARAM_TARGET_X, x)
if y is not None:
SerialLoop.send_param(PARAM_TARGET_Y, y)
if z is not None:
SerialLoop.send_param(PARAM_TARGET_Z, z)
SerialLoop.send_command(CMD_OFFSET_RESTORE)
SerialLoop.send_command(CMD_LINE)
def rastermove(x, y, z=0.0):
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_param(PARAM_TARGET_X, x)
SerialLoop.send_param(PARAM_TARGET_Y, y)
SerialLoop.send_param(PARAM_TARGET_Z, z)
SerialLoop.send_command(CMD_RASTER)
def rasterdata(data, start, end):
# NOTE: no SerialLoop.lock
# more granular locking in send_data
SerialLoop.send_raster_data(data, start, end)
def pause():
global SerialLoop
with SerialLoop.lock:
if SerialLoop.tx_buffer:
SerialLoop._paused = True
def unpause():
global SerialLoop
with SerialLoop.lock:
SerialLoop._paused = False
def stop():
"""Force stop condition."""
global SerialLoop
with SerialLoop.lock:
SerialLoop.tx_buffer = []
SerialLoop.tx_pos = 0
SerialLoop.job_size = 0
SerialLoop.request_stop = True
def unstop():
"""Resume from stop condition."""
global SerialLoop
with SerialLoop.lock:
SerialLoop.request_resume = True
def dwell():
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_command(CMD_DWELL)
def air_on():
global SerialLoop
with SerialLoop.lock:
SerialLoop.send_command(CMD_AIR_ENABLE)