-
Notifications
You must be signed in to change notification settings - Fork 3
/
nxvcontrol.py
executable file
·1915 lines (1719 loc) · 79.6 KB
/
nxvcontrol.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
#!/usr/bin/env python3
# encoding: utf8
#
# Copyright 2016-2017 Yunhui Fu <[email protected]>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check https://github.com/yhfudev/python-nxvcontrol.git
try:
import Tkinter as tk
import ttk
import ScrolledText
import tkFileDialog as fd
except ImportError:
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
import tkinter.filedialog as fd
import os
import sys
import queue
# print("arg[0]: " + sys.argv[0])
# print("program name: " + os.path.basename(__file__))
#import __main__ as main0
# print("main: " + main0.__file__)
PROGRAM_PREFIX = os.path.basename(__file__).split('.')[0]
import logging as L
L.basicConfig(filename=PROGRAM_PREFIX+'.log', level=L.DEBUG, format='%(asctime)s %(levelname)s: %(message)s')
import neatocmdapi
import guilog
import locale
import gettext
_=gettext.gettext
APP_NAME="nxvcontrol"
def gettext_init():
global _
langs = []
language = os.environ.get('LANG', None)
if (language):
langs += language.split(":")
language = os.environ.get('LANGUAGE', None)
if (language):
langs += language.split(":")
lc, encoding = locale.getdefaultlocale()
if (lc):
langs += [lc]
# we know that we have
langs += ["en_US", "zh_CN"]
local_path = os.path.realpath(os.path.dirname(sys.argv[0]))
local_path = "languages/"
gettext.bindtextdomain(APP_NAME, local_path)
gettext.textdomain(APP_NAME)
lang = gettext.translation(APP_NAME, local_path, languages=langs, fallback = True)
#_=gettext.gettext
_=lang.gettext
L.debug("local=" + str(lc) + ", encoding=" + str(encoding) + ", langs=" + str(langs) + ", lang=" + str(lang) )
str_progname="nxvControl"
str_version="0.1"
LARGE_FONT= ("Verdana", 18)
NORM_FONT = ("Helvetica", 12)
SMALL_FONT = ("Helvetica", 8)
# key for state machine wheel
KEY_NONE=0
KEY_LEFT=1
KEY_RIGHT=2
KEY_UP=3
KEY_DOWN=4
KEY_BACK=5
# the states
STATE_STOP=1
STATE_FORWARD=2
STATE_BACK=3
STATE_LEFT=4
STATE_RIGHT=5
# TODO:
# the background thread to handle the communication with the neato
# a request scheduler is used because of the serial port
# the scheduler supports the time tagged request which is executed at the exact time
# the scheduler supports the the requst which has no required time, it will executed at the idle time
# a request contains the exact time tag, repeat time, user data, callback?
# return the result, execute start time, execute end time,
def test_pack(main_container):
main_container.pack(side="top", fill="both", expand=True)
top_frame = tk.Frame(main_container, background="green")
bottom_frame = tk.Frame(main_container, background="yellow")
top_frame.pack(side="top", fill="x", expand=False)
bottom_frame.pack(side="bottom", fill="both", expand=True)
top_left = tk.Frame(top_frame, background="pink")
top_center = tk.Frame(top_frame, background="red")
top_right = tk.Frame(top_frame, background="blue")
top_left.pack(side="left", fill="x", expand=True)
top_center.pack(side="left", fill="x", expand=True)
top_right.pack(side="right", fill="x", expand=True)
top_left_label = tk.Label(top_left, text="Top Left")
top_center_label = tk.Label(top_center, text="Top Center")
top_right_label = tk.Label(top_right, text="Top Right")
top_left_label.pack(side="left")
top_center_label.pack(side="top")
top_right_label.pack(side="right")
text_box = tk.Text(bottom_frame, height=5, width=40, background="gray")
text_box.pack(side="top", fill="both", expand=True)
def test_grid(myParent, main_container):
main_container.grid(row=0, column=0, sticky="nsew")
myParent.grid_rowconfigure(0, weight=1)
myParent.grid_columnconfigure(0, weight=1)
top_frame = tk.Frame(main_container, background="green")
bottom_frame = tk.Frame(main_container, background="yellow")
top_frame.grid(row=0, column=0, sticky="ew")
bottom_frame.grid(row=1, column=0,sticky="nsew")
main_container.grid_rowconfigure(1, weight=1)
main_container.grid_columnconfigure(0, weight=1)
top_left = tk.Frame(top_frame, background="pink")
top_center = tk.Frame(top_frame, background="red")
top_right = tk.Frame(top_frame, background="blue")
top_left.grid(row=0, column=0, sticky="w")
top_center.grid(row=0, column=1)
top_right.grid(row=0, column=2, sticky="e")
top_frame.grid_columnconfigure(1, weight=1)
top_left_label = tk.Label(top_left, text="Top Left")
top_center_label = tk.Label(top_center, text="Top Center")
top_right_label = tk.Label(top_right, text="Top Right")
top_left_label.grid(row=0, column=0, sticky="w")
top_center_label.grid(row=0, column=0)
top_right_label.grid(row=0, column=0, sticky="e")
def set_readonly_text(text, msg):
text.config(state=tk.NORMAL)
text.delete(1.0, tk.END)
text.insert(tk.END, msg)
text.config(state=tk.DISABLED)
import math
# const
MAXDIST=16700 # the maxmium allowed of the distance value of lidar
MAXDIST=4000 # the maxmium allowed of the distance value of lidar
CONST_RAD=math.pi / 180
import editabletreeview as et
class ScheduleTreeview(et.EditableTreeview):
def __init__(self, parent):
et.EditableTreeview.__init__(self, parent)
def initUI(self):
tree = self
tree["columns"]=("time")
tree.column('#0', anchor='w', width=30)
tree.heading('#0', text=_("Day of Week"), anchor='w')
tree.heading("time", text=_("Time"))
tree.bind('<<TreeviewInplaceEdit>>', self.on_row_edit)
tree.bind('<<TreeviewCellEdited>>', self.on_cell_changed)
self.updateSchedule("")
tree.tag_configure('schedis', background='grey')
tree.tag_configure('scheon', background='white')
tree.tag_configure('scheoff', background='grey')
pass
def on_row_edit(self, event):
tree = self
col, item = tree.get_event_info()
if col in ("time",):
#tree.inplace_entry(col, item)
tree.inplace_combobox(col, item, ("00:00 - None -", "00:00 H"), readonly=False)
def on_cell_changed(self, event):
tree = self
col, item = tree.get_event_info()
#L.debug('Column {0} of item {1} was changed={2}'.format(col, item, tree.item(item)["values"]))
if col in ("time",):
self.changed[item] = tree.item(item)["text"]
tag = self.val2tag(tree.item(item)["values"][0])
tree.item(item, tags = (tag,) )
def on_row_selected(self, event):
#print('Rows selected', event.widget.selection())
pass
# convert the value to tag
def val2tag(self, val):
columnlst = val.split(' ')
tag = "schedis"
if columnlst[1] == "H":
tag = "scheon"
return tag
def _updateItems(self, nxvretstr, subtree, nxvretstr_default, list_keys):
daytransmap={'Sun':_('Sunday'), 'Mon':_('Monday'), 'Tue':_('Tuesday'), 'Tues':_('Tuesday'), 'Wed':_('Wednesday'), 'Thu':_('Thursday'), 'Thur':_('Thursday'), 'Fri':_('Friday'), 'Sat':_('Saturday')}
tree = self
subtree=''
if nxvretstr == "":
# remove all of items in the tree
tree.delete(*tree.get_children(subtree))
# init the structure
nxvretstr=nxvretstr_default
items_children = self.get_children(subtree)
if items_children == None or len(items_children) < 1:
# create children
for itemstr in list_keys:
tree.insert(subtree, 'end', text=itemstr, values=(""))
items_children = self.get_children(subtree)
# parse the string
linestr = nxvretstr.strip() + '\n'
linelst = linestr.split('\n')
for i in range(0, len(linelst)):
line = linelst[i].strip()
if len(line) < 1:
break
columnlst = line.split(' ')
if len(columnlst) > 1:
if columnlst[0] in list_keys:
idx = list_keys[columnlst[0]]
val = " ".join(columnlst[1:len(columnlst)])
tag = self.val2tag(val)
#L.debug("len(lst) = " + str(len(columnlst)))
#L.debug("schedule[" + str(idx) + "], val=" + val + "tag=" + tag)
tree.item(items_children[idx], values=(val,), tags = (tag,), text=daytransmap[columnlst[0]])
def updateSchedule(self, nxvretstr):
subtree = self
nxvretstr_default="""Schedule is Disabled
Sun 00:00 - None -
Mon 00:00 - None -
Tue 00:00 - None -
Wed 00:00 - None -
Thu 00:00 - None -
Fri 00:00 - None -
Sat 00:00 - None -
"""
list_keys = {
"Sun":0,
"Mon":1,
"Tue":2,
"Wed":3,
"Thu":4,
"Fri":5,
"Sat":6,
}
self._updateItems(nxvretstr, subtree, nxvretstr_default, list_keys)
self.changed={}
# pack the schedule to commands, split by \n
def packSchedule(self):
tree = self
daymap={_('Sunday'):0, _('Monday'):1, _('Tuesday'):2, _('Wednesday'):3, _('Thursday'):4, _('Friday'):5, _('Saturday'):6}
retstr = ""
for item in self.changed:
day = self.changed[item]
scheline = tree.item(item)["values"][0].strip()
schelst = scheline.split(' ')
tmlst = schelst[0].split(':')
stype = "None"
if schelst[1] == "H":
stype = "House"
retstr += "SetSchedule Day " + str(daymap[day]) + " Hour " + tmlst[0] + " Min " + tmlst[1] + " " + stype + "\n"
L.debug("save schedule: " + retstr)
return retstr
class SensorTreeview(ttk.Treeview):
def __init__(self, parent):
ttk.Treeview.__init__(self, parent)
def initUI(self):
tree = self
tree["columns"]=("value")#,"max","min")
tree.column("value", anchor='center') #, width=100 )
#tree.column("max", width=100)
#tree.column("min", width=100)
tree.column('#0', anchor='w')
tree.heading('#0', text=_("Sensors"), anchor='w')
tree.heading("value", text=_("Value"))
#tree.heading("max", text=_("Max Value"))
#tree.heading("min", text=_("Min Value"))
self.subtree_digital = tree.insert('', 'end', "digital", text=_("Digital Sensors"))
self.subtree_analogy = tree.insert('', 'end', "analogy", text=_("Analog Sensors"))
self.subtree_buttons = tree.insert('', 'end', "buttons", text=_("Buttons"))
self.subtree_motors = tree.insert('', 'end', "motors", text=_("Motors"))
self.subtree_accel = tree.insert('', 'end', "accel", text=_("Accelerometer"))
self.subtree_charger = tree.insert('', 'end', "charger", text=_("Charger"))
self.updateDigitalSensors("")
self.updateButtons("")
self.updateAnalogSensors("")
self.updateMotors("")
self.updateAccel("")
self.updateCharger("")
# colors
tree.tag_configure('digiudef', background='grey')
tree.tag_configure('digion', background='#ff6699')
tree.tag_configure('digioff', background='white')
def getType(self, node):
if node == self.subtree_digital:
return "digital"
elif node == self.subtree_analogy:
return "analogy"
elif node == self.subtree_buttons:
return "buttons"
elif node == self.subtree_motors:
return "motors"
elif node == self.subtree_accel:
return "accel"
elif node == self.subtree_charger:
return "charger"
return "unknown"
def _updateDigitalSensors(self, nxvretstr, subtree, nxvretstr_default, list_keys, list_values):
tree = self
if nxvretstr == "":
# remove all of items in the tree
tree.delete(*tree.get_children(subtree))
# init the structure
nxvretstr=nxvretstr_default
items_children = self.get_children(subtree)
if items_children == None or len(items_children) < 1:
# create children
for itemstr in list_keys:
#L.debug("Digital Sensors add key: " + itemstr)
tree.insert(subtree, 'end', text=itemstr, values=(""))
items_children = self.get_children(subtree)
# parse the string
linestr = nxvretstr.strip() + '\n'
linelst = linestr.split('\n')
for i in range(0, len(linelst)):
line = linelst[i].strip()
if len(line) < 1:
break
columnlst = line.split(',')
if len(columnlst) > 1:
if columnlst[0] in list_keys:
idx = list_keys[columnlst[0]]
value = _("Unknown")
tag = "digiudef"
if columnlst[1] in list_values:
value = list_values[columnlst[1]][0]
tag = list_values[columnlst[1]][1]
#L.debug("Digital Sensors add key value: [" + str(idx) + "] " + str(items_children[idx]) + ": " + columnlst[0] + "=" + columnlst[1])
tree.item(items_children[idx], values=(value,), tags = (tag,), text=columnlst[0])
pass
def updateDigitalSensors(self, nxvretstr):
subtree = self.subtree_digital
nxvretstr_default="""Digital Sensor Name, Value
SNSR_DC_JACK_CONNECT,-1
SNSR_DUSTBIN_IS_IN,-1
SNSR_LEFT_WHEEL_EXTENDED,-1
SNSR_RIGHT_WHEEL_EXTENDED,-1
LSIDEBIT,-1
LFRONTBIT,-1
RSIDEBIT,-1
RFRONTBIT,-1
"""
list_keys = {
"SNSR_DC_JACK_CONNECT":0,
"SNSR_DUSTBIN_IS_IN":1,
"SNSR_LEFT_WHEEL_EXTENDED":2,
"SNSR_RIGHT_WHEEL_EXTENDED":3,
"LSIDEBIT":4,
"LFRONTBIT":5,
"RSIDEBIT":6,
"RFRONTBIT":7,
}
list_values = {
"0": (_("Released"), "digioff"),
"1": (_("Pressed"), "digion"),
}
self._updateDigitalSensors(nxvretstr, subtree, nxvretstr_default, list_keys, list_values)
def updateButtons(self, nxvretstr):
subtree = self.subtree_buttons
nxvretstr_default="""Button Name,Pressed
BTN_SOFT_KEY,-1
BTN_SCROLL_UP,-1
BTN_START,-1
BTN_BACK,-1
BTN_SCROLL_DOWN,-1
"""
list_keys = {
"BTN_SCROLL_UP":0,
"BTN_SCROLL_DOWN":1,
"BTN_BACK":2,
"BTN_START":3,
"BTN_SOFT_KEY":4,
}
list_values = {
"0": (_("Released"), "digioff"),
"1": (_("Pressed"), "digion"),
}
self._updateDigitalSensors(nxvretstr, subtree, nxvretstr_default, list_keys, list_values)
def _updateAnalogSensors(self, nxvretstr, subtree, nxvretstr_default, list_keys):
tree = self
if nxvretstr == "":
# remove all of items in the tree
tree.delete(*tree.get_children(subtree))
# init the structure
nxvretstr=nxvretstr_default
items_children = self.get_children(subtree)
if items_children == None or len(items_children) < 1:
# create children
for itemstr in list_keys:
tree.insert(subtree, 'end', text=itemstr, values=(""))
items_children = self.get_children(subtree)
# parse the string
linestr = nxvretstr.strip() + '\n'
linelst = linestr.split('\n')
for i in range(0, len(linelst)):
line = linelst[i].strip()
if len(line) < 1:
break
columnlst = line.split(',')
if len(columnlst) > 1:
if columnlst[0] in list_keys:
idx = list_keys[columnlst[0]]
tree.item(items_children[idx], values=(columnlst[1],), text=columnlst[0])
pass
def updateAnalogSensors(self, nxvretstr):
subtree = self.subtree_analogy
nxvretstr_default="""SensorName,Value
WallSensorInMM,-1,
BatteryVoltageInmV,-1,
LeftDropInMM,-1,
RightDropInMM,-1,
LeftMagSensor,-1,
RightMagSensor,-1,
UIButtonInmV,-1,
VacuumCurrentInmA,-1,
ChargeVoltInmV,-1,
BatteryTemp0InC,-1,
BatteryTemp1InC,-1,
CurrentInmA,-1,
SideBrushCurrentInmA,-1,
VoltageReferenceInmV,-1,
AccelXInmG,-1,
AccelYInmG,-1,
AccelZInmG,-1,
"""
list_keys = {
"WallSensorInMM":0,
"BatteryVoltageInmV":1,
"LeftDropInMM":2,
"RightDropInMM":3,
"LeftMagSensor":4,
"RightMagSensor":5,
"UIButtonInmV":6,
"VacuumCurrentInmA":7,
"ChargeVoltInmV":8,
"BatteryTemp0InC":9,
"BatteryTemp1InC":10,
"CurrentInmA":11,
"SideBrushCurrentInmA":12,
"VoltageReferenceInmV":13,
"AccelXInmG":14,
"AccelYInmG":15,
"AccelZInmG":16,
}
self._updateAnalogSensors(nxvretstr, subtree, nxvretstr_default, list_keys)
def updateMotors(self, nxvretstr):
subtree = self.subtree_motors
nxvretstr_default="""Parameter,Value
Brush_RPM,0
Brush_mA,0
Vacuum_RPM,0
Vacuum_mA,0
LeftWheel_RPM,0
LeftWheel_Load%,0
LeftWheel_PositionInMM,0
LeftWheel_Speed,0
RightWheel_RPM,0
RightWheel_Load%,0
RightWheel_PositionInMM,0
RightWheel_Speed,0
Charger_mAH, 0
SideBrush_mA,0
"""
list_keys = {
"Brush_RPM":0,
"Brush_mA":1,
"Vacuum_RPM":2,
"Vacuum_mA":3,
"LeftWheel_RPM":4,
"LeftWheel_Load%":5,
"LeftWheel_PositionInMM":6,
"LeftWheel_Speed":7,
"RightWheel_RPM":8,
"RightWheel_Load%":9,
"RightWheel_PositionInMM":10,
"RightWheel_Speed":11,
"Charger_mAH":12,
"SideBrush_mA":13,
}
self._updateAnalogSensors(nxvretstr, subtree, nxvretstr_default, list_keys)
def updateAccel(self, nxvretstr):
subtree = self.subtree_accel
nxvretstr_default="""Label,Value
PitchInDegrees,0.00
RollInDegrees,0.00
XInG,0.000
YInG,0.000
ZInG,0.000
SumInG,0.000
"""
list_keys = {
"PitchInDegrees":0,
"RollInDegrees":1,
"XInG":2,
"YInG":3,
"ZInG":4,
"SumInG%":5,
}
self._updateAnalogSensors(nxvretstr, subtree, nxvretstr_default, list_keys)
def updateCharger(self, nxvretstr):
subtree = self.subtree_charger
nxvretstr_default="""Label,Value
FuelPercent,-1
BatteryOverTemp,-1
ChargingActive,-1
ChargingEnabled,-1
ConfidentOnFuel,-1
OnReservedFuel,-1
EmptyFuel,-1
BatteryFailure,-1
ExtPwrPresent,-1
ThermistorPresent[0],-1
ThermistorPresent[1],-1
BattTempCAvg[0],-1
BattTempCAvg[1],-1
VBattV,-1
VExtV,-1
Charger_mAH,-1
"""
list_keys = {
"FuelPercent":0,
"BatteryOverTemp":1,
"ChargingActive":2,
"ChargingEnabled":3,
"ConfidentOnFuel":4,
"OnReservedFuel":5,
"EmptyFuel":6,
"BatteryFailure":7,
"ExtPwrPresent":8,
"ThermistorPresent[0]":9,
"ThermistorPresent[1]":10,
"BattTempCAvg[0]":11,
"BattTempCAvg[1]":12,
"VBattV":13,
"VExtV":14,
"Charger_mAH":15,
}
self._updateAnalogSensors(nxvretstr, subtree, nxvretstr_default, list_keys)
class MyTkAppFrame(ttk.Notebook): #(tk.Frame):
def show_battery_level(self, level):
self.style_battstat.configure("LabeledProgressbar", text="{0} % ".format(level))
self.progress_batt["value"]=level
#self.frame_status.update()
#self.progress_batt.update_idletasks()
def show_robot_version(self, msg):
if msg.find("GetVersion") >= 0:
set_readonly_text(self.text_version, msg)
else:
guilog.textarea_append(self.text_version, "\n\n" + msg)
def show_robot_time(self, msg):
self.lbl_synctime['text'] = msg
def show_robot_testmode(self, onoff=False):
if onoff:
self.lbl_testmode['text'] = _("ON")
self.lbl_testmode['fg'] = "red"
else:
self.lbl_testmode['text'] = _("OFF")
self.lbl_testmode['fg'] = "green"
# the functions for log file in status
def onSelectAllLogname(self, event):
self.combobox_logfile.tag_add(tk.SEL, "1.0", tk.END)
self.combobox_logfile.mark_set(tk.INSERT, "1.0")
self.combobox_logfile.see(tk.INSERT)
return 'break'
def onLogfileCheckChanged(self):
# read self.use_logfile changed by self.check_logfile
# check if the file exists
# start to log
return
def onLogfileSelected(self, event):
# read self.use_logfile changed by self.check_logfile
# change log file
return
def onSelectLogfile(self):
#dir_path = os.path.dirname(os.path.realpath(__file__))
pname_input = self.combobox_logfile.get().strip()
dir_path=os.path.dirname(os.path.realpath(pname_input))
if True != os.path.exists(dir_path):
dir_path = os.getcwd()
fname = fd.askopenfilename(
initialdir=dir_path,
filetypes=(
(_("Text files"), "*.txt"),
(_("All files"), "*.*")
)
)
if fname:
self.combobox_logfile.set(fname.strip())
return
def __init__(self, tk_frame_parent):
global MAXDIST
global CONST_RAD
#nb = ttk.Notebook(tk_frame_parent)
ttk.Notebook.__init__(self, tk_frame_parent)
nb = self
self.serv_cli = None
self.istestmode = False
self.mailbox = neatocmdapi.MailPipe()
# the error to disconnect socket
self.mid_socket_disconnect = self.mailbox.declair()
# the images for toggle buttons
self.img_ledon=tk.PhotoImage(file="ledred-on.gif")
self.img_ledoff=tk.PhotoImage(file="ledred-off.gif")
guilog.rClickbinder(tk_frame_parent)
# page for test pack()
#page_testpack = tk.Frame(nb)
#test_pack(page_testpack)
# page for test grid
#page_testgrid = tk.Frame(nb)
#myParent = nb
#main_container = page_testgrid
#test_grid(myParent, main_container)
# page for About
page_about = tk.Frame(nb)
lbl_about_head = tk.Label(page_about, text=_("About"), font=LARGE_FONT)
lbl_about_head.pack(side="top", fill="x", pady=10)
lbl_about_main = tk.Label(page_about
, font=NORM_FONT
, text="\n" + str_progname + "\n" + str_version + "\n"
+ _("Setup your Neato Robot") + "\n"
+ "\n"
+ _("Copyright © 2015-2016 The nxvControl Authors") + "\n"
+ "\n"
+ _("This program comes with absolutely no warranty.") + "\n"
+ _("See the GNU General Public License, version 3 or later for details.") + "\n"
)
lbl_about_main.pack(side="top", fill="x", pady=10)
# adding Frames as pages for the ttk.Notebook
# first page, which would get widgets gridded into it
page_conn = tk.Frame(nb)
# includes:
# connect with port selection or Serial-TCP connection;
# button to shutdown
# testmode indicator and button to enter/leave test mode
# the robot time, sync with pc
# textarea of version info
# log file name, enable/disable: all of connection message and input output will be here!
lbl_conn_head = tk.Label(page_conn, text=_("Connection"), font=LARGE_FONT)
lbl_conn_head.pack(side="top", fill="x", pady=10)
self.frame_status = ttk.LabelFrame(page_conn, text=_("Status"))
# connection
frame_cli = ttk.LabelFrame(page_conn, text=_("Conection"))
line=0
client_port_history = ('tcp://192.168.3.163:3333', 'dev://ttyACM0:115200', 'dev://ttyUSB0:115200', 'dev://COM11:115200', 'dev://COM12:115200', 'sim:', 'tcp://localhost:3333')
self.client_port = tk.StringVar()
lbl_cli_port = tk.Label(frame_cli, text=_("Connect to:"))
lbl_cli_port.grid(row=line, column=0, padx=5, sticky=tk.N+tk.S+tk.W)
combobox_client_port = ttk.Combobox(frame_cli, textvariable=self.client_port)
combobox_client_port['values'] = client_port_history
combobox_client_port.grid(row=line, column=1, padx=5, pady=5, sticky=tk.N+tk.S+tk.W)
combobox_client_port.current(0)
# Buttons
self.btn_cli_connect = tk.Button(frame_cli, text=_("Connect"), command=self.do_cli_connect)
self.btn_cli_connect.grid(row=line, column=2, columnspan=1, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
#btn_cli_connect.pack(side="left", fill="both", padx=5, pady=5, expand=True)
self.btn_cli_disconnect = tk.Button(frame_cli, text=_("Disconnect"), state=tk.DISABLED, command=self.do_cli_disconnect)
self.btn_cli_disconnect.grid(row=line, column=3, columnspan=1, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
#btn_cli_disconnect.pack(side="left", fill="both", padx=5, pady=5, expand=True)
frame_cli.pack(side="top", fill="x", pady=10)
self.status_isactive = False # shall we refresh the time and battery info?
# status
line = 0 # line
lbl_synctime_conn = tk.Label(self.frame_status, text=_("Robot Time:"))
lbl_synctime_conn.grid(row=line, column=0, padx=5, sticky=tk.N+tk.S+tk.W)
self.lbl_synctime = tk.Label(self.frame_status, text="00:00:00")
self.lbl_synctime.grid(row=line, column=1, padx=5)
#self.lbl_synctime.pack(side="right", fill="x", pady=10)
btn_synctime = tk.Button(self.frame_status, text=_("Sync PC time to robot"), command=self.set_robot_time_from_pc)
btn_synctime.grid(row=line, column=2, padx=5, sticky=tk.N+tk.S+tk.E+tk.W)
#btn_synctime.pack(side="right", fill="x", pady=10)
line += 1
lbl_testmode_conn = tk.Label(self.frame_status, text=_("Test Mode:"))
lbl_testmode_conn.grid(row=line, column=0, padx=5)
self.lbl_testmode = tk.Label(self.frame_status, text=_("Unknown"))
self.lbl_testmode.grid(row=line, column=1, padx=5)
btn_testmode_on = tk.Button(self.frame_status, text=_("Test ON"), command=lambda: self.set_robot_testmode(True))
btn_testmode_off = tk.Button(self.frame_status, text=_("Test OFF"), command=lambda: self.set_robot_testmode(False))
btn_testmode_on.grid(row=line, column=2, padx=5, sticky=tk.N+tk.S+tk.W)
btn_testmode_off.grid(row=line, column=2, padx=5, sticky=tk.N+tk.S+tk.E)
line += 1
lbl_battstat_conn = tk.Label(self.frame_status, text=_("Battery Status:"))
lbl_battstat_conn.grid(row=line, column=0, padx=5)
self.style_battstat = ttk.Style(self.frame_status)
# add the label to the progressbar style
self.style_battstat.layout("LabeledProgressbar",
[('LabeledProgressbar.trough',
{'children': [('LabeledProgressbar.pbar',
{'side': 'left', 'sticky': 'ns'}),
("LabeledProgressbar.label",
{"sticky": ""})],
'sticky': 'nswe'})])
self.style_battstat.configure('LabeledProgressbar', foreground='red', background='#00ff00')
self.progress_batt = ttk.Progressbar(self.frame_status, orient=tk.HORIZONTAL, style="LabeledProgressbar", mode='determinate', length=300)
self.progress_batt.grid(row=line, column=1, padx=5)
#btn_battstat = tk.Button(self.frame_status, text="")
#btn_battstat.grid(row=line, column=2, padx=5, sticky=tk.E)
line += 1
lbl_battstat_conn = tk.Label(self.frame_status, text=_("Version:"))
lbl_battstat_conn.grid(row=line, column=0, padx=5)
self.text_version = ScrolledText(self.frame_status, wrap=tk.WORD, height=10)
self.text_version.configure(state='disabled')
#self.text_version.pack(expand=True, fill="both", side="top")
self.text_version.grid(row=line, column=1, columnspan=2, padx=5)
self.text_version.bind("<1>", lambda event: self.text_version.focus_set()) # enable highlighting and copying
# save log file?
#line += 1
#self.use_logfile = tk.StringVar()
#self.check_logfile = ttk.Checkbutton(self.frame_status, text=_("Use Log File"),
#command=self.onLogfileCheckChanged, variable=self.use_logfile,
#onvalue='metric', offvalue='imperial')
#self.check_logfile.grid(row=line, column=0, padx=5)
#sellogfiles = tk.StringVar()
#self.combobox_logfile = ttk.Combobox(self.frame_status, textvariable=sellogfiles)
#self.combobox_logfile.bind('<<ComboboxSelected>>', self.onLogfileSelected)
#self.combobox_logfile.bind("<Control-Key-a>", self.onSelectAllLogname)
#self.combobox_logfile.bind("<Control-Key-A>", self.onSelectAllLogname)
#self.combobox_logfile['values'] = ('neatologfile.txt', '/tmp/neatologfile.txt', '$HOME/logfile.txt')
#self.combobox_logfile.current(0)
#self.combobox_logfile.grid(row=line, column=1, sticky=tk.W+tk.E)
#self.button_select_logfile = tk.Button(self.frame_status, text=" ... ", command=self.onSelectLogfile)
#self.button_select_logfile.grid(row=line, column=2, sticky=tk.W)
frame_cli.pack(side="top", fill="x", pady=10)
self.frame_status.pack(side="top", fill="both", pady=10)
#ttk.Separator(page_conn, orient=HORIZONTAL).pack()
#b1 = tk.Button(page_about, text=_("Button 1"))
# page for commands
page_command = tk.Frame(nb)
# combox list for all available know commands, select one will show the help message in text area
# edit line which supports history
# output
# help message area
lbl_command_head = tk.Label(page_command, text=_("Commands"), font=LARGE_FONT)
lbl_command_head.pack(side="top", fill="x", pady=10)
frame_top = tk.Frame(page_command)#, background="green")
frame_bottom = tk.Frame(page_command)#, background="yellow")
frame_top.pack(side="top", fill="both", expand=True)
frame_bottom.pack(side="bottom", fill="x", expand=False)
self.text_cli_command = ScrolledText(frame_top, wrap=tk.WORD)
#self.text_cli_command.insert(tk.END, "Some Text\ntest 1\ntest 2\n")
self.text_cli_command.configure(state='disabled')
self.text_cli_command.pack(expand=True, fill="both", side="top")
# make sure the widget gets focus when clicked
# on, to enable highlighting and copying to the
# clipboard.
self.text_cli_command.bind("<1>", lambda event: self.text_cli_command.focus_set())
btn_clear_cli_command = tk.Button(frame_bottom, text=_("Clear"), command=lambda: (set_readonly_text(self.text_cli_command, ""), self.text_cli_command.update_idletasks()) )
btn_clear_cli_command.pack(side="left", fill="x", padx=5, pady=5, expand=False)
self.cli_command = tk.StringVar()
self.combobox_cli_command = ttk.Combobox(frame_bottom, textvariable=self.cli_command)
self.combobox_cli_command['values'] = ('Help', 'GetAccel', 'GetButtons', 'GetCalInfo', 'GetCharger', 'GetDigitalSensors', 'GetErr', 'GetLDSScan', 'GetLifeStatLog', 'GetMotors', 'GetSchedule', 'GetTime', 'GetVersion', 'GetWarranty', 'PlaySound 0', 'Clean House', 'DiagTest MoveAndBump', 'DiagTest DropTest', 'RestoreDefaults', 'SetDistanceCal DropMinimum', 'SetFuelGauge Percent 100', 'SetIEC FloorSelection carpet', 'SetLCD BGWhite', 'SetLDSRotation On', 'SetLED BacklightOn', 'SetMotor VacuumOn', 'SetSchedule Day Sunday Hour 17 Min 0 House ON', 'SetSystemMode Shutdown', 'SetTime Day Sunday Hour 12 Min 5 Sec 25', 'SetWallFollower Enable', 'TestMode On', 'Upload' )
self.combobox_cli_command.pack(side="left", fill="both", padx=5, pady=5, expand=True)
self.combobox_cli_command.bind("<Return>", self.do_cli_run_ev)
self.combobox_cli_command.bind("<<ComboboxSelected>>", self.do_select_clicmd)
self.combobox_cli_command.current(0)
btn_run_cli_command = tk.Button(frame_bottom, text=_("Run"), command=self.do_cli_run)
btn_run_cli_command.pack(side="right", fill="x", padx=5, pady=5, expand=False)
# page for scheduler
page_sche = tk.Frame(nb)
# indicator, enable/disable button
# save/load file
# the list of scheduler
lbl_sche_head = tk.Label(page_sche, text=_("Schedule"), font=LARGE_FONT)
lbl_sche_head.pack(side="top", fill="x", pady=10)
frame_top = tk.Frame(page_sche)#, background="green")
frame_bottom = tk.Frame(page_sche)#, background="yellow")
frame_top.pack(side="top", fill="both", expand=True)
frame_bottom.pack(side="bottom", fill="x", expand=False)
self.mid_query_schedule = -1
self.etv_schedule = ScheduleTreeview(frame_top)
self.etv_schedule.initUI()
self.etv_schedule.pack(pady=5, fill="both", side="left", expand=True)
self.schedule_isenabled = False
devstr = _("Schedule")
self.btn_enable_schedule = guilog.ToggleButton(frame_bottom, txtt=_("Enabled: ")+devstr, txtr=_("Disabled: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_schedule_enable)
self.btn_enable_schedule.pack(pady=5, side="left")
btn_save_schedule = tk.Button(frame_bottom, text=_("Save schedule"), command=lambda: (btn_save_schedule.focus_set(), self.guiloop_save_schedule(), ))
btn_save_schedule.pack(side="right", fill="x", padx=5, pady=5, expand=False)
btn_get_schedule = tk.Button(frame_bottom, text=_("Get schedule"), command=lambda: (btn_get_schedule.focus_set(), self.guiloop_get_schedule(), ))
btn_get_schedule.pack(side="right", fill="x", padx=5, pady=5, expand=False)
# page for sensors
page_sensors = tk.Frame(nb)
# the list of sensor status, includes sensor and value
# indicator of testmode, no control
# indicator, enable/disable auto update
lbl_sensor_head = tk.Label(page_sensors, text=_("Sensors"), font=LARGE_FONT)
lbl_sensor_head.pack(side="top", fill="x", pady=10)
frame_top = tk.Frame(page_sensors)#, background="green")
frame_bottom = tk.Frame(page_sensors)#, background="yellow")
frame_top.pack(side="top", fill="both", expand=True)
frame_bottom.pack(side="bottom", fill="x", expand=False)
self.mid_query_digitalsensors = -1
self.mid_query_analogysensors = -1
self.mid_query_buttonssensors = -1
self.mid_query_motorssensors = -1
self.mid_query_accelsensors = -1
self.tab_sensors_isactive = False # if the tab is "Sensors status"
# flag to signal the command is finished
self.sensors_request_full_digital = False
self.sensors_request_full_analogy = False
self.sensors_request_full_buttons = False
self.sensors_request_full_motors = False
self.sensors_request_full_accel = False
self.sensors_request_full_charger = False
self.sensors_update_isopen_digital = False # if the tree is open?
self.sensors_update_isopen_analogy = False
self.sensors_update_isopen_buttons = False
self.sensors_update_isopen_motors = False
self.sensors_update_isopen_accel = False
self.sensors_update_isopen_charger = False
self.sensors_update_isactive = False
devstr = _("Update Sensors")
self.btn_sensors_update_enable = guilog.ToggleButton(frame_bottom, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_sensors_update_enable)
self.btn_sensors_update_enable.pack(pady=5, side="right")
self.sensor_tree_status = SensorTreeview(frame_top)
self.sensor_tree_status.initUI()
self.sensor_tree_status.pack(pady=5, fill="both", side="left", expand=True)
# <<TreeviewOpen>> <<TreeviewClose>>
self.sensor_tree_status.bind('<<TreeviewOpen>>', lambda ev:self.guiloop_sensors_changed_to(ev,True))
self.sensor_tree_status.bind('<<TreeviewClose>>', lambda ev:self.guiloop_sensors_changed_to(ev,False))
scrollbar_y_tree = ttk.Scrollbar(frame_top, orient="vertical")
scrollbar_y_tree.configure(command=self.sensor_tree_status.yview)
self.sensor_tree_status.configure(yscrollcommand=scrollbar_y_tree.set)
scrollbar_y_tree.pack( side = tk.RIGHT, fill=tk.Y )
#scrollbar_x_tree = ttk.Scrollbar(frame_top, orient="horizontal")
#scrollbar_x_tree.configure(command=self.sensor_tree_status.xview)
#self.sensor_tree_status.configure(xscrollcommand=scrollbar_x_tree.set)
#scrollbar_x_tree.pack( side = tk.BOTTOM, fill=tk.X )
# page for LiDAR
page_lidar = tk.Frame(nb)
# graph for current data
# indicator, enable/disable scanning
# buttons to remote control: left/right/up/down/rotate
lbl_lidar_head = tk.Label(page_lidar, text=_("LiDAR"), font=LARGE_FONT)
lbl_lidar_head.pack(side="top", fill="x", pady=10)
frame_top = tk.Frame(page_lidar)#, background="green")
frame_bottom = tk.Frame(page_lidar)#, background="yellow")
frame_top.pack(side="top", fill="both", expand=True)
frame_bottom.pack(side="bottom", fill="x", expand=False)
self.canvas_lidar = tk.Canvas(frame_top)
self.canvas_lidar.pack(side="top", fill="both", expand="yes", pady=10)
self.canvas_lidar_points = {} # 360 items, 0 - 359 degree, lines
self.canvas_lidar_lines = {}
self.map_sin_lidar = {}
self.map_cos_lidar = {}
for i in range(0,360):
self.map_cos_lidar[i] = math.cos(CONST_RAD * i) / MAXDIST
self.map_sin_lidar[i] = math.sin(CONST_RAD * i) / MAXDIST
self.mid_query_lidar = -1
self.canvas_lidar_isfocused = False
self.canvas_lidar_isactive = False
self.canvas_lidar_request_full = False
self.state_wheel = STATE_STOP
self.speed_wheel = 0
devstr = _("LiDAR")
self.btn_lidar_enable = guilog.ToggleButton(frame_bottom, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_lidar_enable)
self.btn_lidar_enable.pack(pady=5, side="left")
self.setup_keypad_navigate(self.canvas_lidar)
self.wheelctrl_isactive = False
devstr = _("Wheels Controlled by Keypad")
self.btn_wheelctrl_enable = guilog.ToggleButton(frame_bottom, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_wheelctrl_enable)
self.btn_wheelctrl_enable.pack(pady=5, side="right")
# page for motors
page_moto = tk.Frame(nb)
# list of motors and each has indicator, start/stop button
# warnning message: flip the robot upside down so the wheels are faceing up, before enable wheels moto!
lbl_moto_head = tk.Label(page_moto, text=_("Motors"), font=LARGE_FONT)
lbl_moto_head.pack(side="top", fill="x", pady=10)
s = ttk.Scale(page_moto, orient=tk.HORIZONTAL, length=200, from_=1.0, to=100.0)
devstr = _("Left Wheel")
self.btn_enable_leftwheel = guilog.ToggleButton(page_moto, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_enable_leftwheel)
self.btn_enable_leftwheel.pack(pady=5)
devstr = _("Right Wheel")
self.btn_enable_rightwheel = guilog.ToggleButton(page_moto, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_enable_rightwheel )
self.btn_enable_rightwheel.pack(pady=5)
devstr = _("LiDAR Motor")
self.btn_enable_lidarmoto = guilog.ToggleButton(page_moto, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_enable_lidarmoto )
self.btn_enable_lidarmoto.pack(pady=5)
devstr = _("Vacuum")
self.btn_enable_vacuum = guilog.ToggleButton(page_moto, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_enable_vacuum )
self.btn_enable_vacuum.pack(pady=5)
devstr = _("Brush")
self.btn_enable_brush = guilog.ToggleButton(page_moto, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_enable_brush )
self.btn_enable_brush.pack(pady=5)
devstr = _("Side Brush")
self.btn_enable_sidebrush = guilog.ToggleButton(page_moto, txtt=_("ON: ")+devstr, txtr=_("OFF: ")+devstr, imgt=self.img_ledon, imgr=self.img_ledoff, command=self.guiloop_enable_sidebrush )
self.btn_enable_sidebrush.pack(pady=5)
# page for Recharge
page_recharge = tk.Frame(nb)
# only available when connected to Serial port directly, not for TCP
lbl_recharge_head = tk.Label(page_recharge, text=_("Recharge"), font=LARGE_FONT)
lbl_recharge_head.pack(side="top", fill="x", pady=10)