-
Notifications
You must be signed in to change notification settings - Fork 0
/
Form1.cs
2652 lines (2520 loc) · 130 KB
/
Form1.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.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using GMap.NET.ObjectModel;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using GMap.NET.MapProviders;
using GMap.NET;
using MySql.Data.MySqlClient;
using XBeeLibrary.Core;
using XBeeLibrary.Core.Models;
using System.Drawing.Drawing2D;
using System.Threading;
using CCWin;
using System.Numerics;
using IWshRuntimeLibrary;
using System.Reflection;
namespace GCS_5895
{
public partial class GCS_5895 : CCSkinMain
{
private float x;//定義當前窗體的寬度
private float y;//定義當前窗體的高度
public int default_UAVnumbers = 10; //預設無人機數量
public Dictionary<string, CoordinateTransform> Origin = new Dictionary<string, CoordinateTransform>()
{
{"沙崙草皮捲", new CoordinateTransform(22.9242595824972, 120.310152769089, 26.0, new PointLatLng(22.9246251967135, 120.309573411942))},
{"西瓜皮空地", new CoordinateTransform(22.9105162191694, 120.312446057796, 26.0, new PointLatLng(22.9105162191694, 120.312446057796))}
};
public List<int> existing_UAVs = new List<int>();
// 定義通訊管道
public static Socket client;
public bool client_connect;
// X2 ConnectPort (gateway)
public EndPoint connectPort = new IPEndPoint(IPAddress.Parse("169.254.219.218"), 14500);
public static int port_number = 14500;
public static XBeeLibrary.Windows.DigiMeshDevice XBee;
public string[] baudRate = new string[] { "Baud: 9600", "Baud: 115200" };
public Dictionary<int, RemoteDigiMeshDevice> G2U_points;
// 定義MySQL資料庫
MySqlConnection timelist_conn = new MySqlConnection("data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;database=timelist;" +
";pooling=true;charset=utf8;"); //紀錄任務開始時間
public List<MySqlConnection> UAVs_flightData_conn = new List<MySqlConnection>(); // 紀錄無人機飛行數據
// 定義座標系
CoordinateTransform coordinate;
// 定義google map
public List<GMapOverlay> markers_main = new List<GMapOverlay>();
public List<GMapRoute> marker_of_uavRoute = new List<GMapRoute>(); // 動態航線marker
public List<Color> color_of_uavs = new List<Color> { Color.DarkSeaGreen, Color.LightBlue, Color.RosyBrown, Color.Thistle,
Color.DarkGray, Color.LightSteelBlue, Color.DarkKhaki, Color.MediumTurquoise, Color.LightPink, Color.DarkSalmon}; // 無人機路徑及標籤顏色
public List<GMapOverlay> waypoints_pin = new List<GMapOverlay>();
public bool lockMap = false;
public bool isChooseWP = false;
public GMapMarker currentMarker;
public Point mousePin;
// 定義飛機圖案
Planes Planes = new Planes();
// 定義路線軌跡儲存空間
public SortableBindingList<Packets> Buffers = new SortableBindingList<Packets>();
public List<List<PointLatLng>> routesBuffer = new List<List<PointLatLng>>();
public double u2gFreq, route_seconds;
public int displayPoint;
public bool allRouteCheck = false;
// WP命令設定
public List<Waypoints> waypoints = new List<Waypoints>();
[Obsolete]
public GCS_5895()
{
InitializeComponent();
x = this.Width;
y = this.Height;
setTag(this);
// 座標系
coordinate = Origin["西瓜皮空地"]; //預設圓點
comboBox_origin.Items.AddRange(Origin.Keys.ToArray());
comboBox_origin.Text = "西瓜皮空地";
comboBox_mapCenter.Items.AddRange(Origin.Keys.ToArray());
comboBox_mapCenter.Text = "西瓜皮空地";
/* GMap 初始參數 */
// 離線地圖
GMaps.Instance.Mode = AccessMode.CacheOnly;
string mapPath = Application.StartupPath + "\\bingmap.gmdb";
GMaps.Instance.ImportFromGMDB(mapPath);
gMapControl_main.DragButton = MouseButtons.Left;
gMapControl_main.MapProvider = GMapProviders.GoogleMap;
gMapControl_main.Position = coordinate.mapCenter;
gMapControl_main.MaxZoom = 24;
gMapControl_main.MinZoom = 3;
gMapControl_main.Zoom = 20;
gMapControl_main.ShowCenter = false;
gMapControl_main.Manager.Mode = AccessMode.ServerAndCache;
// default parameters
u2gFreq = 1;
route_seconds = 5;
displayPoint = (int)Math.Round(u2gFreq * route_seconds, 0, MidpointRounding.AwayFromZero);
comboBox_u2gFreq.Items.AddRange(new string[] { "1", "2", "3", "5", "10"});
comboBox_u2gFreq.Text = $"{u2gFreq}";
comboBox_routeDisplay.Items.AddRange(new string[] { "2", "5", "10", "15", "20", "All Routes" });
comboBox_routeDisplay.Text = $"{route_seconds}";
// definre List
for (int i = 0; i < default_UAVnumbers; i++)
{
markers_main.Add(new GMapOverlay("markers" + (i + 1))); // 定義每台無人機的markers
marker_of_uavRoute.Add(new GMapRoute(Name = "route" + (i + 1))); // 定義每台無人機的Gmap路線
routesBuffer.Add(new List<PointLatLng>()); // 定義每台無人機的軌跡路線空間
waypoints_pin.Add(new GMapOverlay("waypoints" + (i + 1))); // 定義每台無人機的WPs markers
gMapControl_main.Overlays.Add(waypoints_pin[i]);
gMapControl_main.Overlays.Add(markers_main[i]);
// 定義飛行數據之資料庫管道並開啟通道
try
{
// check UAV databases
if (!existDatabase($"uav{i+1}"))
{
MySqlConnection mConnection = new MySqlConnection("data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;" +
";pooling=true;charset=utf8;");
mConnection.Open();
MySqlCommand mySqlCommand = new MySqlCommand($"CREATE DATABASE uav{i+1};", mConnection);
mySqlCommand.ExecuteNonQuery();
mConnection.Close();
}
UAVs_flightData_conn.Add(new MySqlConnection($"data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;database=uav{i + 1};pooling=true;charset=utf8;"));
UAVs_flightData_conn[i].Open();
if (!existTable("flight_data"))
{
MySqlConnection mConnection = new MySqlConnection("data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;" +
";pooling=true;charset=utf8;");
string createStatement = @"create table `flight_data`(`Timestamp` double,
`Datetime` varchar(30),`Mode` varchar(20),`Mission` varchar(20),
`E` double,`N` DOUBLE,`U` double,`Speed` double,
`Roll` double,`Pitch` double,`Yaw` double,primary key(`Timestamp`)); ";
using (UAVs_flightData_conn[i])
{
using (MySqlCommand cmd = new MySqlCommand(createStatement, UAVs_flightData_conn[i]))
{
cmd.ExecuteNonQuery();
}
}
}
}
catch
{
textBox_info.SelectionColor = Color.SlateGray;
textBox_info.AppendText($"⚠️ cannot connect to the uav{i+1} database!" + Environment.NewLine);
}
}
try
{
// check timelist database
if (!existDatabase("timelist"))
{
MySqlConnection mConnection = new MySqlConnection("data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;" +
";pooling=true;charset=utf8;");
mConnection.Open();
MySqlCommand mySqlCommand = new MySqlCommand($"CREATE DATABASE timelist;", mConnection);
mySqlCommand.ExecuteNonQuery();
mConnection.Close();
}
if (timelist_conn.State != ConnectionState.Open)
timelist_conn.Open();
if (!existTable("timeline"))
{
string createStatement = @"create table `timeline`(`No.` int auto_increment,`Mission` varchar(20),
`Status` varchar(100),`GCS Timestamp` double,`Datatime` varchar(30),primary key(`No.`));";
using (timelist_conn)
{
using (MySqlCommand cmd = new MySqlCommand(createStatement, timelist_conn))
{
cmd.ExecuteNonQuery();
}
}
}
}
catch
{
textBox_info.SelectionColor = Color.SlateGray;
textBox_info.AppendText("⚠️ cannot connect to the timelist database!" + Environment.NewLine);
}
dataGridView_flghtData.DataSource = Buffers;
string[] command = new string[] { "Arm", "Disarm", "Guided", "RTL", "Stabilize", "POSHOLD", "position", "Land", "Loiter", "Alt_Hod", "Auto" };
comboBox_Command.Items.AddRange(command);
dataGridView_flghtData.ForeColor = Color.Black;
dataGridView_mission.ForeColor = Color.Black;
// 任務設定
skinComboBox_SEAD.Items.AddRange(Mission_setting.SEAD_mission.Keys.ToArray());
// Drone Skin Initiate
skinPictureBox_quadSkin.Image = new Bitmap($"../../image/quad_{Planes.quadSkinIndex}.tif");
skinPictureBox_quadSkin.Image.Tag = Planes.quadSkinIndex;
skinPictureBox_fixedwingSkin.Image = new Bitmap($"../../image/fixed-wing_{Planes.fixedwingSkinIndex}.tif");
skinPictureBox_fixedwingSkin.Image.Tag = Planes.fixedwingSkinIndex;
//Shortcut update
CreateShortcut("5895GCS", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Assembly.GetExecutingAssembly().Location);
}
public void setTag(Control cons)
{
foreach (Control con in cons.Controls)
{
con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
if (con.Controls.Count > 0)
{
setTag(con);
}
}
}
public void setControls(float newx, float newy, Control cons)
{
//遍歷窗體中的控制元件,重新設定控制元件的值
foreach (Control con in cons.Controls)
{
//獲取控制元件的Tag屬性值,並分割後儲存字串陣列
if (con.Tag != null)
{
string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
//根據窗體縮放的比例確定控制元件的值
con.Width = Convert.ToInt32(Convert.ToSingle(mytag[0]) * newx);//寬度
con.Height = Convert.ToInt32(Convert.ToSingle(mytag[1]) * newy);//高度
con.Left = Convert.ToInt32(Convert.ToSingle(mytag[2]) * newx);//左邊距
con.Top = Convert.ToInt32(Convert.ToSingle(mytag[3]) * newy);//頂邊距
// Single currentSize = Convert.ToSingle(mytag[4]) * newy; //字型大小
// con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);//字型大小
if (con.Controls.Count > 0)
{
setControls(newx, newy, con);
}
}
}
}
private void GCS_5895_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Maximized)
{
gMapControl_main.Height -= 34;
}
float newx = (this.Width) / x;
float newy = (this.Height) / y;
setControls(newx, newy, this);
if (this.WindowState == FormWindowState.Maximized)
{
gMapControl_main.Height += 34;
}
}
private void GCS_5895_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show(this, "確定退出?", "退出視窗通知٩(✿∂‿∂✿)۶", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr != DialogResult.Yes)
{
e.Cancel = true;
}
}
public bool existDatabase(string databaseName)
{
MySqlConnection mConnection = new MySqlConnection("data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;" +
";pooling=true;charset=utf8;");
mConnection.Open();
MySqlCommand mySqlCommand = new MySqlCommand($@"SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME='{databaseName}'", mConnection);
MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
object name = mySqlDataReader.GetString(1);
if (name.ToString() == $"{databaseName}")
{
mConnection.Close();
return true;
}
}
mConnection.Close();
return false;
}
public bool existTable(string tableName)
{
MySqlConnection mConnection = new MySqlConnection("data source=127.0.0.1;;port=3306;user id=root;password=ncku5895;" +
";pooling=true;charset=utf8;");
mConnection.Open();
MySqlCommand mySqlCommand = new MySqlCommand($@"SELECT table_name FROM information_schema.TABLES WHERE table_name ='{tableName}';", mConnection);
if (mySqlCommand.ExecuteScalar() != null)
{
mConnection.Close();
return true;
}
mConnection.Close();
return false;
}
public static void CreateShortcut(string shortcutName, string shortcutPath, string targetFileLocation)
{
string deskTop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";
if (System.IO.File.Exists(deskTop + shortcutName + ".lnk")) //
{
System.IO.File.Delete(deskTop + shortcutName + ".lnk");//刪除原來的桌面快捷鍵方式
}
WshShell shell = new WshShell();
//快捷鍵方式建立的位置、名稱
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(deskTop + shortcutName + ".lnk");
shortcut.TargetPath = targetFileLocation; //目標檔案
//該屬性指定應用程式的工作目錄,當用戶沒有指定一個具體的目錄時,快捷方式的目標應用程式將使用該屬性所指定的目錄來裝載或儲存檔案。
shortcut.WorkingDirectory = System.Environment.CurrentDirectory;
shortcut.WindowStyle = 1; //目標應用程式的視窗狀態分為普通、最大化、最小化【1,3,7】
shortcut.Description = shortcutName; //描述
shortcut.IconLocation = System.IO.Path.Combine(Environment.CurrentDirectory, @"..\..\image\GCS icon.ico"); //快捷方式圖示
shortcut.Arguments = "";
shortcut.Save(); //必須呼叫儲存快捷才成建立成功
}
[Obsolete]
private void button_Connect_Click(object sender, EventArgs e)
{
switch (button_Connect.Text)
{
case "Connect":
if (String.IsNullOrEmpty(comboBox_connectOption.Text) || String.IsNullOrEmpty(comboBox_PortOrBaud.Text))
{
MessageBox.Show("Please select a connect method (ʘ言ʘ╬)");
}
else if (comboBox_connectOption.Text == "UDP")
{
try
{
var myHost = Dns.GetHostByName(Dns.GetHostName());
client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.Bind(new IPEndPoint(IPAddress.Parse(myHost.AddressList[0].ToString()), Int32.Parse(comboBox_PortOrBaud.Text.Remove(0, 6))));
client_connect = true;
// 連線成功後開啟背景執行接收訊息
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += backgroundReceiver;
bgw.RunWorkerAsync();
// 控件開啟
button_Publish.Enabled = true;
button_takeoff.Enabled = true;
button_FreqConfirm.Enabled = true;
skinButton_RTL.Enabled = true;
skinButton_HOLD.Enabled = true;
skinButton_loiter.Enabled = true;
skinButton_land.Enabled = true;
skinButton_arm.Enabled = true;
skinButton_disarm.Enabled = true;
skinButton_abort.Enabled = true;
button_Connect.Text = "Disconnect";
comboBox_connectOption.Enabled = false;
comboBox_PortOrBaud.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else if (comboBox_connectOption.Text.Contains("COM"))
{
try
{
XBee = new XBeeLibrary.Windows.DigiMeshDevice(comboBox_connectOption.Text, Int32.Parse(comboBox_PortOrBaud.Text.Remove(0, 6)));
XBee.Open(); //讀串口
G2U_points = new XBee_addr(XBee).G2U_points;
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += backgroundReceiver;
bgw.RunWorkerAsync();
button_Connect.Text = "Disconnect";
comboBox_connectOption.Enabled = false;
comboBox_PortOrBaud.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
break;
case "Disconnect":
try
{
// 關閉串口通道
if (comboBox_connectOption.Text == "UDP")
{
client.Close();
client_connect = false;
}
else
{
XBee.Close();
}
// 初始化地圖
for (int i = 0; i < default_UAVnumbers; i++)
{
markers_main[i].Clear();
routesBuffer[i].Clear();
waypoints_pin[i].Clear();
waypoints.Clear();
}
gMapControl_main.Position = coordinate.mapCenter;
gMapControl_main.Zoom = 20;
// 初始化連線設定
comboBox_PortOrBaud.Text = string.Empty;
comboBox_PortOrBaud.Items.Clear();
comboBox_connectOption.Text = string.Empty;
button_Connect.Text = "Connect";
comboBox_connectOption.Enabled = true;
comboBox_PortOrBaud.Enabled = true;
// 初始化儲存空間
Buffers.Clear();
existing_UAVs.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
}
}
// 背景執行訊息接收
void backgroundReceiver(object sender, EventArgs e)
{
string connectMethod = "";
this.Invoke(new Action(() =>
{
connectMethod = comboBox_connectOption.Text;
}));
if (connectMethod == "UDP")
{
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
byte[] packet;
int UDPDate = 0;
double time_received;
while (client_connect)
{
try
{
packet = new byte[1024];
UDPDate = client.ReceiveFrom(packet, ref point); //接收數據
time_received = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Packet_Processing(packet, time_received);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
else
{
XBeeMessage xbee_message;
double time_received;
byte[] packet;
while (XBee.IsOpen)
{
try
{
xbee_message = XBee.ReadData();
time_received = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
if (xbee_message != null)
{
packet = xbee_message.Data;
Packet_Processing(packet, time_received);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
private string UAV_ID_text(int uav_id)
{
string name;
if (uav_id < 10)
{
name = $"UAV0{uav_id}";
}
else
{
name = $"UAV{uav_id}";
}
return name;
}
private void Packet_Processing(byte[] packet, double receive_time)
{
int uav_id = packet[1];
this.Invoke(new Action(() =>
{
// 查看是否為已登錄無人機
if (!existing_UAVs.Contains(uav_id))
{
existing_UAVs.Add(uav_id);
existing_UAVs.Sort();
Buffers.Add(new Packets(coordinate, uav_id));
dataGridView_flghtData.Sort(dataGridView_flghtData.Columns["UAV_ID"], ListSortDirection.Ascending);
comboBox_mapCenter.Items.Add(UAV_ID_text(uav_id));
checkBoxComboBox_UAVselect.Items.Add(UAV_ID_text(uav_id));
}
// 解封包
int select_index = existing_UAVs.IndexOf(uav_id);
Buffers[select_index].unpack_packet(packet, receive_time);
dataGridView_flghtData.InvalidateRow(select_index);
// 訊息種類
switch (Buffers[select_index].Mission)
{
case Message_ID.Default:
case Message_ID.Waypoints:
case Message_ID.SEAD_mission:
// 清除該無人機markers
markers_main[uav_id - 1].Clear();
// plot uav on map
markers_main[uav_id - 1].Markers.Add(Planes.AddDrone(Buffers[select_index].Lat, Buffers[select_index].Lng, Buffers[select_index].Heading,
Buffers[select_index].Frame_type, UAV_ID_text(uav_id), new SolidBrush(color_of_uavs[uav_id - 1])));
// follow UAV
if (lockMap)
{
if (comboBox_mapCenter.Text.Contains("UAV") && existing_UAVs.IndexOf(Int32.Parse(comboBox_mapCenter.Text.Remove(0, 3))) == select_index)
{
gMapControl_main.Position = new PointLatLng(Buffers[select_index].Lat, Buffers[select_index].Lng);
}
}
// plot route
routesBuffer[uav_id - 1].Add(new PointLatLng(Buffers[select_index].Lat, Buffers[select_index].Lng));
if (routesBuffer[uav_id - 1].Count > displayPoint && !allRouteCheck)
{
routesBuffer[uav_id - 1] = routesBuffer[uav_id - 1].GetRange(routesBuffer[uav_id - 1].Count - displayPoint, displayPoint);
}
marker_of_uavRoute[uav_id - 1] = new GMapRoute(routesBuffer[uav_id - 1], marker_of_uavRoute[uav_id - 1].Name);
marker_of_uavRoute[uav_id - 1].Stroke = new Pen(color_of_uavs[uav_id - 1], 2);
markers_main[uav_id - 1].Routes.Add(marker_of_uavRoute[uav_id - 1]);
// 存進資料庫
try
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0).AddHours(8).AddSeconds(Buffers[select_index].GCS_timestamp);
string flightdata_sql = $@"insert into `flight_data` values
('{Buffers[select_index].UAV_timestamp}', '{dateTime}', '{Buffers[select_index].Mode}', '{Buffers[select_index].Mission}',
'{Buffers[select_index].E}', '{Buffers[select_index].N}', '{Buffers[select_index].U}', '{Buffers[select_index].Speed}',
'{Buffers[select_index].Roll}', '{Buffers[select_index].Pitch}', '{Buffers[select_index].Yaw}');";
MySqlCommand cmd = new MySqlCommand(flightdata_sql, UAVs_flightData_conn[uav_id - 1]);
cmd.ExecuteNonQuery();
}
catch { }
break;
case Message_ID.Time_Syncronize: // 時間同步校正
if (comboBox_connectOption.Text == "UDP")
{
client.SendTo(Buffers[select_index].pack_time_synchronize_packet(receive_time), connectPort);
}
else
{
XBee.SendData(G2U_points[uav_id], Buffers[select_index].pack_time_synchronize_packet(receive_time));
}
break;
case Message_ID.info: // 顯示無人機回傳訊息
textBox_info.SelectionColor = Color.Red;
textBox_info.AppendText($"UAV{uav_id} ");
textBox_info.SelectionColor = Color.Black;
textBox_info.AppendText(Buffers[select_index].Info + Environment.NewLine);
break;
case Message_ID.Record_Time: // 紀錄時間並顯示資訊
try
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0).AddHours(8).AddSeconds(Buffers[select_index].GCS_timestamp);
string timeline_sql = $@"insert into `timeline` (`Mission`, `Status`, `UAV Timestamp`, `GCS Timestamp`, `Datatime`)
values('{Buffers[select_index].Mission}',
'UAV{uav_id} {Buffers[select_index].Info}',
{Buffers[select_index].UAV_timestamp}, {receive_time}, '{dateTime}');";
MySqlCommand cmd = new MySqlCommand(timeline_sql, timelist_conn);
cmd.ExecuteNonQuery();
textBox_info.SelectionColor = Color.MediumSlateBlue;
textBox_info.AppendText($"UAV{uav_id} ");
textBox_info.SelectionColor = Color.Black;
textBox_info.AppendText($"{Buffers[select_index].Info} --- " +
$"{Math.Round(Buffers[select_index].UAV_timestamp, 3, MidpointRounding.AwayFromZero)}, " +
$"{Math.Round(receive_time, 3, MidpointRounding.AwayFromZero)}" + Environment.NewLine);
}
catch { }
break;
}
}));
}
// 更換地圖中心
private void comboBox_mapCenter_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox_mapCenter.Text.Contains("UAV"))
{
var select_uav_center = existing_UAVs.IndexOf(Int32.Parse(comboBox_mapCenter.Text.Remove(0, 3)));
gMapControl_main.Position = new PointLatLng(Buffers[select_uav_center].Lat, Buffers[select_uav_center].Lng);
}
else
{
gMapControl_main.Position = Origin[comboBox_mapCenter.Text].mapCenter;
gMapControl_main.Zoom = 20;
}
}
// read existing COM ports
private void comboBox_connectOption_DropDown(object sender, EventArgs e)
{
string[] port = SerialPort.GetPortNames();
Array.Sort(port);
comboBox_connectOption.Items.Clear();
comboBox_connectOption.Items.Add("UDP");
comboBox_connectOption.Items.AddRange(port);
}
// choose (COM: Baud) or (UDP: port)
private void comboBox_connectOption_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox_connectOption.Text == "UDP")
{
comboBox_PortOrBaud.Text = string.Empty;
comboBox_PortOrBaud.Items.Clear();
comboBox_PortOrBaud.Items.Add($"Port: {port_number}");
}
else if (comboBox_connectOption.Text != "UDP" && !String.IsNullOrEmpty(comboBox_connectOption.Text))
{
comboBox_PortOrBaud.Text = string.Empty;
comboBox_PortOrBaud.Items.Clear();
comboBox_PortOrBaud.Items.AddRange(baudRate);
}
}
private void checkBox_allUAVselect_CheckedChanged(object sender, EventArgs e)
{
if (checkBox_allUAVselect.Checked)
{
if (existing_UAVs.Any())
{
checkBoxComboBox_UAVselect.Enabled = false;
}
else
{
checkBox_allUAVselect.Checked = false;
MessageBox.Show("No existing UAV ༼つ ͡◕_ ͡◕ ༽つ");
}
}
else
{
checkBoxComboBox_UAVselect.Enabled = true;
}
}
private void button_Publish_Click(object sender, EventArgs e)
{
if ((!string.IsNullOrEmpty(checkBoxComboBox_UAVselect.Text) || checkBox_allUAVselect.Checked) && !string.IsNullOrEmpty(comboBox_Command.Text))
{
commandsTransmit(comboBox_Command.Text);
}
else
{
MessageBox.Show("Please fil in the command or UAV ༼つ ͡◕_ ͡◕ ༽つ");
}
}
private void button_guideClear_Click(object sender, EventArgs e)
{
textBox_wpE.Text = string.Empty;
textBox_wpN.Text = string.Empty;
textBox_wpU.Text = string.Empty;
if (!String.IsNullOrEmpty(comboBox_guideWP.Text))
{
int uav_id = Int32.Parse(comboBox_guideWP.Text.Remove(0, 3));
waypoints_pin[uav_id - 1].Clear();
waypoints.RemoveAll(p => p.UAV_ID == uav_id && p.Type == WaypointMissionMethod.guide_waypoint);
comboBox_guideWP.Text = string.Empty;
}
if (!waypoints.Any(p => p.Type == WaypointMissionMethod.guide_waypoint))
{
skinButton_pubWP.Enabled = false;
skinButton_clearWPs.Enabled = false;
}
textBox_WPguided.Text = string.Empty;
foreach (Waypoints wp in waypoints)
{
if (wp.Type == WaypointMissionMethod.guide_waypoint)
{
textBox_WPguided.AppendText($"UAV{wp.UAV_ID}: " +
$"[{wp.waypoints[0][0]}, {wp.waypoints[0][1]}, {wp.waypoints[0][2]}]" + Environment.NewLine);
}
}
}
private void comboBox_routeDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox_routeDisplay.Text == "All Routes")
{
allRouteCheck = true; // 顯示所有動態路線之變數
}
else
{
route_seconds = Int32.Parse(comboBox_routeDisplay.Text); // 顯示(route_seconds)秒前的軌跡
displayPoint = (int)Math.Round(u2gFreq * route_seconds, 0, MidpointRounding.AwayFromZero);
allRouteCheck = false;
}
}
private void button_FreqConfirm_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(checkBoxComboBox_UAVselect.Text) || checkBox_allUAVselect.Checked)
{
u2gFreq = Convert.ToDouble(comboBox_u2gFreq.Text);
foreach (Packets uav in Buffers)
{
if (comboBox_connectOption.Text == "UDP")
{
client.SendTo(uav.pack_commFreqAdjust_packet("U2G", u2gFreq), connectPort);
}
else
{
XBee.SendData(G2U_points[uav.UAV_ID], uav.pack_commFreqAdjust_packet("U2G", u2gFreq));
}
}
}
else
{
MessageBox.Show("Please fil in the UAV ༼つ ͡◕_ ͡◕ ༽つ");
}
}
private void button_WPconfirm_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBox_guideWP.Text) && !string.IsNullOrEmpty(textBox_wpE.Text)
&& !string.IsNullOrEmpty(textBox_wpN.Text) && !string.IsNullOrEmpty(textBox_wpU.Text))
{
int uav_id = Int32.Parse(comboBox_guideWP.Text.Remove(0, 3));
double[] enu;
if (string.IsNullOrEmpty(textBox_wpYaw.Text))
{
enu = new double[] { Double.Parse(textBox_wpE.Text), Double.Parse(textBox_wpN.Text), Double.Parse(textBox_wpU.Text) };
}
else
{
enu = new double[] { Double.Parse(textBox_wpE.Text), Double.Parse(textBox_wpN.Text), Double.Parse(textBox_wpU.Text),
Double.Parse(textBox_wpYaw.Text)};
}
var lla = coordinate.enu2llh(enu[0], enu[1], enu[2]);
waypoints_pin[uav_id - 1].Clear();
GMarkerGoogle target = new GMarkerGoogle(new PointLatLng(lla[0], lla[1]), GMarkerGoogleType.blue);
waypoints_pin[uav_id - 1].Markers.Add(target);
int select_index = existing_UAVs.IndexOf(uav_id);
List<PointLatLng> route = new List<PointLatLng>() {
new PointLatLng(Buffers[select_index].Lat, Buffers[select_index].Lng), new PointLatLng(lla[0], lla[1]) };
GMapRoute wp_route = new GMapRoute(route, $"UAV{uav_id} wp")
{
Stroke = new Pen(Color.DarkGray, 2)
};
wp_route.Stroke.DashStyle = DashStyle.Dash;
waypoints_pin[uav_id - 1].Routes.Add(wp_route);
var matches = waypoints.Find(p => p.UAV_ID == uav_id && p.Type == WaypointMissionMethod.guide_waypoint);
if (matches != null)
{
matches.waypoints.Clear();
matches.waypoints.Add(enu);
}
else
{
waypoints.Add(new Waypoints(uav_id, enu, WaypointMissionMethod.guide_waypoint));
}
comboBox_guideWP.Text = string.Empty;
textBox_wpE.Text = string.Empty;
textBox_wpN.Text = string.Empty;
skinButton_pubWP.Enabled = true;
skinButton_clearWPs.Enabled = true;
textBox_WPguided.Text = string.Empty;
foreach (Waypoints wp in waypoints)
{
if (wp.Type == WaypointMissionMethod.guide_waypoint)
{
if (wp.waypoints[0].Count() == 3)
{
textBox_WPguided.AppendText($"UAV{wp.UAV_ID}→" +
$"({wp.waypoints[0][0]}, {wp.waypoints[0][1]}, {wp.waypoints[0][2]})" + Environment.NewLine);
}
else
{
textBox_WPguided.AppendText($"UAV{wp.UAV_ID}→" +
$"({wp.waypoints[0][0]}, {wp.waypoints[0][1]}, {wp.waypoints[0][2]}) with {wp.waypoints[0][3]}(deg)" + Environment.NewLine);
}
}
}
}
else
{
MessageBox.Show("Please fill in waypoint or UAV.༼つ ͡◕_ ͡◕ ༽つ");
}
}
private void gMapControl_main_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
lockMap = false;
}
}
private void button_sortDataGrid_Click(object sender, EventArgs e)
{
// 刷新並調整顯示表格
dataGridView_flghtData.AutoResizeColumns();
}
private void comboBox_missionUAV_DropDown(object sender, EventArgs e)
{
comboBox_missionUAV.Items.Clear();
foreach (int uav_id in existing_UAVs)
{
comboBox_missionUAV.Items.Add(UAV_ID_text(uav_id));
}
}
private void button_missionPrepare_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBox_missionUAV.Text) && !string.IsNullOrEmpty(comboBox_missionTypeMission.Text) &&
!string.IsNullOrEmpty(comboBox_missionMethod.Text))
{
int uav_id = Int32.Parse(comboBox_missionUAV.Text.Remove(0, 3));
int select_index = existing_UAVs.IndexOf(uav_id);
waypoints.RemoveAll(p => p.UAV_ID == uav_id && p.Type != WaypointMissionMethod.guide_waypoint);
var start_pos = new double[] { Buffers[select_index].E, Buffers[select_index].N, Buffers[select_index].U,
Buffers[select_index].Heading};
var mission = Mission_setting.path_mission[comboBox_missionTypeMission.Text].Deepcopy();
mission.UAV_ID = uav_id;
mission.Type = Mission_setting.WaypointMissionMethod_name[comboBox_missionMethod.Text];
mission.start_position = start_pos;
waypoints.Add(mission);
var matches = waypoints.Last();
// plot on map (preplan)
try
{
var overlay = gMapControl_WPs.Overlays.First(p => p.Id == $"preplan {UAV_ID_text(uav_id)}");
overlay.Markers.Clear();
overlay.Routes.Clear();
}
catch
{
gMapControl_WPs.Overlays.Add(new GMapOverlay($"preplan {UAV_ID_text(uav_id)}"));
}
finally
{
List<PointLatLng> wps;
var overlay = gMapControl_WPs.Overlays.First(p => p.Id == $"preplan {UAV_ID_text(uav_id)}");
if (matches.Type == WaypointMissionMethod.CraigReynolds_Path_Following)
{
wps = new List<PointLatLng>() { };
}
else
{
wps = new List<PointLatLng>() { new PointLatLng(Buffers[select_index].Lat, Buffers[select_index].Lng) };
}
// add wps (default mission)
dataGridView_mission.Rows.Clear();
if (matches.waypoints.Count != 0)
{
dataGridView_mission.Rows.Add(matches.waypoints.Count);
}
var dubins = new DubinsPath();
for (int i = 0; i < matches.waypoints.Count; i++)
{
var wp = matches.waypoints[i];
var lla = coordinate.enu2llh(wp[0], wp[1], wp[2]);
overlay.Markers.Add(Planes.AddWaypoint(lla[0], lla[1], i + 1, GMarkerGoogleType.green));
if (matches.Type == WaypointMissionMethod.CraigReynolds_Path_Following &&
matches.pathFollowing_method == pathFollowingMethod.dubinsPath_following_velocity_PID)
{
try
{
var path = dubins.Dubins_shortestPath(new double[] { wp[0], wp[1], wp[3]},
new double[] { matches.waypoints[i + 1][0], matches.waypoints[i + 1][1], matches.waypoints[i + 1][3] }, matches.Rmin);
foreach (Vector3 point in path)
{
lla = coordinate.enu2llh(point.X, point.Y, point.Z);
wps.Add(new PointLatLng(lla[0], lla[1]));
}
}
catch { }
}
else
{
wps.Add(new PointLatLng(lla[0], lla[1]));
}
dataGridView_mission.Rows[i].Cells["order"].Value = i + 1;
dataGridView_mission.Rows[i].Cells["E"].Value = wp[0];
dataGridView_mission.Rows[i].Cells["N"].Value = wp[1];
dataGridView_mission.Rows[i].Cells["U"].Value = wp[2];
try { dataGridView_mission.Rows[i].Cells["heading"].Value = wp[3]; }
catch { }
dataGridView_mission.Rows[i].Cells["up"].Value = "▲";
dataGridView_mission.Rows[i].Cells["down"].Value = "▼";
dataGridView_mission.Rows[i].Cells["delete"].Value = "X";
}
dataGridView_mission.AutoResizeColumns();
GMapRoute ref_route = new GMapRoute(wps, $"preplan {UAV_ID_text(uav_id)}")
{
Stroke = new Pen(color_of_uavs[uav_id - 1], 4)
};
overlay.Routes.Add(ref_route);
overlay.Markers.Add(Planes.AddDrone(Buffers[select_index].Lat, Buffers[select_index].Lng, Buffers[select_index].Heading,
Buffers[select_index].Frame_type, UAV_ID_text(uav_id), new SolidBrush(color_of_uavs[uav_id - 1])));
button_missionConfirm.Enabled = true;
button_missionClear.Enabled = true;
}
}
else
{
MessageBox.Show("Mission inputs are missing ~");
}
}
private void button_startMission_Click(object sender, EventArgs e)
{
gMapControl_WPs.DragButton = MouseButtons.Left;
gMapControl_WPs.MapProvider = GMapProviders.GoogleMap;
gMapControl_WPs.Position = coordinate.mapCenter;
gMapControl_WPs.MaxZoom = 24;
gMapControl_WPs.MinZoom = 3;
gMapControl_WPs.Zoom = 19;
gMapControl_WPs.ShowCenter = false;
gMapControl_WPs.Manager.Mode = AccessMode.ServerAndCache;
comboBox_missionTypeMission.Enabled = true;
comboBox_missionUAV.Enabled = true;
comboBox_missionMethod.Enabled = true;
button_missionPrepare.Enabled = true;
button_missionCancel.Enabled = true;
// mission setting
comboBox_missionTypeMission.Items.Clear();
comboBox_missionTypeMission.Items.AddRange(Mission_setting.path_mission.Keys.ToArray());
comboBox_missionMethod.Items.Clear();
comboBox_missionMethod.Items.AddRange(Mission_setting.WaypointMissionMethod_name.Keys.ToArray());
}
private void button_missionCancel_Click(object sender, EventArgs e)
{
dataGridView_mission.Rows.Clear();
if (!String.IsNullOrEmpty(comboBox_missionUAV.Text))
{
var uav_id = Int32.Parse(comboBox_missionUAV.Text.Remove(0, 3));
waypoints.RemoveAll(p => p.UAV_ID == uav_id && p.Type != WaypointMissionMethod.guide_waypoint);
try
{
var overlay = gMapControl_WPs.Overlays.First(p => p.Id == $"preplan {UAV_ID_text(uav_id)}");
overlay.Markers.Clear();
overlay.Routes.Clear();
}
catch { }
}
if (waypoints.Find(p => p.Type != WaypointMissionMethod.guide_waypoint) == null)
{
skinComboBox_PubMission.Items.Remove("Waypoints mission");
}
comboBox_missionTypeMission.Text = string.Empty;
comboBox_missionUAV.Text = string.Empty;
comboBox_missionMethod.Text = string.Empty;
}
private void gMapControl_mission_MouseClick(object sender, MouseEventArgs e)
{
if (!skinButton_adjustMission.Enabled && e.Button == MouseButtons.Right && !String.IsNullOrEmpty(comboBox_missionUAV.Text) && !String.IsNullOrEmpty(comboBox_missionTypeMission.Text))
{