forked from ArduPilot/MissionPlanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainV2.cs
2946 lines (2504 loc) · 117 KB
/
MainV2.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.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Collections;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Threading;
using MissionPlanner.Utilities;
using IronPython.Hosting;
using log4net;
using MissionPlanner.Controls;
using MissionPlanner.Comms;
using Transitions;
using System.Speech.Synthesis;
namespace MissionPlanner
{
public partial class MainV2 : Form
{
private static readonly ILog log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static class NativeMethods
{
// used to hide/show console window
[DllImport("user32.dll")]
public static extern int FindWindow(string szClass, string szTitle);
[DllImport("user32.dll")]
public static extern int ShowWindow(int Handle, int showState);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr RegisterDeviceNotification
(IntPtr hRecipient,
IntPtr NotificationFilter,
Int32 Flags);
// Import SetThreadExecutionState Win32 API and necessary flags
[DllImport("kernel32.dll")]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
static public int SW_SHOWNORMAL = 1;
static public int SW_HIDE = 0;
}
static menuicons displayicons = new menuicons1();
public abstract class menuicons
{
public abstract Image fd { get; }
public abstract Image fp { get; }
public abstract Image initsetup { get; }
public abstract Image config_tuning { get; }
public abstract Image sim { get; }
public abstract Image terminal { get; }
public abstract Image help { get; }
public abstract Image donate { get; }
public abstract Image connect { get; }
public abstract Image disconnect { get; }
public abstract Image bg { get; }
}
public class menuicons1 : menuicons
{
public override Image fd { get { return global::MissionPlanner.Properties.Resources.light_flightdata_icon; } }
public override Image fp { get { return global::MissionPlanner.Properties.Resources.light_flightplan_icon; } }
public override Image initsetup { get { return global::MissionPlanner.Properties.Resources.light_initialsetup_icon; } }
public override Image config_tuning { get { return global::MissionPlanner.Properties.Resources.light_tuningconfig_icon; } }
public override Image sim { get { return global::MissionPlanner.Properties.Resources.light_simulation_icon; } }
public override Image terminal { get { return global::MissionPlanner.Properties.Resources.light_terminal_icon; } }
public override Image help { get { return global::MissionPlanner.Properties.Resources.light_help_icon; } }
public override Image donate { get { return global::MissionPlanner.Properties.Resources.donate; } }
public override Image connect { get { return global::MissionPlanner.Properties.Resources.light_connect_icon; } }
public override Image disconnect { get { return global::MissionPlanner.Properties.Resources.light_disconnect_icon; } }
public override Image bg { get { return global::MissionPlanner.Properties.Resources.bgdark; } }
}
public class menuicons2 : menuicons
{
public override Image fd { get { return global::MissionPlanner.Properties.Resources.dark_flightdata_icon; } }
public override Image fp { get { return global::MissionPlanner.Properties.Resources.dark_flightplan_icon; } }
public override Image initsetup { get { return global::MissionPlanner.Properties.Resources.dark_initialsetup_icon; } }
public override Image config_tuning { get { return global::MissionPlanner.Properties.Resources.dark_tuningconfig_icon; } }
public override Image sim { get { return global::MissionPlanner.Properties.Resources.dark_simulation_icon; } }
public override Image terminal { get { return global::MissionPlanner.Properties.Resources.dark_terminal_icon; } }
public override Image help { get { return global::MissionPlanner.Properties.Resources.dark_help_icon; } }
public override Image donate { get { return global::MissionPlanner.Properties.Resources.donate; } }
public override Image connect { get { return global::MissionPlanner.Properties.Resources.dark_connect_icon; } }
public override Image disconnect { get { return global::MissionPlanner.Properties.Resources.dark_disconnect_icon; } }
public override Image bg { get { return null; } }
}
Controls.MainSwitcher MyView;
static bool _advanced = false;
/// <summary>
/// Control what is displayed
/// </summary>
public static Boolean Advanced
{
get
{
return _advanced;
}
set
{
_advanced = value;
MissionPlanner.Controls.BackstageView.BackstageView.Advanced = value;
if (AdvancedChanged != null)
AdvancedChanged(null, new EventArgs());
}
}
public static bool ShowAirports { get; set; }
public static bool ShowTFR { get; set; }
private Utilities.adsb _adsb;
public bool EnableADSB
{
get { return _adsb != null; }
set
{
if (value == true)
{
_adsb = new Utilities.adsb();
if (MainV2.config["adsbserver"] != null)
Utilities.adsb.server = MainV2.config["adsbserver"].ToString();
if (MainV2.config["adsbport"] != null)
Utilities.adsb.serverport = int.Parse(MainV2.config["adsbport"].ToString());
}
else
{
Utilities.adsb.Stop();
_adsb = null;
}
}
}
public static event EventHandler AdvancedChanged;
/// <summary>
/// Active Comport interface
/// </summary>
public static MAVLinkInterface comPort = new MAVLinkInterface();
/// <summary>
/// passive comports
/// </summary>
public static List<MAVLinkInterface> Comports = new List<MAVLinkInterface>();
public delegate void WMDeviceChangeEventHandler(WM_DEVICECHANGE_enum cause);
public event WMDeviceChangeEventHandler DeviceChanged;
/// <summary>
/// other planes in the area from adsb
/// </summary>
internal object adsblock = new object();
public Hashtable adsbPlanes = new Hashtable();
public Hashtable adsbPlaneAge = new Hashtable();
string titlebar;
/// <summary>
/// Comport name
/// </summary>
public static string comPortName = "";
/// <summary>
/// use to store all internal config
/// </summary>
public static Hashtable config = new Hashtable();
/// <summary>
/// mono detection
/// </summary>
public static bool MONO = false;
/// <summary>
/// speech engine enable
/// </summary>
public static bool speechEnable = false;
/// <summary>
/// spech engine static class
/// </summary>
public static Speech speechEngine = null;
/// <summary>
/// joystick static class
/// </summary>
public static Joystick.Joystick joystick = null;
/// <summary>
/// track last joystick packet sent. used to control rate
/// </summary>
DateTime lastjoystick = DateTime.Now;
/// <summary>
/// determine if we are running sitl
/// </summary>
public static bool sitl
{
get
{
if (MissionPlanner.Controls.SITL.SITLSEND == null) return false;
if (MissionPlanner.Controls.SITL.SITLSEND.Client.Connected) return true;
return false;
}
}
/// <summary>
/// hud background image grabber from a video stream - not realy that efficent. ie no hardware overlays etc.
/// </summary>
public static WebCamService.Capture cam = null;
/// <summary>
/// controls the main serial reader thread
/// </summary>
bool serialThread = false;
bool pluginthreadrun = false;
bool joystickthreadrun = false;
Thread httpthread;
Thread joystickthread;
Thread serialreaderthread;
Thread pluginthread;
/// <summary>
/// track the last heartbeat sent
/// </summary>
private DateTime heatbeatSend = DateTime.Now;
/// <summary>
/// used to call anything as needed.
/// </summary>
public static MainV2 instance = null;
public static string LogDir
{
get
{
if (config["logdirectory"] == null)
return _logdir;
return config["logdirectory"].ToString();
}
set
{
_logdir = value;
config["logdirectory"] = value;
}
}
static string _logdir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"logs";
public static MainSwitcher View;
/// <summary>
/// store the time we first connect
/// </summary>
DateTime connecttime = DateTime.Now;
DateTime nodatawarning = DateTime.Now;
DateTime OpenTime = DateTime.Now;
/// <summary>
/// enum of firmwares
/// </summary>
public enum Firmwares
{
ArduPlane,
ArduCopter2,
ArduRover,
Ateryx,
ArduTracker,
Gymbal
}
DateTime connectButtonUpdate = DateTime.Now;
/// <summary>
/// declared here if i want a "single" instance of the form
/// ie configuration gets reloaded on every click
/// </summary>
public GCSViews.FlightData FlightData;
public GCSViews.FlightPlanner FlightPlanner;
GCSViews.Simulation Simulation;
private Form connectionStatsForm;
private ConnectionStats _connectionStats;
/// <summary>
/// This 'Control' is the toolstrip control that holds the comport combo, baudrate combo etc
/// Otiginally seperate controls, each hosted in a toolstip sqaure, combined into this custom
/// control for layout reasons.
/// </summary>
static internal ConnectionControl _connectionControl;
public void updateAdvanced(object sender, EventArgs e)
{
if (Advanced == false)
{
MenuTerminal.Visible = false;
MenuSimulation.Visible = false;
}
else
{
MenuTerminal.Visible = true;
MenuSimulation.Visible = true;
}
}
public MainV2()
{
log.Info("Mainv2 ctor");
ShowAirports = true;
// setup adsb
Utilities.adsb.UpdatePlanePosition += adsb_UpdatePlanePosition;
Form splash = Program.Splash;
splash.Refresh();
Application.DoEvents();
instance = this;
//disable dpi scaling
if (Font.Name != "宋体") //Chinese displayed normally when scaling. But would be too small or large using this line of code.
Font = new Font(Font.Name, 8.25f * 96f / CreateGraphics().DpiX, Font.Style, Font.Unit, Font.GdiCharSet, Font.GdiVerticalFont);
InitializeComponent();
MyView = new MainSwitcher(this);
View = MyView;
AdvancedChanged += updateAdvanced;
//startup console
TCPConsole.Write((byte)'S');
// full screen
//this.TopMost = true;
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
//this.WindowState = FormWindowState.Maximized;
_connectionControl = toolStripConnectionControl.ConnectionControl;
_connectionControl.CMB_baudrate.TextChanged += this.CMB_baudrate_TextChanged;
_connectionControl.CMB_serialport.SelectedIndexChanged += this.CMB_serialport_SelectedIndexChanged;
_connectionControl.CMB_serialport.Click += this.CMB_serialport_Click;
_connectionControl.TOOL_APMFirmware.SelectedIndexChanged += this.TOOL_APMFirmware_SelectedIndexChanged;
_connectionControl.ShowLinkStats += (sender, e) => ShowConnectionStatsForm();
srtm.datadirectory = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "srtm";
var t = Type.GetType("Mono.Runtime");
MONO = (t != null);
speechEngine = new Speech();
Warnings.CustomWarning.defaultsrc = comPort.MAV.cs;
Warnings.WarningEngine.Start();
// proxy loader - dll load now instead of on config form load
new Transition(new TransitionType_EaseInEaseOut(2000));
//MyRenderer.currentpressed = MenuFlightData;
//MainMenu.Renderer = new MyRenderer();
foreach (object obj in Enum.GetValues(typeof(Firmwares)))
{
_connectionControl.TOOL_APMFirmware.Items.Add(obj);
}
if (_connectionControl.TOOL_APMFirmware.Items.Count > 0)
_connectionControl.TOOL_APMFirmware.SelectedIndex = 0;
comPort.BaseStream.BaudRate = 115200;
PopulateSerialportList();
if (_connectionControl.CMB_serialport.Items.Count > 0)
{
_connectionControl.CMB_baudrate.SelectedIndex = 8;
_connectionControl.CMB_serialport.SelectedIndex = 0;
}
// ** Done
splash.Refresh();
Application.DoEvents();
// set this before we reset it
MainV2.config["NUM_tracklength"] = "200";
// create one here - but override on load
MainV2.config["guid"] = Guid.NewGuid().ToString();
// load config
xmlconfig(false);
MissionPlanner.Utilities.Tracking.cid = new Guid(MainV2.config["guid"].ToString());
// setup guids for droneshare
if (!MainV2.config.ContainsKey("plane_guid"))
MainV2.config["plane_guid"] = Guid.NewGuid().ToString();
if (!MainV2.config.ContainsKey("copter_guid"))
MainV2.config["copter_guid"] = Guid.NewGuid().ToString();
if (!MainV2.config.ContainsKey("rover_guid"))
MainV2.config["rover_guid"] = Guid.NewGuid().ToString();
if (config.ContainsKey("language") && !string.IsNullOrEmpty((string)config["language"]))
{
changelanguage(CultureInfoEx.GetCultureInfo((string)config["language"]));
}
this.Text = splash.Text;
titlebar = splash.Text;
if (!MONO) // windows only
{
if (MainV2.config["showconsole"] != null && MainV2.config["showconsole"].ToString() == "True")
{
}
else
{
int win = NativeMethods.FindWindow("ConsoleWindowClass", null);
NativeMethods.ShowWindow(win, NativeMethods.SW_HIDE); // hide window
}
// prevent system from sleeping while mp open
var previousExecutionState = NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
}
ChangeUnits();
if (config["theme"] != null)
{
ThemeManager.SetTheme((ThemeManager.Themes)Enum.Parse(typeof(ThemeManager.Themes), MainV2.config["theme"].ToString()));
if (ThemeManager.CurrentTheme == ThemeManager.Themes.Custom)
{
try
{
ThemeManager.BGColor = Color.FromArgb(int.Parse(MainV2.config["theme_bg"].ToString()));
ThemeManager.ControlBGColor = Color.FromArgb(int.Parse(MainV2.config["theme_ctlbg"].ToString()));
ThemeManager.TextColor = Color.FromArgb(int.Parse(MainV2.config["theme_text"].ToString()));
ThemeManager.ButBG = Color.FromArgb(int.Parse(MainV2.config["theme_butbg"].ToString()));
ThemeManager.ButBorder = Color.FromArgb(int.Parse(MainV2.config["theme_butbord"].ToString()));
}
catch { log.Error("Bad Custom theme - reset to standard"); ThemeManager.SetTheme(ThemeManager.Themes.BurntKermit); }
}
if (ThemeManager.CurrentTheme == ThemeManager.Themes.HighContrast)
{
switchlight(new menuicons2());
}
}
if (MainV2.config["showairports"] != null)
{
MainV2.ShowAirports = bool.Parse(config["showairports"].ToString());
}
// set default
ShowTFR = true;
// load saved
if (MainV2.config["showtfr"] != null)
{
MainV2.ShowTFR = bool.Parse(config["showtfr"].ToString());
}
if (MainV2.config["enableadsb"] != null)
{
MainV2.instance.EnableADSB = bool.Parse(config["enableadsb"].ToString());
}
// load this before the other screens get loaded
if (MainV2.config["advancedview"] != null)
{
MainV2.Advanced = bool.Parse(config["advancedview"].ToString());
}
else
{
// existing user - enable advanced view
if (MainV2.config.Count > 3)
{
config["advancedview"] = true.ToString();
MainV2.Advanced = true;
}
else
{
config["advancedview"] = false.ToString();
}
}
try
{
log.Info("Create FD");
FlightData = new GCSViews.FlightData();
log.Info("Create FP");
FlightPlanner = new GCSViews.FlightPlanner();
//Configuration = new GCSViews.ConfigurationView.Setup();
log.Info("Create SIM");
Simulation = new GCSViews.Simulation();
//Firmware = new GCSViews.Firmware();
//Terminal = new GCSViews.Terminal();
FlightData.Width = MyView.Width;
FlightPlanner.Width = MyView.Width;
Simulation.Width = MyView.Width;
}
catch (ArgumentException e)
{
//http://www.microsoft.com/en-us/download/details.aspx?id=16083
//System.ArgumentException: Font 'Arial' does not support style 'Regular'.
log.Fatal(e);
CustomMessageBox.Show(e.ToString() + "\n\n Font Issues? Please install this http://www.microsoft.com/en-us/download/details.aspx?id=16083");
//splash.Close();
//this.Close();
Application.Exit();
}
catch (Exception e) { log.Fatal(e); CustomMessageBox.Show("A Major error has occured : " + e.ToString()); Application.Exit(); }
if (MainV2.config["CHK_GDIPlus"] != null)
GCSViews.FlightData.myhud.UseOpenGL = !bool.Parse(MainV2.config["CHK_GDIPlus"].ToString());
if (MainV2.config["CHK_hudshow"] != null)
GCSViews.FlightData.myhud.hudon = bool.Parse(MainV2.config["CHK_hudshow"].ToString());
try
{
if (config["MainLocX"] != null && config["MainLocY"] != null)
{
this.StartPosition = FormStartPosition.Manual;
Point startpos = new Point(int.Parse(config["MainLocX"].ToString()), int.Parse(config["MainLocY"].ToString()));
this.Location = startpos;
}
if (config["MainMaximised"] != null)
{
this.WindowState = (FormWindowState)Enum.Parse(typeof(FormWindowState), config["MainMaximised"].ToString());
// dont allow minimised start state
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
this.Location = new Point(100, 100);
}
}
if (config["MainHeight"] != null)
this.Height = int.Parse(config["MainHeight"].ToString());
if (config["MainWidth"] != null)
this.Width = int.Parse(config["MainWidth"].ToString());
if (config["CMB_rateattitude"] != null)
MainV2.comPort.MAV.cs.rateattitude = byte.Parse(config["CMB_rateattitude"].ToString());
if (config["CMB_rateposition"] != null)
MainV2.comPort.MAV.cs.rateposition = byte.Parse(config["CMB_rateposition"].ToString());
if (config["CMB_ratestatus"] != null)
MainV2.comPort.MAV.cs.ratestatus = byte.Parse(config["CMB_ratestatus"].ToString());
if (config["CMB_raterc"] != null)
MainV2.comPort.MAV.cs.raterc = byte.Parse(config["CMB_raterc"].ToString());
if (config["CMB_ratesensors"] != null)
MainV2.comPort.MAV.cs.ratesensors = byte.Parse(config["CMB_ratesensors"].ToString());
if (config["speechenable"] != null)
MainV2.speechEnable = bool.Parse(config["speechenable"].ToString());
if (MainV2.config["analyticsoptout"] != null)
MissionPlanner.Utilities.Tracking.OptOut = bool.Parse(config["analyticsoptout"].ToString());
try
{
if (config["TXT_homelat"] != null)
MainV2.comPort.MAV.cs.HomeLocation.Lat = double.Parse(config["TXT_homelat"].ToString());
if (config["TXT_homelng"] != null)
MainV2.comPort.MAV.cs.HomeLocation.Lng = double.Parse(config["TXT_homelng"].ToString());
if (config["TXT_homealt"] != null)
MainV2.comPort.MAV.cs.HomeLocation.Alt = double.Parse(config["TXT_homealt"].ToString());
// remove invalid entrys
if (Math.Abs(MainV2.comPort.MAV.cs.HomeLocation.Lat) > 90 || Math.Abs(MainV2.comPort.MAV.cs.HomeLocation.Lng) > 180)
MainV2.comPort.MAV.cs.HomeLocation = new PointLatLngAlt();
}
catch { }
}
catch { }
if (MainV2.comPort.MAV.cs.rateattitude == 0) // initilised to 10, configured above from save
{
CustomMessageBox.Show("NOTE: your attitude rate is 0, the hud will not work\nChange in Configuration > Planner > Telemetry Rates");
}
// log dir
if (config["logdirectory"] != null)
MainV2.LogDir = config["logdirectory"].ToString();
// create log dir if it doesnt exist
if (!Directory.Exists(MainV2.LogDir))
Directory.CreateDirectory(MainV2.LogDir);
//System.Threading.Thread.Sleep(2000);
Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
// make sure new enough .net framework is installed
if (!MONO)
{
Microsoft.Win32.RegistryKey installed_versions = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
string[] version_names = installed_versions.GetSubKeyNames();
//version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture);
int SP = Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1]).GetValue("SP", 0));
if (Framework < 4.0)
{
CustomMessageBox.Show("This program requires .NET Framework 4.0. You currently have " + Framework);
}
}
if (Program.Logo != null)
{
this.Icon = Icon.FromHandle(((Bitmap)Program.Logo).GetHicon());
}
if (Program.Logo != null && Program.vvvvz)
{
MenuDonate.Click -= this.toolStripMenuItem1_Click;
MenuDonate.Text = "";
MenuDonate.Image = Program.Logo;
MenuDonate.Click += MenuCustom_Click;
MenuFlightData.Visible = false;
MenuFlightPlanner.Visible = true;
MenuConfigTune.Visible = false;
MenuHelp.Visible = false;
MenuInitConfig.Visible = false;
MenuSimulation.Visible = false;
MenuTerminal.Visible = false;
}
Application.DoEvents();
Comports.Add(comPort);
// save config to test we have write access
xmlconfig(true);
}
void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
// try prevent crash on resume
if (e.Mode == Microsoft.Win32.PowerModes.Suspend)
{
doDisconnect(MainV2.comPort);
}
}
private void BGLoadAirports(object nothing)
{
// read airport list
try
{
Utilities.Airports.ReadOurairports(Application.StartupPath + Path.DirectorySeparatorChar + "airports.csv");
Utilities.Airports.checkdups = true;
//Utilities.Airports.ReadOpenflights(Application.StartupPath + Path.DirectorySeparatorChar + "airports.dat");
log.Info("Loaded " + Utilities.Airports.GetAirportCount + " airports");
}
catch { }
}
void switchlight(menuicons icons)
{
displayicons = icons;
MainMenu.BackColor = SystemColors.MenuBar;
MainMenu.BackgroundImage = displayicons.bg;
MenuFlightData.Image = displayicons.fd;
MenuFlightPlanner.Image = displayicons.fp;
MenuInitConfig.Image = displayicons.config_tuning;
MenuSimulation.Image = displayicons.sim;
MenuConfigTune.Image = displayicons.config_tuning;
MenuTerminal.Image = displayicons.terminal;
MenuConnect.Image = displayicons.connect;
MenuHelp.Image = displayicons.help;
MenuDonate.Image = displayicons.donate;
MenuFlightData.ForeColor = ThemeManager.TextColor;
MenuFlightPlanner.ForeColor = ThemeManager.TextColor;
MenuInitConfig.ForeColor = ThemeManager.TextColor;
MenuSimulation.ForeColor = ThemeManager.TextColor;
MenuConfigTune.ForeColor = ThemeManager.TextColor;
MenuTerminal.ForeColor = ThemeManager.TextColor;
MenuConnect.ForeColor = ThemeManager.TextColor;
MenuHelp.ForeColor = ThemeManager.TextColor;
MenuDonate.ForeColor = ThemeManager.TextColor;
}
void MenuCustom_Click(object sender, EventArgs e)
{
if (getConfig("password_protect") == "" || bool.Parse(getConfig("password_protect")) == false)
{
MenuFlightData.Visible = true;
MenuFlightPlanner.Visible = true;
MenuConfigTune.Visible = true;
MenuHelp.Visible = true;
MenuInitConfig.Visible = true;
MenuSimulation.Visible = true;
MenuTerminal.Visible = true;
}
else
{
if (Password.VerifyPassword())
{
MenuFlightData.Visible = true;
MenuFlightPlanner.Visible = true;
MenuConfigTune.Visible = true;
MenuHelp.Visible = true;
MenuInitConfig.Visible = true;
MenuSimulation.Visible = true;
MenuTerminal.Visible = true;
}
}
}
void adsb_UpdatePlanePosition(object sender, EventArgs e)
{
lock (adsblock)
{
adsbPlanes[((MissionPlanner.Utilities.adsb.PointLatLngAltHdg)sender).Tag] = ((MissionPlanner.Utilities.adsb.PointLatLngAltHdg)sender);
adsbPlaneAge[((MissionPlanner.Utilities.adsb.PointLatLngAltHdg)sender).Tag] = DateTime.Now;
}
}
private void ResetConnectionStats()
{
log.Info("Reset connection stats");
// If the form has been closed, or never shown before, we need do nothing, as
// connection stats will be reset when shown
if (this.connectionStatsForm != null && connectionStatsForm.Visible)
{
// else the form is already showing. reset the stats
this.connectionStatsForm.Controls.Clear();
_connectionStats = new ConnectionStats(comPort);
this.connectionStatsForm.Controls.Add(_connectionStats);
ThemeManager.ApplyThemeTo(this.connectionStatsForm);
}
}
private void ShowConnectionStatsForm()
{
if (this.connectionStatsForm == null || this.connectionStatsForm.IsDisposed)
{
// If the form has been closed, or never shown before, we need all new stuff
this.connectionStatsForm = new Form
{
Width = 430,
Height = 180,
MaximizeBox = false,
MinimizeBox = false,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = Strings.LinkStats
};
// Change the connection stats control, so that when/if the connection stats form is showing,
// there will be something to see
this.connectionStatsForm.Controls.Clear();
_connectionStats = new ConnectionStats(comPort);
this.connectionStatsForm.Controls.Add(_connectionStats);
this.connectionStatsForm.Width = _connectionStats.Width;
}
this.connectionStatsForm.Show();
ThemeManager.ApplyThemeTo(this.connectionStatsForm);
}
private void CMB_serialport_Click(object sender, EventArgs e)
{
string oldport = _connectionControl.CMB_serialport.Text;
PopulateSerialportList();
if (_connectionControl.CMB_serialport.Items.Contains(oldport))
_connectionControl.CMB_serialport.Text = oldport;
}
private void PopulateSerialportList()
{
_connectionControl.CMB_serialport.Items.Clear();
_connectionControl.CMB_serialport.Items.Add("AUTO");
_connectionControl.CMB_serialport.Items.AddRange(SerialPort.GetPortNames());
_connectionControl.CMB_serialport.Items.Add("TCP");
_connectionControl.CMB_serialport.Items.Add("UDP");
_connectionControl.CMB_serialport.Items.Add("UDPCl");
}
private void MenuFlightData_Click(object sender, EventArgs e)
{
MyView.ShowScreen("FlightData");
}
private void MenuFlightPlanner_Click(object sender, EventArgs e)
{
MyView.ShowScreen("FlightPlanner");
}
public void MenuSetup_Click(object sender, EventArgs e)
{
if (getConfig("password_protect") == "" || bool.Parse(getConfig("password_protect")) == false)
{
MyView.ShowScreen("HWConfig");
}
else
{
if (Password.VerifyPassword())
{
MyView.ShowScreen("HWConfig");
}
}
}
private void MenuSimulation_Click(object sender, EventArgs e)
{
MyView.ShowScreen("Simulation");
}
private void MenuTuning_Click(object sender, EventArgs e)
{
if (getConfig("password_protect") == "" || bool.Parse(getConfig("password_protect")) == false)
{
MyView.ShowScreen("SWConfig");
}
else
{
if (Password.VerifyPassword())
{
MyView.ShowScreen("SWConfig");
}
}
}
private void MenuTerminal_Click(object sender, EventArgs e)
{
MyView.ShowScreen("Terminal");
}
public void doDisconnect(MAVLinkInterface comPort)
{
log.Info("We are disconnecting");
try
{
if (speechEngine != null) // cancel all pending speech
speechEngine.SpeakAsyncCancelAll();
comPort.BaseStream.DtrEnable = false;
comPort.Close();
}
catch (Exception ex)
{
log.Error(ex);
}
// now that we have closed the connection, cancel the connection stats
// so that the 'time connected' etc does not grow, but the user can still
// look at the now frozen stats on the still open form
try
{
// if terminal is used, then closed using this button.... exception
if (this.connectionStatsForm != null)
((ConnectionStats)this.connectionStatsForm.Controls[0]).StopUpdates();
}
catch { }
// refresh config window if needed
if (MyView.current != null)
{
if (MyView.current.Name == "HWConfig")
MyView.ShowScreen("HWConfig");
if (MyView.current.Name == "SWConfig")
MyView.ShowScreen("SWConfig");
}
try
{
System.Threading.ThreadPool.QueueUserWorkItem((WaitCallback)delegate
{
try
{
MissionPlanner.Log.LogSort.SortLogs(Directory.GetFiles(MainV2.LogDir, "*.tlog"));
}
catch { }
}
);
}
catch { }
this.MenuConnect.Image = global::MissionPlanner.Properties.Resources.light_connect_icon;
}
public void doConnect(MAVLinkInterface comPort, string portname, string baud)
{
bool skipconnectcheck = false;
log.Info("We are connecting");
switch (portname)
{
case "preset":
skipconnectcheck = true;
break;
case "TCP":
comPort.BaseStream = new TcpSerial();
_connectionControl.CMB_serialport.Text = "TCP";
break;
case "UDP":
comPort.BaseStream = new UdpSerial();
_connectionControl.CMB_serialport.Text = "UDP";
break;
case "UDPCl":
comPort.BaseStream = new UdpSerialConnect();
_connectionControl.CMB_serialport.Text = "UDPCl";
break;
case "AUTO":
default:
comPort.BaseStream = new SerialPort();
break;
}
// Tell the connection UI that we are now connected.
_connectionControl.IsConnected(true);
// Here we want to reset the connection stats counter etc.
this.ResetConnectionStats();
comPort.MAV.cs.ResetInternals();
//cleanup any log being played
comPort.logreadmode = false;
if (comPort.logplaybackfile != null)
comPort.logplaybackfile.Close();
comPort.logplaybackfile = null;
try
{
// do autoscan
if (portname == "AUTO")
{
Comms.CommsSerialScan.Scan(false);
DateTime deadline = DateTime.Now.AddSeconds(50);
while (Comms.CommsSerialScan.foundport == false)
{
System.Threading.Thread.Sleep(100);
if (DateTime.Now > deadline)
{
CustomMessageBox.Show(Strings.Timeout);
_connectionControl.IsConnected(false);
return;
}
}
_connectionControl.CMB_serialport.Text = portname = Comms.CommsSerialScan.portinterface.PortName;
_connectionControl.CMB_baudrate.Text = baud = Comms.CommsSerialScan.portinterface.BaudRate.ToString();
}
log.Info("Set Portname");
// set port, then options
comPort.BaseStream.PortName = portname;
log.Info("Set Baudrate");
try
{
comPort.BaseStream.BaudRate = int.Parse(baud);
}
catch (Exception exp)
{
log.Error(exp);
}
// prevent serialreader from doing anything
comPort.giveComport = true;
log.Info("About to do dtr if needed");
// reset on connect logic.
if (config["CHK_resetapmonconnect"] == null || bool.Parse(config["CHK_resetapmonconnect"].ToString()) == true)
{