-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathGUI.py
1418 lines (1148 loc) · 56.2 KB
/
GUI.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
import math, ConfigParser, ast, os, re, time, sys
import wx
import PoMoCoModule
import webbrowser
import wx.lib.agw.hyperlink as hl
if os.name == 'nt': #sys.platform == 'win32':
from serial.tools.list_ports_windows import *
elif os.name == 'posix':
from serial.tools.list_ports_posix import *
else:
raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
#naughty magic constants
ROBOTS_FOLDER_PATH = "Robots/"
ROBOT_FOLDER_PATH = "Robots/Hexy V1/"
#----------------------------------------------------------------------
def sendNote(note):
PoMoCoModule.Node.modules[note.receiver].put(note)
def writeAndSendNote(type, message, receiver):
toSend = PoMoCoModule.Note()
toSend.sender = "GUI"
toSend.type = type
toSend.message = message
toSend.receiver = receiver
sendNote(toSend)
class RedirectText(object):
def __init__(self,aWxTextCtrl):
self.out=aWxTextCtrl
def write(self,string):
wx.CallAfter(self.out.WriteText, string)
class MainGui(wx.Frame):
def __init__(self):
super(MainGui, self).__init__(None, title="PoMoCo 2.0 - Position and Motion Controller", size=(730, 750))
self.initUI()
#self.LoadRobot(ROBOT_FOLDER_PATH)
self.Show()
def initUI(self):
self.topPanel = wx.Panel(self)
if os.name == 'nt':
self.topPanel.SetFont(wx.Font(8,wx.FONTFAMILY_MODERN,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL, faceName="Helvetica"))
self.SetBackgroundColour('LIGHT_GREY')
elif os.name == 'posix':
self.topPanel.SetFont(wx.Font(12,wx.FONTFAMILY_MODERN,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL, faceName="Helvetica"))
self.SetBackgroundColour('LIGHT GREY')
# robot select
robotPanel = wx.Panel(self.topPanel, size=(100,30))
self.robots = RobotSelect(robotPanel)
# side button for executing Moves
movePanel = wx.Panel(self.topPanel, size=(100, 1000))
self.moveButtons = MoveControls(movePanel)
# controller control panel
controllerPanel = wx.Panel(self.topPanel)
controller = ControllerPanel(controllerPanel)
controller.SetFirmwareV("?")
self.controller = controller
# Servo control and visualization area
servoPanel = wx.Panel(self.topPanel, size=(600, 521))
self.servos = ServoWidget(servoPanel, 600, 521)
# Servo show/hide toggle panel
togglePanel = wx.Panel(self.topPanel)
self.toggle = ServoToggle(togglePanel)
for button in self.toggle.toggleButtons:
button.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggleServo)
self.toggle.disableAllBtn.Bind(wx.EVT_BUTTON, self.OnDisableAll)
self.toggle.centerAllBtn.Bind(wx.EVT_BUTTON, self.OnCenterAll)
self.toggle.enableAllBtn.Bind(wx.EVT_BUTTON, self.OnEnableAll)
self.toggle.offsetsEditBtn.Bind(wx.EVT_BUTTON, self.OnEditOffsets)
#console panel
self.consoleBox = wx.TextCtrl(self.topPanel, size=(380, 230), pos=(5,5), style=wx.TE_MULTILINE)
sys.stdout = RedirectText(self.consoleBox)
### Main GUI Layout
#Left Panel
leftBox = wx.BoxSizer(wx.VERTICAL)
leftBox.Add(robotPanel, proportion=0, border=5)
leftBox.Add(movePanel, proportion=0, border=5)
#Middle Panel
middleBox = wx.BoxSizer(wx.VERTICAL)
middleBox.Add(controllerPanel, proportion=0, border=5,flag=wx.CENTER)
middleBox.Add(servoPanel, proportion=1, border=5,flag=wx.CENTER)
middleBox.Add(togglePanel, proportion=0, border=5,flag=wx.CENTER)
middleBox.AddSpacer(5, proportion=0)
middleBox.Add(self.consoleBox, proportion=2, border=5, flag=wx.EXPAND|wx.CENTER)
middleBox.AddSpacer(5, proportion=0)
#Right Panel
rightBox = wx.BoxSizer(wx.VERTICAL)
rightBox.AddSpacer(5, proportion=0)
#Top Panel
topBox = wx.BoxSizer(wx.HORIZONTAL)
topBox.Add(leftBox, proportion=0, flag=wx.EXPAND)
topBox.Add(middleBox, proportion=1, flag=wx.EXPAND|wx.CENTER)
topBox.Add(rightBox, proportion=0, flag=wx.EXPAND|wx.CENTER)
self.topPanel.SetSizerAndFit(topBox)
### menu bar
menubar = wx.MenuBar()
self.SetMenuBar(menubar)
fileMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
saveServosMenuItem = fileMenu.Append(wx.NewId(), "Save Servos", "Save the state of the servos in a file")
self.Bind(wx.EVT_MENU, self.OnSaveServos, saveServosMenuItem)
loadServosMenuItem = fileMenu.Append(wx.NewId(), "Load Servos", "Load the state of the servos from a file")
self.Bind(wx.EVT_MENU, self.OnLoadServos, loadServosMenuItem)
exitMenuItem = fileMenu.Append(wx.NewId(), "Exit", "Exit the application")
self.Bind(wx.EVT_MENU, self.OnExit, exitMenuItem)
helpMenu = wx.Menu()
menubar.Append(helpMenu, '&Help')
servoCalibrationWizard = helpMenu.Append(wx.NewId(), "Calibrate Servo Wizard", "Calibrate the Robot's Servos")
self.Bind(wx.EVT_MENU, self.LaunchServoCalibrationWizard, servoCalibrationWizard)
usingPoMoCo = helpMenu.Append(wx.NewId(), "How to use PoMoCo", "Help on how to use PoMoCo")
self.Bind(wx.EVT_MENU, self.UsingPoMoCo, usingPoMoCo)
aboutPoMoCo = helpMenu.Append(wx.NewId(), "About PoMoCo", "Information about PoMoCo")
self.Bind(wx.EVT_MENU, self.LaunchAboutPage, aboutPoMoCo)
def UpdateServoPos(self, num, pos):
for servo in self.servos.servos:
if servo.num == num:
servo.SetDeg(pos)
servo.Refresh()
def UpdateServoOffset(self, num, offset):
for servo in self.servos.servos:
if servo.num == num:
servo.SetOffset(offset)
servo.Refresh()
def UpdateServoActive(self, num, state):
for servo in self.servos.servos:
if servo.num == num:
servo.SetActive(state)
servo.Refresh()
def UpdateConnectionState(self, state):
self.controller.SetConnectionStatus(state)
def UpdatePortList(self, portList):
self.controller.SetPortList(portList)
def UpdateFirmwareVersion(self, version):
self.controller.SetFirmwareV(str(version))
def UpdateArduinoCode(self, code):
self.moveButtons.updateCodeBox(code)
def ServoCalibrationWizard(self, evt):
pass
def UsingPoMoCo(self, evt):
webbrowser.open_new_tab("http://arcbotics.com/products/pomoco/how-to-use-pomoco/")
def LaunchAboutPage(self, evt):
self.aboutPageItem = AboutPage(self.topPanel, 1)
def LaunchServoCalibrationWizard(self, evt):
self.ServoCalibrationWizard = ServoCalibrationWizard(self.topPanel, 1)
def LoadRobot(self, folderPath):
Config = ConfigParser.ConfigParser()
Config.read(folderPath+"robot.inf")
self.robotName = Config.get('robot', 'name')
self.robotVersion = Config.get('robot', 'version')
self.controllerName = Config.get('robot', 'controller')
robotMovesFolder = Config.get('robot', 'movesfolder')
mainFileName = Config.get('robot', 'mainfile')
servoFileName = Config.get('robot', 'servofile')
imageFileName = Config.get('robot', 'imagefile')
self.moveButtons.SetMovesFolder(folderPath+robotMovesFolder)
self.LoadServoConfig(folderPath + servoFileName)
bmp = wx.Bitmap(folderPath+imageFileName)
self.servos.SetBackgroundImage(bmp)
self.Refresh()
def OnExit(self, evt):
self.Close()
pass
def OnSaveServos(self, evt):
saveFileDialog = wx.FileDialog(self, "Save servo file", "", "", "inf files (*.inf)|*.inf", wx.FD_SAVE)
if saveFileDialog.ShowModal() == wx.ID_CANCEL:
return # the user changed idea...
with open(saveFileDialog.GetPath(), 'w') as cfgFile:
Config = ConfigParser.ConfigParser()
for servo in self.servos.servos:
numStr = "servo_%.2d"%int(servo.num)
Config.add_section(numStr)
Config.set(numStr,'num',servo.num)
Config.set(numStr,'active',servo.active)
Config.set(numStr,'deg',servo.deg)
Config.set(numStr,'offset',servo.offset)
Config.set(numStr,'visible',servo.visible)
Config.set(numStr,'posX',servo.pos[0])
Config.set(numStr,'posY',servo.pos[1])
Config.set(numStr,'joint',servo.joint)
Config.write(cfgFile)
cfgFile.close()
def OnLoadServos(self, evt):
openFileDialog = wx.FileDialog(self, "Open servo file", "", "", "inf files (*.inf)|*.inf", wx.FD_OPEN)
if openFileDialog.ShowModal() == wx.ID_CANCEL:
return # the user changed idea...
self.LoadServoConfig(openFileDialog.GetPath())
def LoadServoConfig(self, filePath):
Config = ConfigParser.ConfigParser()
Config.read(filePath)
self.servos.servos = []
for servo in Config.sections():
num = int(Config.get(servo, 'num'))
posX = int(Config.get(servo, 'posX'))
posY = int(Config.get(servo, 'posY'))
pos = (posX, posY)
deg = float(Config.get(servo, 'deg'))
offset = float(Config.get(servo, 'offset'))
visible = ast.literal_eval(Config.get(servo, 'visible'))
active = ast.literal_eval(Config.get(servo, 'active'))
joint = str(Config.get(servo, 'joint'))
self.servos.AddServo(num, pos, deg, offset, visible, active, joint)
button = self.toggle.GetButton(num)
if button:
button.SetValue(visible)
self.Refresh()
def OnToggleServo(self, evt):
button = evt.GetEventObject()
servo = self.servos.getServo(button.GetLabel())
if servo:
servo.visible = button.GetValue()
servo.Render()
else:
servoNum = int(button.GetLabel())
self.servos.AddServo(servoNum, (0,0), active=False)
self.Refresh()
def OnEditOffsets(self, evt):
#show the servo offsets for writing
for servo in self.servos.servos:
servo.OffsetsToggle()
servo.Render()
self.Refresh()
def OnWriteOffsets(self, evt):
#write that shit to the controller
pass
def OnDisableAll(self, evt):
for servo in self.servos.servos:
servo.SetActive(False)
servo.Render()
writeAndSendNote("RequestDisableAll", "", "robot")
self.Refresh()
def OnEnableAll(self, evt):
for servo in self.servos.servos:
servo.SetActive(True)
servo.Render()
writeAndSendNote("RequestEnableAll", "", "robot")
self.Refresh()
def OnCenterAll(self, evt):
for servo in self.servos.servos:
servo.SetDeg(0)
servo.Render()
writeAndSendNote("RequestCenterAll", "", "robot")
self.Refresh()
class AboutPage(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self, parent, id, 'Hexy Servo Calibration Wizard')
wx.Frame.CenterOnScreen(self)
self.panel = wx.Panel(self)
self.vertical = wx.BoxSizer(wx.VERTICAL)
text = "PoMoCo (Postition and Moction Controller) is an open-source robot control application developed by" \
"ArcBotics LLC."
part1 = wx.StaticText(self.panel, -1, text, style=wx.ALIGN_LEFT)
hyper1 = hl.HyperLinkCtrl(self.panel, -1, "http://www.arcbotics.com\n", URL="http://www.arcbotics.com")
text = "More information is available on it's homepage at:"
part2 = wx.StaticText(self.panel, -1, text, style=wx.ALIGN_LEFT)
hyper2 = hl.HyperLinkCtrl(self.panel, -1, "http://arcbotics.com/products/pomoco\n", URL="http://arcbotics.com/products/pomoco")
text = "or at its github page at:"
part3 = wx.StaticText(self.panel, -1, text, style=wx.ALIGN_LEFT)
hyper3 = hl.HyperLinkCtrl(self.panel, -1, "http://github.com/arcbotics/github\n", URL="http://github.com/arcbotics/github")
text = "PoMoCo is developed and released under the MIT License:\n" \
"\n" \
"The MIT License (MIT)\n" \
"Copyright 2015 ArcBotics LLC.,\n" \
"http://arcbotics.com\n" \
"\n" \
"Permission is hereby granted, free of charge, to any person obtaining a copy\n" \
"of this software and associated documentation files (the 'Software'), to deal\n" \
"in the Software without restriction, including without limitation the rights\n" \
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" \
"copies of the Software, and to permit persons to whom the Software is\n" \
"furnished to do so, subject to the following conditions:\n" \
"\n" \
"The above copyright notice and this permission notice shall be included in\n" \
"all copies or substantial portions of the Software.\n" \
"\n" \
"THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" \
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" \
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" \
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" \
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" \
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" \
"THE SOFTWARE.\n"
part4 = wx.StaticText(self.panel, -1, text, style=wx.ALIGN_LEFT)
self.vertical.Add(part1, border=5, flag=wx.LEFT|wx.RIGHT|wx.TOP)
self.vertical.Add(hyper1, border=5, flag=wx.LEFT|wx.RIGHT)
self.vertical.Add(part2, border=5, flag=wx.LEFT|wx.RIGHT)
self.vertical.Add(hyper2, border=5, flag=wx.LEFT|wx.RIGHT)
self.vertical.Add(part3, border=5, flag=wx.LEFT|wx.RIGHT)
self.vertical.Add(hyper3, border=5, flag=wx.LEFT|wx.RIGHT)
self.vertical.Add(part4, border=5, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM)
self.panel.SetSizerAndFit(self.vertical)
self.Fit()
self.Show()
class ServoCalibrationWizard(wx.Frame):
def __init__(self,parent,id):
self.activeServo = None
self.parent = parent
self.id = id
self.jointCounter = 0
self.servoOrder = [5,6,7, 9,10,11, 13,14,15, 18, 17, 16, 22,21,20, 26,25,24, 31]
self.servoPosition = ["Front Left Foot", "Front Left Thigh", "Front Left Hip",
"Middle Left Foot", "Middle Left Thigh", "Middle Left Hip",
"Back Left Foot", "Back Left Thigh", "Back Left Hip",
"Back Right Foot", "Back Right Thigh", "Back Right Hip",
"Middle Right Foot", "Middle Right Thigh", "Middle Right Hip",
"Front Right Foot", "Front Right Thigh", "Front Right Hip",
"Head"]
self.servoType = ["Foot", "Thigh", "Hip",
"Foot", "Thigh", "Hip",
"Foot", "Thigh", "Hip",
"Foot", "Thigh", "Hip",
"Foot", "Thigh", "Hip",
"Foot", "Thigh", "Hip",
"Head"]
self.offsetChoices = {}
self.servoMapLocations = {5:[53,47], 6:[70,70], 7:[85,91],
9:[16,158], 10:[34,161], 11:[57,163],
13:[64,261], 14:[80,245], 15:[94,229],
18:[236,260], 17:[222,242], 16:[205,227],
22:[289,157], 21:[264,158], 20:[240,160],
26:[240,46], 25:[225,67], 24:[210,87],
31:[148,89]}
self.initUI()
for servo in self.servoOrder:
writeAndSendNote("SetServoActive", "%d,%s"%(servo, "inactive"), "robot")
self.startCalibratingServo()
def initUI(self):
wx.Frame.__init__(self, self.parent, self.id, 'Hexy Servo Calibration Wizard')
wx.Frame.CenterOnScreen(self)
self.panel = wx.Panel(self)
#Window text at top
self.vertical = wx.BoxSizer(wx.VERTICAL)
calibrationTitle = wx.StaticText(self.panel, -1, "Calibrating Hexy", style=wx.ALIGN_CENTER)
font = wx.Font(18, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
calibrationTitle.SetFont(font)
self.vertical.Add(calibrationTitle, border=10, flag=wx.ALL|wx.CENTER)
normalFont = wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
#Left panel - overall guide on which servo is being calibrated
self.leftBox = wx.BoxSizer(wx.VERTICAL)
self.servoTitle = wx.StaticText(self.panel, -1, "Joint 00/18 - None - Servo -1", style=wx.ALIGN_CENTER)
self.servoTitle.SetFont(normalFont)
self.leftBox.Add(self.servoTitle, 0, wx.CENTER)
#image of hexy being calibrated, showing which servo is currently being calibrated
#self.calGuideImage = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.BitmapFromImage(wx.Image('Images//robot_300.jpg', wx.BITMAP_TYPE_ANY)))
#self.leftBox.Add(self.calGuideImage, border=10, flag=wx.ALL)
#alternate image that is capable of drawing servos onto
self.drawPanel = wx.Panel(self, size=(300, 300))
self.drawPanel.Bind(wx.EVT_PAINT, self.OnPaint)
self.drawPanel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.selectBlinkOn = True #controls whether the blinking servo is blinked on or off
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.flashCurrentServo, self.timer)
self.timer.Start(300)
self.leftBox.Add(self.drawPanel, border=10, flag=wx.ALL)
#buttons to choose previous/next servo
self.prevNextButtons = wx.BoxSizer(wx.HORIZONTAL)
self.prevServoBtn = wx.Button(self.panel, label="Previous")
self.prevServoBtn.Bind(wx.EVT_BUTTON, self.prevServo)
self.prevNextButtons.Add(self.prevServoBtn, 0, wx.LEFT)
self.nextServoBtn = wx.Button(self.panel, label="Next")
self.nextServoBtn.Bind(wx.EVT_BUTTON, self.nextServo)
self.prevNextButtons.Add(self.nextServoBtn, 0, wx.RIGHT)
self.leftBox.Add(self.prevNextButtons, 1, wx.CENTER)
#Right pane - calibrating the individual servo
self.rightBox = wx.BoxSizer(wx.VERTICAL)
instructionTitle = wx.StaticText(self.panel, -1, "Adjust below until aligned as shown", style=wx.ALIGN_CENTER)
instructionTitle.SetFont(normalFont)
self.rightBox.Add(instructionTitle, 0, wx.CENTER)
img = wx.EmptyImage(300,300)
self.jointGuideImage = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.BitmapFromImage(wx.Image('Images//Hip_Guide_300.jpg', wx.BITMAP_TYPE_ANY)))
self.rightBox.Add(self.jointGuideImage, border=10, flag=wx.ALL)
self.offsetAdjustSizer = wx.BoxSizer(wx.HORIZONTAL)
self.offsetSlider = wx.Slider(self.panel, id=0, value=0, minValue=-30.0, maxValue=30.0, size=(250, -1), style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS )
self.offsetSlider.Bind(wx.EVT_SLIDER, self.changeOffset)
self.offsetAdjustSizer.Add(self.offsetSlider, 0, border=5)
self.rightBox.Add(self.offsetAdjustSizer, 0, wx.CENTER)
#Bottom portion - finish calibration
self.twoBoxes = wx.BoxSizer(wx.HORIZONTAL)
self.twoBoxes.Add(self.leftBox)
self.twoBoxes.Add(self.rightBox)
self.vertical.Add(self.twoBoxes)
finishedCalibrationBtn = wx.Button(self.panel, label="Finish Calibration")
finishedCalibrationBtn.Bind(wx.EVT_BUTTON, self.OnClose)
self.vertical.Add(finishedCalibrationBtn, border=10, flag=wx.ALL|wx.CENTER)
self.panel.SetSizerAndFit(self.vertical)
self.Fit()
self.Show()
def OnEraseBackground(self, evt):
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self.drawPanel)
rect = self.drawPanel.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.SetBackground(wx.Brush('WHITE'))
bmp = wx.Bitmap('Images//robot_300.jpg')
dc.DrawBitmap(bmp, 0, 0)
def OnPaint(self, evt):
dc = wx.PaintDC(self.drawPanel)
bmp = wx.Bitmap('Images//robot_300.jpg')
dc.DrawBitmap(bmp, 0, 0)
#draw the servos activated
for servo in self.servoOrder:
self.IndicateServo(dc, servo, 'Red')
for servo in self.offsetChoices:
self.IndicateServo(dc, servo, 'Green')
if self.selectBlinkOn:
self.IndicateServo(dc, self.activeServo, 'Yellow')
else:
self.IndicateServo(dc, self.activeServo, 'Red')
def IndicateServo(self, dc, servo, color):
dc.SetPen(wx.Pen('White', 6, wx.SOLID))
dc.SetBrush(wx.Brush('WHITE', wx.TRANSPARENT))
dc.DrawCircle(self.servoMapLocations[servo][0], self.servoMapLocations[servo][1], 8) # body outline circle
dc.SetPen(wx.Pen(color, 4, wx.SOLID))
dc.DrawCircle(self.servoMapLocations[servo][0], self.servoMapLocations[servo][1], 8) # body outline circle
def flashCurrentServo(self, evt):
if self.selectBlinkOn:
self.selectBlinkOn = False
else:
self.selectBlinkOn = True
x = self.servoMapLocations[self.activeServo][0]
y = self.servoMapLocations[self.activeServo][1]
self.drawPanel.RefreshRect(wx.Rect(x-10, y-10, 20, 20))
def startCalibratingServo(self):
#set current servo inactive
if self.activeServo:
writeAndSendNote("SetServoActive", "%d,%s"%(self.activeServo, "inactive"), "robot")
#save the current servo state
offset = self.offsetSlider.GetValue()
self.offsetChoices[self.activeServo] = offset
#change servo diagram picture accordingly
if self.servoType[self.jointCounter] == "Foot":
self.jointGuideImage.SetBitmap(wx.BitmapFromImage(wx.Image('Images//Foot_Guide_300.jpg', wx.BITMAP_TYPE_ANY)))
if self.servoType[self.jointCounter] == "Thigh":
self.jointGuideImage.SetBitmap(wx.BitmapFromImage(wx.Image('Images//Thigh_Guide_300.jpg', wx.BITMAP_TYPE_ANY)))
if self.servoType[self.jointCounter] == "Hip":
self.jointGuideImage.SetBitmap(wx.BitmapFromImage(wx.Image('Images//Hip_Guide_300.jpg', wx.BITMAP_TYPE_ANY)))
if self.servoType[self.jointCounter] == "Head":
self.jointGuideImage.SetBitmap(wx.BitmapFromImage(wx.Image('Images//Head_Guide_300.jpg', wx.BITMAP_TYPE_ANY)))
#activate and center new servo
self.activeServo = self.servoOrder[self.jointCounter]
self.servoTitle.SetLabel("%.2d/%.2d - %s - Servo %.2d"%(self.jointCounter+1, len(self.servoOrder), self.servoPosition[self.jointCounter], self.activeServo))
self.panel.Layout() #re-centers the text
writeAndSendNote("SetServoActive", "%d,%s"%(self.activeServo, "active"), "robot")
writeAndSendNote("SetServoPos", "%d,%.1f"%(self.activeServo, 0), "robot")
self.Refresh()
#reload servo offset, if it existed before. If not, set slider to zero.
if self.activeServo in self.offsetChoices:
offset = self.offsetChoices[self.activeServo]
self.offsetSlider.SetValue(offset)
else:
self.offsetSlider.SetValue(0)
def changeOffset(self, evt):
#change offset output based on slider
offset = self.offsetSlider.GetValue()
self.offsetChoices[self.activeServo] = offset
writeAndSendNote("SetServoOffset", "%d,%.1f"%(self.activeServo, offset), "robot")
def nextServo(self, evt):
#find out which is next servo, set it active
self.jointCounter += 1
if self.jointCounter > len(self.servoOrder)-1:
self.jointCounter = len(self.servoOrder)-1
else:
self.startCalibratingServo()
def prevServo(self, evt):
#find out which is previous servo, set it active
self.jointCounter -= 1
if self.jointCounter < 0:
self.jointCounter = 0
else:
self.startCalibratingServo()
def OnClose(self, evt):
self.timer.Stop()
self.Destroy()
class RobotSelect():
def __init__(self, panel):
self.panel = panel
self.robots = None
#stuff the list with all the directories in ROBOTS_FOLDER_PATH
for folder in os.listdir('Robots'):
if os.path.isdir(folder):
self.robots.append(str(folder))
self.robots = ["Hexy V1"]
cb = wx.ComboBox(self.panel, pos=(5, 5), choices=self.robots, style=wx.CB_READONLY)
if len(self.robots) >= 1:
cb.SetValue(self.robots[0])
ROBOT_FOLDER_PATH = ROBOTS_FOLDER_PATH + self.robots[0] + "\\"
def OnComboSelect(self):
pass
class ArduinoRecordWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self, parent, id, 'Record Arduino Moves', size=(400,300))
wx.Frame.CenterOnScreen(self)
self.panel = wx.Panel(self)
icon = wx.Bitmap('Images//RecBtn.png')
self.recordBtn = wx.BitmapButton(self.panel, bitmap=icon, size=(30, 30))
self.recordBtn.Bind(wx.EVT_BUTTON, self.recordMoves)
icon = wx.Bitmap('Images//StopBtn.png')
self.stopBtn = wx.BitmapButton(self.panel, bitmap=icon, size=(30, 30))
self.stopBtn.Bind(wx.EVT_BUTTON, self.stopRecordMoves)
self.moveNameLabel = wx.StaticText(self.panel, label="Move Name:")
self.moveName = wx.TextCtrl(self.panel, size=(300, 20))
self.moveName.SetValue("hexy")
self.arduinoCode = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE|wx.TE_READONLY)
text = "How to record a move for Arduino:\n" \
"0.) (Optional) Choose a move name in the box above\n" \
"1.) Press the red record above button above\n" \
"2.) Run a move or multiple moves in PoMoCo\n" \
"3.) Press the black stop button above\n" \
"4.) Copy the generated move code to the Arduino IDE"
self.arduinoCode.ChangeValue(text)
#GUI Layout
self.horizontal = wx.BoxSizer()
self.horizontal.Add(self.recordBtn, flag=wx.CENTER)
self.horizontal.Add(self.stopBtn, flag=wx.CENTER)
self.horizontal.Add(self.moveNameLabel, flag=wx.CENTER)
self.horizontal.Add(self.moveName, flag=wx.CENTER)
self.vertical = wx.BoxSizer(wx.VERTICAL)
self.vertical.Add(self.horizontal, flag=wx.EXPAND)
self.vertical.Add(self.arduinoCode, proportion=1, flag=wx.EXPAND)
self.panel.SetSizerAndFit(self.vertical)
self.Show()
def recordMoves(self, evt):
moveNameStr = self.moveName.GetValue()
self.arduinoCode.ChangeValue("Recording PoMoCo Moves...\nStop when finished for Arduino Code")
writeAndSendNote("StartRecording", moveNameStr, "controller")
def stopRecordMoves(self, evt):
writeAndSendNote("StopRecording", "", "controller")
def updateCodeBox(self, code):
self.arduinoCode.ChangeValue(code)
class MoveControls():
def __init__(self, panel):
self.panel = panel
self.moveFolderPath = None
self.moves = []
self.moveBtns = []
#self.firmwareLabel = wx.StaticText(self.panel, label="Moves", pos=(30,7))
icon = wx.Bitmap('Images//Refresh.png')
refreshBtn = wx.BitmapButton(self.panel, bitmap=icon, pos=(5,5), size=(30, 22))
refreshBtn.Bind(wx.EVT_BUTTON, self.loadButtons)
icon = wx.Bitmap('Images//Arduino.png')
refreshBtn = wx.BitmapButton(self.panel, bitmap=icon, pos=(35,5), size=(30, 22))
refreshBtn.Bind(wx.EVT_BUTTON, self.ArduinoRecord)
def updateCodeBox(self, code):
if self.arduinoCodeWindow:
self.arduinoCodeWindow.updateCodeBox(code)
def ArduinoRecord(self, evt):
self.arduinoCodeWindow = ArduinoRecordWindow(self.panel,1)
def SetMovesFolder(self, folderPath):
self.moveFolderPath = folderPath
self.loadButtons()
def loadButtons(self, evt=None):
offsetY=30
if len(self.moveBtns) > 0:
for button in self.moveBtns:
button.Destroy()
self.moves = []
self.moveBtns = []
if self.moveFolderPath:
for fileName in os.listdir(self.moveFolderPath):
if os.path.splitext(fileName)[1] == '.py':
fileName = os.path.splitext(fileName)[0]
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', fileName)
self.moves.append(s1)
self.moves.sort()
for move in self.moves:
cbtn = wx.Button(self.panel, style=wx.BU_LEFT, label=str(move), pos=(5,offsetY), size=(85, 20))
cbtn.moveName = move
cbtn.Bind(wx.EVT_BUTTON, self.OnMoveButton)
self.moveBtns.append(cbtn)
offsetY += 22
def OnMoveButton(self, evt):
moveName = evt.GetEventObject().moveName
writeAndSendNote("RunMove", "%s"%(moveName), "robot")
class ServoWidget(wx.Panel):
def __init__(self, parent, width , height):
self.parent = parent
self.servos = []
self.dragImage = None
self.dragShape = None
self.dragPos = None
self.hiliteShape = None
self.parent.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
self.bg_bmp = wx.EmptyBitmap(width, height)
self.parent.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.parent.Bind(wx.EVT_PAINT, self.OnPaint)
self.parent.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.parent.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.parent.Bind(wx.EVT_MOTION, self.OnMotion)
self.parent.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
self.parent.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
self.LastDrivenTimer = wx.Timer(self.parent)
self.parent.Bind(wx.EVT_TIMER, self.LastDrivenCheck, self.LastDrivenTimer)
self.LastDrivenTimer.Start(50)
def LastDrivenCheck(self, evt):
for servo in self.servos:
servo.CheckDriven()
def SetBackgroundImage(self, bmp):
self.bg_bmp = bmp
def AddServo(self, num, pos, deg=float(0.0), offset=float(0.0), visible=True, active=False, joint=""):
servo = ServoControl(self, num, pos, deg, offset, visible, active, joint)
self.servos.append(servo)
def OnToggleServo(self, evt):
obj = evt.GetEventObject()
isPressed = obj.GetValue()
servo = self.getServo(int(obj.label))
servo.SetActive(isPressed)
self.parent.Update()
def getServo(self, servoNum):
for servo in self.servos:
if servo.num == int(servoNum):
return servo
return None
def OnLeaveWindow(self, evt):
pass
# tile the background bitmap
def TileBackground(self, dc):
dc.SetBackground(wx.Brush('WHITE'))
dc.DrawBitmap(self.bg_bmp, 0, 0)
# Go through our list of shapes and draw them in whatever place they are.
def DrawShapes(self, dc):
for shape in self.servos:
if shape.visible:
shape.Draw(dc)
# This is actually a sophisticated 'hit test', but in this
# case we're also determining which shape, if any, was 'hit'.
def FindShape(self, pt):
for shape in self.servos:
if shape.HitTest(pt):
return shape
return None
# Clears the background, then redraws it. If the DC is passed, then
# we only do so in the area so designated. Otherwise, it's the whole thing.
def OnEraseBackground(self, evt):
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.parent.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
self.TileBackground(dc)
# Fired whenever a paint event occurs
def OnPaint(self, evt):
dc = wx.PaintDC(self.parent)
#self.PrepareDC(dc)
self.DrawShapes(dc)
def OnLeftDClick(self, evt):
pt = evt.GetPosition()
shape = self.FindShape(pt)
if shape:
if shape.ActiveOnButtonTest(pt):
#print shape.num,"turned active"
shape.SendActive(True)
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.ActiveOffButtonTest(pt):
#print shape.num,"turned inactive"
shape.SendActive(False)
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.OffsetPlusTest(pt):
shape.SendOffset(shape.offset + 1)
shape.Render()
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.OffsetMinusTest(pt):
shape.SendOffset(shape.offset - 1)
shape.Render()
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.ServoControlTest(pt):
shape.SendDeg(0)
shape.Refresh()
if shape.offsetsShown:
rect = wx.Rect(shape.pos[0]+12, shape.pos[1]+40, 24, 10)
if rect.InsideXY(pt.x, pt.y):
shape.offset = 0
shape.Render()
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
# Left mouse button is down.
def OnLeftDown(self, evt):
pt = evt.GetPosition()
# Did the mouse go down on one of our shapes?
shape = self.FindShape(pt)
# If a shape was 'hit', then set that as the shape we're going to
# drag around. Get our start position. Dragging has not yet started.
# That will happen once the mouse moves, OR the mouse is released.
if shape:
if(shape.ControlTest(pt)):
if shape.ServoControlTest(pt):
self.dragPos = True
self.dragPosServo = shape
if shape.ActiveOnButtonTest(pt):
#print shape.num,"turned active"
shape.SendActive(True)
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.ActiveOffButtonTest(pt):
#print shape.num,"turned inactive"
shape.SendActive(False)
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.OffsetPlusTest(pt):
shape.SendOffset(shape.offset + 1)
shape.Render()
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
if shape.OffsetMinusTest(pt):
shape.SendOffset(shape.offset - 1)
shape.Render()
self.parent.RefreshRect(shape.GetRect(), True)
self.parent.Update()
else:
self.dragShape = shape
self.dragStartPos = pt
# Left mouse button up.
def OnLeftUp(self, evt):
self.dragPos = None
self.dragPosServo = None
if not self.dragImage or not self.dragShape:
self.dragImage = None
self.dragShape = None
return
# Hide the image, end dragging, and nuke out the drag image.
self.dragImage.Hide()
self.dragImage.EndDrag()
self.dragImage = None
if self.hiliteShape:
self.parent.RefreshRect(self.hiliteShape.GetRect())
self.hiliteShape = None
# reposition and draw the shape
# Note by jmg 11/28/03
# Here's the original:
#
# self.dragShape.pos = self.dragShape.pos + evt.GetPosition() - self.dragStartPos
#
# So if there are any problems associated with this, use that as
# a starting place in your investigation. I've tried to simulate the
# wx.Point __add__ method here -- it won't work for tuples as we
# have now from the various methods
#
# There must be a better way to do this :-)
#
self.dragShape.pos = (
self.dragShape.pos[0] + evt.GetPosition()[0] - self.dragStartPos[0],
self.dragShape.pos[1] + evt.GetPosition()[1] - self.dragStartPos[1]
)
self.dragShape.visible = True
self.parent.RefreshRect(self.dragShape.GetRect())
self.dragShape = None
# The mouse is moving
def OnMotion(self, evt):
#servo control dragging trumps dragging shape dragging
if self.dragPos:
self.dragPosServo.SetServoControl(evt.GetPosition())
#get position relative to "center" of servo
else:
# Ignore mouse movement if we're not dragging.
if not self.dragShape or not evt.Dragging() or not evt.LeftIsDown():
return
# if we have a shape, but haven't started dragging yet
if self.dragShape and not self.dragImage:
# only start the drag after having moved a couple pixels
tolerance = 2
pt = evt.GetPosition()
dx = abs(pt.x - self.dragStartPos.x)
dy = abs(pt.y - self.dragStartPos.y)
if dx <= tolerance and dy <= tolerance:
return
# refresh the area of the window where the shape was so it
# will get erased.
self.dragShape.visible = False
self.parent.RefreshRect(self.dragShape.GetRect(), True)
self.parent.Update()
self.dragImage = wx.DragImage(self.dragShape.bmp,
wx.StockCursor(wx.CURSOR_HAND))
hotspot = self.dragStartPos - self.dragShape.pos
self.dragImage.BeginDrag(hotspot, self.parent, self.dragShape.fullscreen)
self.dragImage.Move(pt)
self.dragImage.Show()
# if we have shape and image then move it, posibly highlighting another shape.
elif self.dragShape and self.dragImage:
onShape = self.FindShape(evt.GetPosition())
unhiliteOld = False
hiliteNew = False
# figure out what to hilite and what to unhilite
if self.hiliteShape:
if onShape is None or self.hiliteShape is not onShape:
unhiliteOld = True
if onShape and onShape is not self.hiliteShape and onShape.visible:
hiliteNew = True
# if needed, hide the drag image so we can update the window
if unhiliteOld or hiliteNew:
self.dragImage.Hide()
if unhiliteOld:
dc = wx.ClientDC(self.parent)
self.hiliteShape.Draw(dc)
self.hiliteShape = None
if hiliteNew:
dc = wx.ClientDC(self.parent)
self.hiliteShape = onShape
self.hiliteShape.Draw(dc, wx.INVERT)
# now move it and show it again if needed
self.dragImage.Move(evt.GetPosition())
if unhiliteOld or hiliteNew:
self.dragImage.Show()
if os.name == 'posix':
self.parent.Refresh()
self.parent.Update()
self.parent.RefreshRect(self.dragShape.GetRect(), True)