/
JaguarCtrl.cs
1404 lines (1179 loc) · 52.2 KB
/
JaguarCtrl.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using EARTHLib;
using System.Drawing.Drawing2D;
using System.IO;
using Microsoft.DirectX.DirectInput;
using System.Threading;
namespace DrRobot.JaguarControl
{
public partial class JaguarCtrl : Form
{
# region Form Variables
DrRobotRobotConnection drRobotConnect = null;
public RobotConfig robotCfg = null;
public Navigation navigation = null;
public RobotConfig.RobotConfigTableRow jaguarSetting = null;
private const string configFile = "c:\\DrRobotAppFile\\OutDoorRobotConfig.xml";
private const double TEMPERATURE_TH = 60.0;
public Image testImage;
double[] robotCornerAngles = { Math.PI / 6, -Math.PI / 6, Math.PI + Math.PI / 6, Math.PI - Math.PI / 6 };
double[] robotTrackAngles = { Math.PI / 4, Math.PI - Math.PI / 4, Math.PI + Math.PI / 4, -Math.PI / 4 };
Point[] robotCorners = new Point[4];
Point[] trackCorners = new Point[4];
public int KNOWN = 0;
public int UNKNOWN = 1;
public int startMode = 0;
# endregion
#region Graphics Variables
GoogleEarth gEarth = new GoogleEarth();
public double mapResolution;
public float metersToPixels = 10;
private double zoomConstant = 2.0;
private static int paneWidth = 484;
private static int paneHeight = 415;
private static int xMin = 11;
private static int yMin = 41;
private static int xMax = paneWidth + xMin;
private static int yMax = paneHeight + yMin;
private static int xCenter = xMin + paneWidth / 2;
private static int yCenter = yMin + paneHeight / 2;
private static int constxCenter = xCenter;
private static int constyCenter = yCenter;
private static Point oPoint = new Point(xMin, yMin);
private static Pen blackPen = new Pen(Color.Black, 1);
private static Pen whitePen = new Pen(Color.White, 10);
private static Pen thinWhitePen = new Pen(Color.White, 1);
private static Pen goldPen = new Pen(Color.Gold, 1);
private static Pen milestonePen = new Pen(Color.White, 2);
private static Pen trajPen = new Pen(Color.Cyan, 2);
private static Pen trackPen = new Pen(Brushes.LightGray);
private static Pen wallPen = new Pen(Brushes.LightGray, 4);
private static Pen particlePen = new Pen(Brushes.Red, 1);
private static Pen estimatePen = new Pen(Brushes.Blue, 2);
private static Pen medBluePen = new Pen(Color.LightBlue, 3);
private static Pen medGreenPen = new Pen(Color.FromArgb(0, 255, 0), 3);
public enum AUTOMODE { TRACKTRAJ, TRACKSETPOINT, ROTONSPOT, FOLLOW_WALL, APPROACH_WALL, FIND_WALL, ALIGN_WALL };
public int AUTO_TRACKTRAJ = 0;
public int AUTO_TRACKSETPOINT = 1;
public int AUTO_ROTONSPOT = 2;
public int AUTO_FOLLOW_WALL = 3;
public int AUTO_APPROACH_WALL = 4;
public int AUTO_FIND_WALL = 5;
public int AUTO_ALIGN_WALL = 6;
public int autoMode = 0;
private static double cellWidth = 1.0; // in meters, mapResolution is in metersToPixels
#endregion
#region Motor Variables
public class MotorData
{
public int pwmOutput = 0;
public int encodeSpeed = 0;
public int encoderPos = 0;
public int encoderDir = 0;
}
//private Robot RobotVars = new Robot();
//here is arm motor array, 0 for front arm, 1 for rear arm
private MotorData[] armMotor = new MotorData[2];
private int[] armEncoder = new int[2]{0,0};
private int[] preArmEncoder = new int[2]{0,0};
private bool firstEncoderData = true;
private const int ARM_CIRCLE_CNT = 1140; // 5*4*285 /5 = 1140
private double[] armPosAngle = new double[2]{0,0};
private double[] preArmPos = new double[2]{0,0};
private int[] armResetPos = new int[2] { 0, 0 };
private double[] armPosStart = new double[2] { 0, 0 };
public MotorData leftFrontWheelMotor = new MotorData();
public MotorData rightFrontWheelMotor = new MotorData();
public MotorData leftRearWheelMotor = new MotorData();
public MotorData rightRearWheelMotor = new MotorData();
private short zeroOutput = 16383;
private short maxPosOutput = 32767;
private int forwardPower = 0;
private int turnPower = 0;
private double[] resTable = new double[25]{114660,84510,62927,47077,35563,27119,20860,16204,12683,10000,
7942,6327,5074,4103,3336,2724,2237,1846,1530,1275,1068,899.3,760.7,645.2,549.4};
private double[] tempTable = new double[25] { -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 };
private const double FULLAD = 4095;
private double stuckVelTH = 50;
private double stuckAcc = 0;
private double stuckPWMTH = 12000;
private double stuckAccTH = 50;
#endregion
#region Joystick Control Variables
private bool forceStop = false;
private bool protectMotorTemp = false;
private bool protectMotorStuck = false;
private const int NOCONTROL = -32768;
int armCmd1 = 0;
int armCmd2 = 0;
int exeTime = 1000;
private bool lightOn = false;
private int expandIO = 0xff;
private const short LEFTARMCHANNEL = 0;
private const short RIGHTARMCHANNEL = 1;
public int forwardVel, turnVel;
private const short LEFTWHEELCHANNEL = 3; //3
private const short RIGHTWHEELCHANNEL = 4; //4
public static JoystickState[] joyState = new JoystickState[2]; //maybe we need second Joystick in future
private static int[] preSetButton = new int[2]{-1,-1}; //no any button pressed
private static int[] joyButtonCnt = new int[2]{0,0};
private const int JOYDELAY = 10;
private Device[] applicationDevice = new Device[2];
private bool blnJoyStick = true;
private const int MAXPWM = 16384;
private const int MINPWM = 4000;
private const int INIPWM = 16384;
private int MOTDIR = 1;
private const int CMD_INT_TIME = 10;
private bool armJoy2 = false;
private bool armJoy1 = false;
private const short armChannel1 = 0;
private const short armChannel2 = 1;
private bool lightCtrl = true;
private const int ARM_DELAY_CNT = 40;
private const int ARM_VEL1 = 200;
private const int ARM_VEL2 = 1000;
public const int SIMULATOR = 0;
public const int HARDWARE = 1;
public int experimentMode = SIMULATOR;
public int MANUAL = 0;
public int AUTONOMOUS = 1;
public int controlMode = 0;
private Thread sensorThread;
public bool runSensorThread;
#endregion
/////////////////////////////////////////////////////////////////
#region Form functions
public JaguarCtrl()
{
simulatedJaguar = new AxDDrRobotSentinel_Simulator();
navigation = new Navigation(this);
drRobotConnect = new DrRobotRobotConnection(this);
drRobotConnect.connectRobot();
robotCfg = drRobotConnect.robotConfig;
jaguarSetting = (RobotConfig.RobotConfigTableRow)robotCfg.RobotConfigTable.Rows[0];
InitializeComponent();
// Setup graphics for simulation
SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.JaguarCtrl_Paint);
panelGE.Visible = false;
mapResolution = trackBarZoom.Value * zoomConstant;
// Start Simulated Sensor Update Thread
runSensorThread = true;
sensorThread = new Thread(runSensorLoop);
sensorThread.Start();
}
public bool Simulating()
{
if (experimentMode == SIMULATOR)
return true;
else
return false;
}
public void runSensorLoop()
{
// Wait
Thread.Sleep(300);
while (runSensorThread)
{
if (Simulating())
{
//Update Real Encoder Measurements
leftFrontWheelMotor.encoderPos = simulatedJaguar.GetEncoderPulse4();
leftFrontWheelMotor.encodeSpeed = simulatedJaguar.GetEncoderSpeed4();
leftFrontWheelMotor.encoderDir = simulatedJaguar.GetEncoderDir4();
rightFrontWheelMotor.encoderPos = simulatedJaguar.GetEncoderPulse5();
rightFrontWheelMotor.encodeSpeed = simulatedJaguar.GetEncoderSpeed5();
rightFrontWheelMotor.encoderDir = simulatedJaguar.GetEncoderDir5();
UpdateFormEncoderData();
}
Animate();
Thread.Sleep(100);
}
}
private void JaguarCtrl_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
}
private void Animate()
{
// Create bitmap to write to
Bitmap gBuffer= new Bitmap(paneWidth, paneHeight);
using (Graphics g = Graphics.FromImage(gBuffer))
{
int xCenter = (int)(constxCenter - navigation.x * mapResolution);
int yCenter = (int)(constyCenter + navigation.y * mapResolution);
// Smooth?
g.SmoothingMode = SmoothingMode.AntiAlias;
g.SmoothingMode = SmoothingMode.HighQuality;
// Paint background of bitmap
g.FillRectangle(Brushes.Black, new Rectangle(xMin, yMin, paneWidth, paneHeight));
// Add Grid
int numXLines = (int)(0.5 * paneWidth / (mapResolution * cellWidth)) + 1;
int numYLines = (int)(0.5 * paneHeight / (mapResolution * cellWidth)) + 1;
for (int i = 0; i < numXLines; i++)
{
float Xp = (float)(xCenter + i * mapResolution * cellWidth);
float Xm = (float)(xCenter - i * mapResolution * cellWidth);
g.DrawLine(goldPen, Xp, yMin, Xp, yMax);
g.DrawLine(goldPen, Xm, yMin, Xm, yMax);
}
for (int i = 0; i < numYLines; i++)
{
float Yp = (float)(yCenter + i * mapResolution * cellWidth);
float Ym = (float)(yCenter - i * mapResolution * cellWidth);
g.DrawLine(goldPen, xMin, Yp, xMax, Yp);
g.DrawLine(goldPen, xMin, Ym, xMax, Ym);
}
// Draw Axis
g.DrawLine(thinWhitePen, xCenter, yCenter, (float)(xCenter + 1.5 * mapResolution), yCenter);
g.DrawLine(thinWhitePen, (float)(xCenter + 1.4 * mapResolution), (float)(yCenter + 0.1 * mapResolution),
(float)(xCenter + 1.5 * mapResolution), (float)(yCenter + 0.0 * mapResolution));
g.DrawLine(thinWhitePen, (float)(xCenter + 1.4 * mapResolution), (float)(yCenter - 0.1 * mapResolution),
(float)(xCenter + 1.5 * mapResolution), (float)(yCenter + 0.0 * mapResolution));
g.DrawLine(thinWhitePen, xCenter, yCenter, xCenter, (float)(yCenter - 1.5 * mapResolution));
g.DrawLine(thinWhitePen, (float)(xCenter - 0.1 * mapResolution), (float)(yCenter - 1.4 * mapResolution),
(float)(xCenter + 0.0 * mapResolution), (float)(yCenter - 1.5 * mapResolution));
g.DrawLine(thinWhitePen, (float)(xCenter + 0.1 * mapResolution), (float)(yCenter - 1.4 * mapResolution),
(float)(xCenter + 0.0 * mapResolution), (float)(yCenter - 1.5 * mapResolution));
// Draw PRM milestones
for (int i = 0; i < navigation.numNodes; i++)
{
g.DrawEllipse(milestonePen, xCenter + (float)navigation.nodeList[i].x * (float)mapResolution, yCenter - (float)navigation.nodeList[i].y * (float)mapResolution, 2, 2);
g.DrawLine(milestonePen, xCenter + (float)navigation.nodeList[i].x * (float)mapResolution, yCenter - (float)navigation.nodeList[i].y * (float)mapResolution, xCenter + (float)navigation.nodeList[navigation.nodeList[i].lastNode].x * (float)mapResolution, yCenter - (float)navigation.nodeList[navigation.nodeList[i].lastNode].y * (float)mapResolution);
}
// Draw Trajectory
for (int i = 0; i < navigation.trajSize - 1; i++)
g.DrawLine(trajPen, xCenter + (float)navigation.trajList[i].x * (float)mapResolution, yCenter - (float)navigation.trajList[i].y * (float)mapResolution,
xCenter + (float)navigation.trajList[i + 1].x * (float)mapResolution, yCenter - (float)navigation.trajList[i + 1].y * (float)mapResolution);
// Draw Robot
int xShift = (int)(mapResolution * navigation.x);
int yShift = (int)(mapResolution * navigation.y);
double robotDiagnol = 0.25 * mapResolution;
for (int i = 0; i < 4; i++)
{
robotCorners[i].X = (int)(xCenter + xShift + robotDiagnol * Math.Cos(navigation.t + robotCornerAngles[i]));
robotCorners[i].Y = (int)(yCenter - yShift - robotDiagnol * Math.Sin(navigation.t + robotCornerAngles[i]));
}
g.FillPolygon(Brushes.DarkSlateGray, robotCorners);
// Draw Tracks
double trackDiagnol = 0.35 * mapResolution;
trackPen.Width = (int)(8 * mapResolution / 100);
for (int i = 0; i < 2; i++)
{
trackCorners[2 * i].X = (int)(xCenter + xShift + robotDiagnol * Math.Cos(navigation.t + robotTrackAngles[2 * i]));
trackCorners[2 * i].Y = (int)(yCenter - yShift - robotDiagnol * Math.Sin(navigation.t + robotTrackAngles[2 * i]));
trackCorners[2 * i+1].X = (int)(xCenter + xShift + robotDiagnol * Math.Cos(navigation.t + robotTrackAngles[2 * i+1]));
trackCorners[2 * i+1].Y = (int)(yCenter - yShift - robotDiagnol * Math.Sin(navigation.t + robotTrackAngles[2 * i+1]));
g.DrawLine(trackPen, trackCorners[2 * i], trackCorners[2 * i + 1]);
}
// Draw Laser on top
double laserDiagonal = 0.15*mapResolution;
int laserDiameter = (int)(0.08*mapResolution);
int X_laser = (int)(xCenter + xShift + laserDiagonal * Math.Cos(navigation.t) - laserDiameter / 2);
int Y_laser = (int)(yCenter - yShift - laserDiagonal * Math.Sin(navigation.t) - laserDiameter / 2);
g.FillEllipse(Brushes.LightGray, X_laser, Y_laser, laserDiameter, laserDiameter);
// Draw Walls
for (int w = 0; w < navigation.map.numMapSegments; w++)
{
g.DrawLine(wallPen, (float)(xCenter + mapResolution * navigation.map.mapSegmentCorners[w, 0, 0]),
(float)(yCenter - mapResolution * navigation.map.mapSegmentCorners[w, 0, 1]),
(float)(xCenter + mapResolution * navigation.map.mapSegmentCorners[w, 1, 0]),
(float)(yCenter - mapResolution * navigation.map.mapSegmentCorners[w, 1, 1]));
}
// Draw myTrajecoty
for (int i = 0; i < navigation.map.trajectory.points.Count; i++)
{
//Draw x,y
drawPoint(g, medBluePen, xCenter, yCenter, navigation.map.trajectory.points[i]);
}
drawPoint(g, medGreenPen, xCenter, yCenter, new JagPoint(navigation.x_des, navigation.y_des, navigation.t_des));
// Draw GPS
drawPoint(g, new Pen(Color.Red,4), xCenter, yCenter, new JagPoint(navigation.x_gps, navigation.y_gps));
// Draw Particles
int partSize = Math.Max((int)(0.16*mapResolution),2);
int partHalfSize = Math.Max((int)(0.08 * mapResolution),1);
for (int p = 0; p < navigation.numParticles; p++)
{
g.DrawPie(particlePen, (int)(xCenter -partHalfSize + mapResolution * navigation.particles[p].x), (int)(yCenter - partHalfSize - mapResolution * navigation.particles[p].y), partSize, partSize, (int)(-navigation.particles[p].t * 180 / 3.14 - 180 - 25), 50);
}
// Draw State Estimate
g.DrawPie(estimatePen, (int)(xCenter - partHalfSize + mapResolution * navigation.x_est), (int)(yCenter - partHalfSize - mapResolution * navigation.y_est), partSize, partSize, (int)(-navigation.t_est * 180 / 3.14 - 180 - 25), 50);
// Paint background of bitmap
g.FillRectangle(Brushes.LightGray, new Rectangle(xMin - 40, yMin, 40, paneHeight));
// Draw the bitmap to the form
this.CreateGraphics().DrawImageUnscaled(gBuffer, 0, 0);
}
}
private void drawPoint(Graphics g, Pen pen, int xCenter, int yCenter, JagPoint p)
{
//Draw x,y
int radius = 5;
int xPoint = (int)(p.x * mapResolution);
int yPoint = (int)(p.y * mapResolution);
g.DrawEllipse(pen, new Rectangle(xCenter + xPoint - radius, yCenter - yPoint - radius, 2 * radius, 2 * radius));
//Draw theta
if (p.hasTheta())
{
int dy = (int)(3 * radius * Math.Sin(p.theta));
int dx = (int)(3 * radius * Math.Cos(p.theta));
g.DrawLine(pen, xCenter + xPoint, yCenter - yPoint, xCenter + xPoint + dx, yCenter - yPoint - dy);
}
}
private void JaguarCtrl_Shown(object sender, EventArgs e)
{
drRobotConnect.Hide ();
this.Focus();
}
private void JaguarCtrl_FormClosed(object sender, FormClosedEventArgs e)
{
myAMC.Stop();
try
{
if (drRobotConnect != null)
drRobotConnect.Close();
}
catch{}
}
private void JaguarCtrl_Load(object sender, EventArgs e)
{
for (int i = 0; i < 2; i++)
{
armMotor[i] = new MotorData();
}
realJaguar.connectRobot (jaguarSetting.RobotID);
//Initialize Robot Variables and Google Earth
//gEarth.Initialize(this);
if (Simulating())
checkBoxHardware.Checked = false;
else
checkBoxHardware.Checked = true;
//for Axis camera
try
{
// Set properties, deciding what url completion to use by MediaType.
myAMC.MediaUsername = jaguarSetting.CameraUser;
myAMC.MediaPassword = jaguarSetting.CameraPWD;
myAMC.MediaType = "mjpeg";
myAMC.MediaURL = CompleteURL(jaguarSetting.CameraIP + ":" + jaguarSetting .CameraPort , "mjpeg");
myAMC.AudioConfigURL = "http://" + jaguarSetting.CameraIP + ":" + jaguarSetting .CameraPort + "/axis-cgi/view/param.cgi?camera=1&action=list&group=Audio,AudioSource.A0";
myAMC.ToolbarConfiguration = "default, + audiocontrol,+ rec";
myAMC.AudioReceiveStop();
// Start the streaming
myAMC.Play();
myAMC.AudioReceiveURL = "http://" + jaguarSetting.CameraIP + ":" + jaguarSetting .CameraPort + "/axis-cgi/audio/receive.cgi";
myAMC.Volume = 0;
//myAMC.AudioReceiveStart();
myAMC.AudioTransmitURL = "http://" + jaguarSetting.CameraIP + ":" + jaguarSetting.CameraPort + "/axis-cgi/audio/transmit.cgi";
}
catch (Exception ex)
{
MessageBox.Show(this, "Unable to play stream: " + ex.Message);
}
//for joystick control
if (InitDirectInput())
tmrJoyStickPoll.Enabled = true;
//for GPS/IMU communication
if ((jaguarSetting.IMUIP !="0.0.0.0") && (jaguarSetting .GPSIP != "0.0.0.0"))
startComm ();
// for laser scan
if ((jaguarSetting.LaserRangeIP != "0.0.0.0") && (jaguarSetting.LaserRangePort != 0))
{
startCommLaser();
btnLaserScan.Enabled = true;
}
else
btnLaserScan.Enabled = false;
drawLaserBackground();
MOTDIR = jaguarSetting .MotorDir;
btnDisArm.Visible = false;
pictureBoxStuckDetect.BackColor = Color.Green;
btnScan.Enabled = false;
}
private void JaguarCtrl_FormClosing(object sender, FormClosingEventArgs e)
{
//kill the navigation thread
runSensorThread = false;
sensorThread.Abort();
//kill the connection form
drRobotConnect.DrRobotRobotConnection_Kill();
drRobotConnect.Close();
//kill the navigation thread
navigation.runThread = false;
tmrDisplay.Enabled = false;
tmrDrawing.Enabled = false;
tmrJoyStickPoll.Enabled = false;
stopCommunication();
stopCommunicationLaser();
if ((startRecord) || (SW != null))
SW.Close();
//we save google earth start point here
//gEarth.Close(this, robotCfg, configFile);
//Thread.Sleep(1000);
}
#endregion
#region Axis Camera Control
string CompleteURL(string theMediaURL, string theMediaType)
{
string anURL = theMediaURL;
if (!anURL.EndsWith("/")) anURL += "/";
if (theMediaType == "mjpeg")
{
anURL += "axis-cgi/mjpg/video.cgi";
}
else if (theMediaType == "mpeg4")
{
anURL += "mpeg4/media.amp";
}
else if (theMediaType == "mpeg2-unicast")
{
anURL += "axis-cgi/mpeg2/video.cgi";
}
else if (theMediaType == "mpeg2-multicast")
{
anURL += "axis-cgi/mpeg2/video.cgi";
}
anURL = CompleteProtocol(anURL, theMediaType);
return anURL;
}
string CompleteProtocol(string theMediaURL, string theMediaType)
{
if (theMediaURL.IndexOf("://") >= 0) return theMediaURL;
string anURL = theMediaURL;
if (theMediaType == "mjpeg")
{
anURL = "http://" + anURL;
}
else if (theMediaType == "mpeg4")
{
anURL = "axrtsphttp://" + anURL;
}
else if (theMediaType == "mpeg2-unicast")
{
anURL = "http://" + anURL;
}
else if (theMediaType == "mpeg2-multicast")
{
anURL = "axsdp" + anURL;
}
return anURL;
}
#endregion
#region GoogleEarth function
//this is a "Look At" function
private void btnSetMapCenter_Click(object sender, EventArgs e) { }
private void trackBarZoom_Scroll(object sender, EventArgs e)
{
// TrackBarZoom ranges from 1 to 100
// MapResolution is in pixels / meters
// Lets limit between 5x5 meters to 500x500 meters
// so lets multiply by 5
mapResolution = Math.Max(1,Math.Min(90,trackBarZoom.Value))*zoomConstant;
this.Invalidate();
}
#endregion
#region Real Jaguar ActiveX event
private void realJaguar_StandardSensorEvent(object sender, EventArgs e)
{
double vol = (double)realJaguar.GetSensorBatteryAD2() / 4095 * 34.498;
//to protect Li-Po Battery, you'd better shut down when battery is lower than 22.2V (3.7V*6)
if (vol < 22.2)
lblBatVol.ForeColor = Color.Red;
else
lblBatVol.ForeColor = Color.Black;
lblBatVol.Text = vol.ToString("0.00");
//here is the board voltage 5V, not display on the UI
vol = (double)realJaguar.GetSensorBatteryAD1() / 4095 * 9;
}
private void realJaguar_MotorSensorEvent(object sender, EventArgs e)
{
forwardPower = realJaguar.GetMotorPWMValue4(); //actually is forward PWM power
turnPower = realJaguar.GetMotorPWMValue5(); //actually is tunning PWM power
}
delegate void SetTextDelegate(string encol, string encor, string vell, string velr);
private void UpdateFormEncoderData(string encol, string encor, string vell, string velr)
{
lblEncoderPos1.Text = leftFrontWheelMotor.encoderPos.ToString(); //
lblEncoderPos2.Text = rightFrontWheelMotor.encoderPos.ToString(); //
lblVel1.Text = (MOTDIR * leftFrontWheelMotor.encodeSpeed * leftFrontWheelMotor.encoderDir).ToString();
lblVel2.Text = (-MOTDIR * rightFrontWheelMotor.encodeSpeed * rightFrontWheelMotor.encoderDir).ToString();
lblEncoderPos4.Text = navigation.x.ToString();
lblVel4.Text = navigation.y.ToString();
lblTemp4.Text = navigation.t.ToString();
}
private void UpdateFormEncoderData()
{
string encl = leftFrontWheelMotor.encoderPos.ToString();
string encr = rightFrontWheelMotor.encoderPos.ToString();
string vell = (MOTDIR * leftFrontWheelMotor.encodeSpeed * leftFrontWheelMotor.encoderDir).ToString();
string velr = (-MOTDIR * rightFrontWheelMotor.encodeSpeed * rightFrontWheelMotor.encoderDir).ToString();
if (InvokeRequired)
{
Invoke(new SetTextDelegate(UpdateFormEncoderData), encl, encr, vell, velr);
}
else
{
lblEncoderPos1.Text = encl; //
lblEncoderPos2.Text = encr; //
lblVel1.Text = vell;
lblVel2.Text = velr;
lblEncoderPos4.Text = navigation.x.ToString();
lblVel4.Text = navigation.y.ToString();
lblTemp4.Text = navigation.t.ToString();
myUpdateGui();
}
}
private void realJaguar_CustomSensorEvent(object sender, EventArgs e)
{
//here is temperature detect
// For a motor, if output PWM is very big but encoder speed is very low or zero, it usually means the motor
// works in a stuck state, the current will be very big, the motor will be damaged in a moment, so please be
// very carefull at these information, especialy if temperature of a motor is getting much higher(above 60 degree),
// stop the motor for a while to protect the motor
// now the temperature is connect to Extended AD port
double tempM1 = Trans2Temperature((double)realJaguar.GetCustomAD5());
tempM1 = double.Parse(tempM1.ToString("0.00"));
double tempM2 = Trans2Temperature((double)realJaguar.GetCustomAD6());
tempM2 = double.Parse(tempM2.ToString("0.00"));
double tempM3 = Trans2Temperature((double)realJaguar.GetCustomAD7());
tempM3 = double.Parse(tempM3.ToString("0.00"));
double tempM4 = Trans2Temperature((double)realJaguar.GetCustomAD8());
tempM4 = double.Parse(tempM4.ToString("0.00"));
//Update Real Encoder Measurements
if (!Simulating())
{
leftFrontWheelMotor.encoderPos = realJaguar.GetEncoderPulse4();
leftFrontWheelMotor.encodeSpeed = realJaguar.GetEncoderSpeed4();
leftFrontWheelMotor.encoderDir = realJaguar.GetEncoderDir4();
rightFrontWheelMotor.encoderPos = realJaguar.GetEncoderPulse5();
rightFrontWheelMotor.encodeSpeed = realJaguar.GetEncoderSpeed5();
rightFrontWheelMotor.encoderDir = realJaguar.GetEncoderDir5();
UpdateFormEncoderData();
}
//here can read back left wheel motor and right wheel motor encoder information
if (checkBoxMotorProtect.Checked)
{
if ((tempM1 > TEMPERATURE_TH) || (tempM2 > TEMPERATURE_TH) )
protectMotorTemp = true;
else
protectMotorTemp = false;
}
else
protectMotorTemp = false;
if (tempM1 > TEMPERATURE_TH)
lblTemp1.ForeColor = Color.Red;
else
lblTemp1.ForeColor = Color.Black;
if (tempM2 > TEMPERATURE_TH)
lblTemp2.ForeColor = Color.Red;
else
lblTemp2.ForeColor = Color.Black;
// Update form with encoder data
lblTemp1.Text = tempM1.ToString("0.00");
lblTemp2.Text = tempM2.ToString("0.00");
//stuck detect here
if ((Math.Abs(forwardPower - 16384) > stuckPWMTH) || (Math.Abs(turnPower - 16384) > stuckPWMTH))
{
if (((Math.Abs(leftFrontWheelMotor.encodeSpeed) < stuckVelTH))
|| ((Math.Abs(rightFrontWheelMotor.encodeSpeed) < stuckVelTH)))
stuckAcc++;
else
{
stuckAcc--;
if (stuckAcc < 0) stuckAcc = 0;
}
}
else
{
stuckAcc--;
if (stuckAcc < 0) stuckAcc = 0;
}
if (stuckAcc >= stuckAccTH)
{
stuckAcc = stuckAccTH;
pictureBoxStuckDetect.BackColor = Color.Red;
if (checkBoxMotorProtect.Checked)
protectMotorStuck = true;
}
else if (stuckAcc <= (stuckAccTH - 50))
{
pictureBoxStuckDetect.BackColor = Color.Green;
if (checkBoxMotorProtect.Checked)
{
protectMotorStuck = false ;
}
}
//here we record encoder with GPS/IMU data
string recTemp = "#M,";
if (startRecord)
{
recTemp += leftFrontWheelMotor.encoderPos.ToString() + "," + rightFrontWheelMotor.encoderPos.ToString();
SW.WriteLine(recTemp);
recordCnt++;
if (recordCnt > MAXFILELEN)
{
recordCnt = 0;
SW.Close();
//open next file
SW = File.CreateText(fileNme + fileCnt.ToString() + ".txt");
fileCnt++;
}
}
}
private double Trans2Temperature(double adValue)
{
//for new temperature sensor
double tempM = 0;
double k = (adValue / FULLAD);
double resValue = 0;
if (k != 1)
resValue = 10000 * k / (1 - k); //AD value to resistor
else
resValue = resTable[0];
int index = -1;
if (resValue >= resTable[0]) //too lower
tempM = -20;
else if (resValue <= resTable[24])
tempM = 100;
else
{
for (int i = 0; i < 24; i++)
{
if ((resValue <= resTable[i]) && (resValue >= resTable[i + 1]))
{
index = i;
break;
}
}
if (index >= 0)
tempM = tempTable[index] + (resValue - resTable[index]) / (resTable[index + 1] - resTable[index]) * (tempTable[index + 1] - tempTable[index]);
else
tempM = 0;
}
return tempM;
}
#endregion
#region Joystick control
private bool InitDirectInput()
{
// Enumerate joysticks in the system.
int i = 0;
foreach (DeviceInstance instance in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
{
// Create the device. Just pick the first one
applicationDevice[i] = new Device(instance.InstanceGuid);
i++;
}
if ( (null == applicationDevice[0]))
{
// MessageBox.Show("Unable to create a joystick device.", "No joystick found");
return false;
}
i = 0;
// Set the data format to the c_dfDIJoystick pre-defined format.
applicationDevice[i].SetDataFormat(DeviceDataFormat.Joystick);
// Set the cooperative level for the device.
applicationDevice[i].SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Foreground);
// Enumerate all the objects on the device.
foreach (DeviceObjectInstance d in applicationDevice[i].Objects)
{
// For axes that are returned, set the DIPROP_RANGE property for the
// enumerated axis in order to scale min/max values.
if ((0 != (d.ObjectId & (int)DeviceObjectTypeFlags.Axis)))
{
// Set the range for the axis.
applicationDevice[i].Properties.SetRange(ParameterHow.ById, d.ObjectId, new InputRange(0, +10000));
}
}
return true;
}
private void GetData()
{
//first device for Arm control, second for wheel control
// Make sure there is a valid device.
if (null == applicationDevice[0])
return;
try
{
// Poll the device for info.
applicationDevice[0].Poll();
}
catch (InputException inputex)
{
if ((inputex is NotAcquiredException) || (inputex is InputLostException))
{
// Check to see if either the app
// needs to acquire the device, or
// if the app lost the device to another
// process.
try
{
// Acquire the device.
applicationDevice[0].Acquire();
}
catch (InputException)
{
// Failed to acquire the device.
// This could be because the app
// doesn't have focus.
realJaguar.DcMotorPwmNonTimeCtrAll(INIPWM, INIPWM, NOCONTROL, INIPWM , INIPWM , NOCONTROL);
return;
}
}
} //catch(InputException inputex)
// Get the state of the device.
try
{
joyState[0] = applicationDevice[0].CurrentJoystickState; }
// Catch any exceptions. None will be handled here,
// any device re-aquisition will be handled above.
// this is a place we can add control code -wf
catch (InputException)
{
realJaguar.DcMotorPwmNonTimeCtrAll(INIPWM, INIPWM, NOCONTROL, INIPWM , INIPWM , NOCONTROL);
return;
}
if (blnJoyStick)
{
int[] pov = joyState[0].GetPointOfView();
if (pov[0] == 9000)
{
// show axis camera in big panel
SetCameraSize(true);
}
else if (pov[0] == 27000)
{
//axis camera original size
SetCameraSize(false);
}
else if (pov[0] == 18000)
{
if (lightCtrl)
{
lightCtrl = false;
SetFrontLight();
}
}
else if (pov[0] == 0)
SetIniPos();
else
lightCtrl = true;
if ((!protectMotorTemp) && (!protectMotorStuck ))
UpdateWheelControl(); //consider also slowing wheels here
else
{
//stop first
realJaguar.DcMotorPwmNonTimeCtrAll(INIPWM, INIPWM, NOCONTROL, INIPWM, INIPWM, NOCONTROL);
}
if (!forceStop) UpdateArmControl();
}
}
private void UpdateWheelControl()
{
int x = (joyState[0].Y - 5000);
int y = -(joyState[0].Z- 5000);
double forwardP = 0;
double turnP = 0;
if (( Math.Abs(x) > 1000) || (Math.Abs(y) > 1000))
{
forwardP = (double)x / 5000 * 100;
if ((x > 0) && (Math.Abs(x) > 300))
y = -y;
turnP = (double)y / 5000 * 100;
trackBarForwardPower.Value = (int)(forwardP);
trackBarTurnPower.Value = (int)(turnP);
}
else
{
controlMode = MANUAL;
trackBarForwardPower.Value = 0;
trackBarTurnPower.Value = 0;
realJaguar.DcMotorPwmNonTimeCtrAll(NOCONTROL, NOCONTROL, NOCONTROL, INIPWM, INIPWM, NOCONTROL);
}
}
private void UpdateArmControl()
{
}
private void tmrJoyStickPoll_Tick(object sender, EventArgs e)
{
GetData();
}
#endregion
#region TrackBar control
private void trackBarForwardPower_ValueChanged(object sender, EventArgs e)
{
controlMode = MANUAL;
trackBarTurnPower.Value = 0;
forwardVel = 0;
if ((!protectMotorTemp) &&(!protectMotorStuck))
{
forwardVel = zeroOutput + (MOTDIR * trackBarForwardPower.Value) * (maxPosOutput - zeroOutput) / 100;
forwardVel = Math.Min(maxPosOutput, Math.Max(0, forwardVel));
}
else
forwardVel = zeroOutput;
// seems a minimum of 16 is needed for forwardVel to move.
if (Simulating())
simulatedJaguar.DcMotorPwmNonTimeCtrAll(0, 0, 0, (short)forwardVel, (short)(zeroOutput - (forwardVel-zeroOutput)), 0);
else
{
realJaguar.DcMotorPwmNonTimeCtrAll(0, 0, 0, (short)forwardVel, (short)(zeroOutput - (forwardVel - zeroOutput)), 0);
}
}
private void trackBarTurnPower_ValueChanged(object sender, EventArgs e)
{
controlMode = MANUAL;
trackBarForwardPower.Value = 0;
turnVel = 0;
if ((!protectMotorTemp) && (!protectMotorStuck))
{
turnVel = zeroOutput+(MOTDIR * trackBarTurnPower.Value)*(maxPosOutput-zeroOutput)/100;
turnVel = Math.Min(maxPosOutput, Math.Max(0, turnVel));
}
else