Subversion Repositories Projects

Rev

Rev 2333 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2287 - 1
using GMap.NET;
2
using GMap.NET.MapProviders;
3
using GMap.NET.WindowsPresentation;
4
using MKLiveView.GMapCustomMarkers;
5
using System;
6
using System.Collections.Generic;
7
using System.ComponentModel;
8
using System.Data;
9
using System.Diagnostics;
10
using System.IO;
11
using System.Linq;
12
using System.Linq.Expressions;
13
using System.Runtime.InteropServices;
14
using System.Text;
15
using System.Threading;
16
using System.Threading.Tasks;
17
using System.Windows;
18
using System.Windows.Controls;
19
using System.Windows.Data;
20
using System.Windows.Documents;
21
using System.Windows.Input;
22
using System.Windows.Interop;
23
using System.Windows.Media;
24
using System.Windows.Media.Animation;
25
using System.Windows.Media.Imaging;
26
using System.Windows.Navigation;
27
using System.Windows.Shapes;
28
using System.Windows.Threading;
2313 - 29
using System.Globalization;
2324 - 30
using System.Xml;
31
using System.Xml.Linq;
2287 - 32
 
33
namespace MKLiveView
34
{
35
    /// <summary>
36
    /// Interaktionslogik für MainWindow.xaml
37
    /// </summary>
38
    public partial class MainWindow : Window
39
    {
2304 - 40
        #region declarations
41
 
2287 - 42
        GMapMarker copter;
43
        GMapMarker home;
44
        PointLatLng start;
45
        PointLatLng end;
46
        PointLatLng pHome;
2328 - 47
        GMapRoute mRouteWP;
48
        List<PointLatLng> wpList = new List<PointLatLng>();
2324 - 49
        #region NC-Errors
2287 - 50
        String[] NC_Error = new string[44]
51
        {
52
            "No Error",
53
            "FC not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A1_.22FC_not_compatible_.22",
54
            "MK3Mag not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A2_.22MK3Mag_not_compatible_.22",
55
            "no FC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A3_.22no_FC_communication_.22",
56
            "no compass communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A4_.22no_compass_communication_.22",
57
            "no GPS communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A5_.22no_GPS_communication_.22",
58
            "bad compass value" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A6_.22bad_compass_value.22",
59
            "RC Signal lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A7_.22RC_Signal_lost_.22",
60
            "FC spi rx error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A8_.22FC_spi_rx_error_.22",
61
            "ERR: no NC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A9:_.22ERR:_no_NC_communication.22",
62
            "ERR: FC Nick Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A10_.22ERR:_FC_Nick_Gyro.22",
63
            "ERR: FC Roll Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A11_.22ERR:_FC_Roll_Gyro.22",
64
            "ERR: FC Yaw Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A12_.22ERR:_FC_Yaw_Gyro.22",
65
            "ERR: FC Nick ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A13_.22ERR:_FC_Nick_ACC.22",
66
            "ERR: FC Roll ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A14_.22ERR:_FC_Roll_ACC.22",
67
            "ERR: FC Z-ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A15_.22ERR:_FC_Z-ACC.22",
68
            "ERR: Pressure sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A16_.22ERR:_Pressure_sensor.22",
69
            "ERR: FC I2C" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A17_.22ERR:_FC_I2C.22",
70
            "ERR: Bl Missing" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A18_.22ERR:_Bl_Missing.22",
71
            "Mixer Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A19_.22Mixer_Error.22",
72
            "FC: Carefree Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A20_.22FC:_Carefree_Error.22",
73
            "ERR: GPS lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A21_.22ERR:_GPS_lost.22",
74
            "ERR: Magnet Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A22_.22ERR:_Magnet_Error.22",
75
            "Motor restart" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A23_.22Motor_restart.22",
76
            "BL Limitation" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A24_.22BL_Limitation.22",
77
            "Waypoint range" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A25_.22Waypoint_range.22",
78
            "ERR:No SD-Card" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A26_.22ERR:No_SD-Card.22",
79
            "ERR:SD Logging aborted" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A27_.22ERR:SD_Logging_aborted.22",
80
            "ERR:Flying range!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A28_.22ERR:Flying_range.21.22",
81
            "ERR:Max Altitude" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A29_.22ERR:Max_Altitude.22",
82
            "No GPS Fix" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A30_.22No_GPS_Fix.22",
83
            "compass not calibrated" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A31_.22compass_not_calibrated.22",
84
            "ERR:BL selftest" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A32_.22ERR:BL_selftest.22",
85
            "no ext. compass" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A33_.22no_ext._compass.22",
86
            "compass sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A34_.22compass_sensor.22",
87
            "FAILSAFE pos.!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A35_.22FAILSAFE_pos..21__.22",
88
            "ERR:Redundancy" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A36_.22ERR:Redundancy__.22",
89
            "Redundancy test" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A37_.22Redundancy_test_.22",
90
            "GPS Update rate" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A38_.22GPS_Update_rate.22",
91
            "ERR:Canbus" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A39_.22ERR:Canbus.22",
92
            "ERR: 5V RC-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A40_.22ERR:_5V_RC-Supply.22",
93
            "ERR:Power-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A41_.22ERR:Power-Supply.22",
94
            "ACC not calibr." + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A42_.22ACC_not_calibr..22",
95
            "ERR:Parachute!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A43_.22ERR:Parachute.21.22"
96
        };
2324 - 97
        #endregion NC-Errors
2287 - 98
        [FlagsAttribute]
99
        enum NC_HWError0 : short
100
        {
101
            None = 0,
102
            SPI_RX = 1,
103
            COMPASS_RX = 2,
104
            FC_INCOMPATIBLE = 4,
105
            COMPASS_INCOMPATIBLE = 8,
106
            GPS_RX = 16,
107
            COMPASS_VALUE = 32
108
        };
109
        [FlagsAttribute]
110
        enum FC_HWError0 : short
111
        {
112
            None = 0,
113
            GYRO_NICK = 1,
114
            GYRO_ROLL = 2,
115
            GYRO_YAW = 4,
116
            ACC_NICK = 8,
117
            ACC_ROLL = 16,
118
            ACC_TOP = 32,
119
            PRESSURE = 64,
120
            CAREFREE = 128
121
        };
122
        [FlagsAttribute]
123
        enum FC_HWError1 : short
124
        {
125
            None = 0,
126
            I2C = 1,
127
            BL_MISSING = 2,
128
            SPI_RX = 4,
129
            PPM = 8,
130
            MIXER = 16,
131
            RC_VOLTAGE = 32,
132
            ACC_NOT_CAL = 64,
133
            RES3 = 128
134
        };
135
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
136
        // Various colors for logging info
137
        private Color[] LogMsgTypeColor = { Color.FromArgb(255, 43, 145, 175), Colors.Green, Colors.Black, Colors.Orange, Colors.Red };
138
 
139
        bool _bCBInit = true;
140
        bool _init = true;
141
        bool check_HWError = false;
142
 
143
        string filePath = Directory.GetCurrentDirectory();
144
        bool bReadContinously = false;
145
        bool _debugDataAutorefresh = true;
146
        bool _navCtrlDataAutorefresh = true;
147
        bool _blctrlDataAutorefresh = true;
148
        bool _OSDAutorefresh = true;
149
        bool _bErrorLog = false;
150
        bool _bConnErr = false;
151
        bool _bFollowCopter = false;
2324 - 152
        bool _bGPXLog = false;
2287 - 153
 
154
        bool _bSaveWinStateNormal = true;
155
        bool _bSaveWinStateFull = true;
156
 
157
        double scaleNormalAll = 1;
158
        double scaleNormalTopBar = 1;
159
        double scaleNormalMotors = 1;
160
        double scaleNormalOSD = 1;
161
        double scaleNormalLOG = 1;
162
        double scaleNormalHorizon = 1;
163
 
164
        double scaleFullAll = 1;
165
        double scaleFullTopBar = 1;
166
        double scaleFullMotors = 1;
167
        double scaleFullOSD = 1;
168
        double scaleFullLOG = 1;
169
        double scaleFullHorizon = 1;
170
 
171
        int _iCtrlAct = 0;
172
        int iOSDPage = 0;
173
        int iOSDMax = 0;
174
        int _iLifeCounter = 0;
175
        int crcError = 0;
176
 
2291 - 177
        bool _bSatFix = false;
178
        Storyboard stbSatFixLostAnim;
179
        bool _bAnimSatFixActive = false;
180
        bool _bVoiceSatFixActive = false;
181
        bool _bVoiceSatFixPlay = false;
182
        int _iSatsLast = 0;
183
        int _iSatsJitter = 0;
184
 
185
        bool _bMagneticFieldOK = false;
186
        Storyboard stbMagneticFieldAnim;
187
        bool _bAnimMagneticFieldActive = false;
188
        bool _bVoiceMagneticFieldActive = false;
189
        bool _bVoiceMagneticFieldPlay = false;
190
        int _iMagneticFieldLast = 0;
191
        int _iMagneticFieldJitter = 0;
192
 
193
        bool _bRCLevelOK = false;
194
        Storyboard stbRCLevelAnim;
195
        bool _bAnimRCLevelActive = false;
196
        bool _bVoiceRCLevelActive = false;
197
        bool _bVoiceRCLevelPlay = false;
198
        int _iRCLevelLast = 0;
199
        int _iRCLevelJitter = 0;
200
 
2287 - 201
        int _iMotors = 4;
202
        int _LipoCells = 4;
203
 
204
        double _dLipoVMax = 16.88;
205
        double _dLipoVMin = 12;
206
        double _dThresholdVoltageWarn = 0;
207
        double _dThresholdVoltageCrit = 0;
208
        Storyboard stbVoltageCritAnim;
209
        bool _bCritAnimVoltActive = false;
210
        bool _bCritVoiceVoltActive = false;
2291 - 211
        bool _bWarnVoiceVoltActive = false;
2287 - 212
        bool _bVoiceVoltPlay = false;
213
        double _dVoltLast = 0;
214
        int _iVoltJitter = 0;
215
 
2291 - 216
        double _dThresholdDistanceWarn = 100;
217
        Storyboard stbDistanceWarnAnim;
218
        bool _bAnimDistanceActive = false;
219
        bool _bVoiceDistanceActive = false;
220
        bool _bVoiceDistancePlay = false;
221
        double _dDistanceLast = 0;
222
        int _iDistanceJitter = 0;
223
 
224
        double _dThresholdDistanceMax = 1000;
225
        int _iThresholdRC = 160;
226
        int _iThresholdMagField = 15;
227
 
2295 - 228
        bool _bAutoHome = false;
229
        bool _bFirstSatFix = false;
230
        int _iFirstSatFix = 0;
2291 - 231
 
2287 - 232
        double _dTopHeight = 36;
233
 
234
        int[] serChan = new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
235
        int[] serChan_sub = new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
236
        string[] serChanTitle = new string[12];
237
 
238
        string[] sAnalogLabel = new string[32];
239
        string[] sAnalogData = new string[32];
2324 - 240
        int[] iAnalogData = new int[32];
2287 - 241
 
242
        int[] iTimings = new int[] {100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900,2000 };
243
        int[] iMotors = new int[] {3,4,5,6,7,8,9,10,11,12 };
244
        string[] sLiPoCells = new string[] { "3s", "4s", "5s", "6s" };
245
        /// <summary>
246
        /// interval for sending debugdata (multiplied by 10ms)
247
        /// </summary>
248
        byte debugInterval = 10; //(=> 100ms)
249
        /// <summary>
250
        /// interval for sending BL-CTRL status (multiplied by 10ms)
251
        /// </summary>
252
        byte blctrlInterval = 75;
253
        /// <summary>
254
        /// interval for sending NAV-CTRL status (multiplied by 10ms)
255
        /// </summary>
256
        byte navctrlInterval = 80;
257
        /// <summary>
258
        /// interval for sending OSD page update (multiplied by 10ms)
259
        /// </summary>
260
        byte OSDInterval = 85;
261
        /// <summary>
262
        /// datatable for the debug data array - displayed on settings tabpage in datagridview
263
        /// </summary>
264
        DataTable dtAnalog = new DataTable();
265
        /// <summary>
266
        /// datatable for motordata (current,temp)
267
        /// </summary>
2315 - 268
        DataTable dtMotors = new DataTable();
2287 - 269
 
270
        DataTable dtWaypoints = new DataTable();
2313 - 271
        static volatile int _iWPCount = -1;
272
        static volatile int _iWPIndex = -1;
273
        int _iWPTimeout = 1000;
2287 - 274
        bool _bGetWP = false;
2328 - 275
        bool _bShowWPRoute = false;
2287 - 276
        static volatile bool _bGetWPCount = false;
2324 - 277
        DataTable dtGPX = new DataTable();
278
        DataRow drGPX;
279
        bool _bAirborne = false;
2287 - 280
        DispatcherTimer timer = new DispatcherTimer();
281
 
282
        /// <summary>
283
        /// stuff for enabeling touch zoom for the map
284
        /// </summary>
285
        Point pTouch1 = new Point(0,0), pTouch2 = new Point(0,0);
286
        int iFirstStylusID = -1;
287
        public string connectButtonText
288
        {
289
            get
290
            {
291
                return bReadContinously ? "stop polling data" + System.Environment.NewLine + "from copter" : "start polling data" + System.Environment.NewLine + "from copter";
292
            }
293
        }
294
 
295
        WinState winState = new WinState();
2304 - 296
        #endregion declarations
2287 - 297
        public MainWindow()
298
        {
299
            InitializeComponent();
300
            _initForm();
301
            _dataTablesInit();
302
            _setupMap();
303
            _init = false;
304
            timer.Tick += new EventHandler(timerEvent);
305
            timer.Interval = new TimeSpan(0, 0, 1);
306
            timer.Start();
307
        }
308
 
309
        #region init
310
        void _initForm()
311
        {
312
            _readIni();
313
            if (_bSaveWinStateNormal)
314
                _setScaleSliders(false);
315
            cBoxTimingsDebug.ItemsSource =
316
                cBoxTimingsNav.ItemsSource =
317
                cBoxTimingsBl.ItemsSource =
318
                cBoxTimingsOSD.ItemsSource =
319
                iTimings;
320
            cBoxLiPoCells.ItemsSource = sLiPoCells;
321
            cBoxLiPoCells.SelectedItem = _LipoCells.ToString() + "s";
322
            _LipoMinMax();
323
            sliderThresholdVoltageWarn.Value = _dThresholdVoltageWarn;
324
            sliderThresholdVoltageCrit.Value = _dThresholdVoltageCrit;
325
            checkBoxThresholdVoltageVoice.IsChecked = _bVoiceVoltPlay;
2291 - 326
            checkBoxSatfixLost.IsChecked = _bVoiceSatFixPlay;
327
            checkBoxMagneticField.IsChecked = _bVoiceMagneticFieldPlay;
328
            checkBoxThresholdDistanceVoice.IsChecked = _bVoiceDistancePlay;
329
            sliderThresholdDistanceWarn.Value = _dThresholdDistanceWarn;
330
            checkBoxRClevel.IsChecked = _bVoiceRCLevelPlay;
2287 - 331
 
2291 - 332
            sliderThresholdDistanceWarn.Maximum = _dThresholdDistanceMax;
333
 
2287 - 334
            cBoxMotors.ItemsSource = iMotors;
335
            cBoxMotors.SelectedItem = _iMotors;
336
 
337
            serialPortCtrl.PortClosed += serialPortCtrl_PortClosed;
338
            serialPortCtrl.PortOpened += serialPortCtrl_PortOpened;
339
            serialPortCtrl.DataReceived += processMessage;
340
 
341
            chkbAutoBL.IsChecked = _blctrlDataAutorefresh;
342
            chkbAutoDbg.IsChecked = _debugDataAutorefresh;
343
            chkbAutoNav.IsChecked = _navCtrlDataAutorefresh;
344
            chkbAutoOSD.IsChecked = _OSDAutorefresh;
345
 
346
            cBoxTimingsDebug.SelectedItem = debugInterval * 10;
347
            cBoxTimingsNav.SelectedItem = navctrlInterval * 10;
348
            cBoxTimingsBl.SelectedItem = blctrlInterval * 10;
349
            cBoxTimingsOSD.SelectedItem = OSDInterval * 10;
2295 - 350
            checkBoxAutoSetHP.IsChecked = _bAutoHome;
2287 - 351
            checkBoxFollowCopter.IsChecked = _bFollowCopter;
2324 - 352
            checkBoxGPXLog.IsChecked = _bGPXLog;
2328 - 353
            checkBoxShowWPRoute.IsChecked = _bShowWPRoute;
2287 - 354
 
355
        }
356
        /// <summary>
357
        /// initialize the datatables
358
        /// with columnnames etc
359
        /// </summary>
360
        void _dataTablesInit()
361
        {
2315 - 362
            dtMotors.Columns.Add("#");
2313 - 363
            if (Thread.CurrentThread.CurrentUICulture.Name == "de-DE")
2315 - 364
                dtMotors.Columns.Add("Strom");
2313 - 365
            else
2315 - 366
                dtMotors.Columns.Add("Current");
367
            dtMotors.Columns.Add("Temp");
368
            dgvMotors1.DataContext = dtMotors.DefaultView;
2287 - 369
            _initDTMotors();
370
 
371
            Setter setter = new Setter(ContentControl.PaddingProperty, new Thickness(5,0,5,0));
372
            Style style = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
373
            style.Setters.Add(setter);
374
            setter = new Setter(ContentControl.BackgroundProperty, new SolidColorBrush(Colors.Transparent));
375
            style.Setters.Add(setter);
376
            setter = new Setter(ContentControl.ForegroundProperty, new SolidColorBrush(Colors.White));
377
            style.Setters.Add(setter);
2313 - 378
 
379
            dtWaypoints.Columns.Add("Index",typeof(int));
2315 - 380
            dtWaypoints.Columns.Add("Type", typeof(int));
2313 - 381
            dtWaypoints.Columns.Add("Name",typeof(string));
2315 - 382
            dtWaypoints.Columns.Add("Latitude",typeof(double));
383
            dtWaypoints.Columns.Add("Longitude",typeof(double));
2313 - 384
            dtWaypoints.Columns.Add("Altitude",typeof(string));
385
            dtWaypoints.Columns.Add("Heading",typeof(string));
386
            dtWaypoints.Columns.Add("Speed",typeof(string));
387
            dtWaypoints.Columns.Add("ClimbRate",typeof(string));
388
            dtWaypoints.Columns.Add("Radius",typeof(string));
389
            dtWaypoints.Columns.Add("HoldTime",typeof(string));
390
            dtWaypoints.Columns.Add("AutoTrigger",typeof(string));
391
            dtWaypoints.Columns.Add("CamAngle",typeof(string));
392
            dtWaypoints.Columns.Add("Event",typeof(string));
393
            dtWaypoints.Columns.Add("Out1Timer",typeof(string));
394
            dtWaypoints.Columns.Add("Status",typeof(string));
395
            dtWaypoints.PrimaryKey = new DataColumn[] { dtWaypoints.Columns["Index"] };
396
            dgvWP.ItemsSource = dtWaypoints.DefaultView;
2287 - 397
            dgvWP.ColumnHeaderStyle = new Style();
398
            dgvWP.ColumnHeaderStyle = style;
2313 - 399
 
2324 - 400
            dtGPX.Columns.Add("Index",typeof(int));
401
            dtGPX.Columns.Add("Latitude",typeof(double));
402
            dtGPX.Columns.Add("Longitude",typeof(double));
403
            dtGPX.Columns.Add("Elevation",typeof(int));
404
            dtGPX.Columns.Add("Time",typeof(string));
405
            dtGPX.PrimaryKey = new DataColumn[] { dtGPX.Columns["Index"] };
406
            drGPX = dtGPX.NewRow();
2313 - 407
 
2287 - 408
        }
409
        /// <summary>
2315 - 410
        /// initialize the datatable dtMotors for motor values
2313 - 411
        /// DataGridView dgvMotors1 is bound to dtMotors1
2287 - 412
        /// </summary>
413
        void _initDTMotors()
414
        {
415
            for (int i = 0; i < 12; i++)
416
            {
2315 - 417
                if (dtMotors.Rows.Count < 12)
418
                    dtMotors.Rows.Add((i + 1).ToString(), "NA", "NA");
2287 - 419
                else
420
                {
2315 - 421
                    dtMotors.Rows[i].SetField(1, "NA");
422
                    dtMotors.Rows[i].SetField(2, "NA");
2287 - 423
                }
424
            }
425
        }
426
 
427
        #endregion init
428
 
429
        #region events
430
        private void serialPortCtrl_PortOpened()
431
        {
432
            Dispatcher.Invoke(() => imageWiFi.Source = new BitmapImage(new Uri("Images/WiFi_G.png", UriKind.Relative)));
433
            _getVersion();
434
            Thread.Sleep(100);
435
            //_OSDMenue(0);
436
            //Thread.Sleep(200);
437
            //_sendSerialData();
438
            _readCont(true);
439
        }
440
        private void serialPortCtrl_PortClosed()
441
        {
442
            Dispatcher.Invoke(() => imageWiFi.Source = new BitmapImage(new Uri("Images/WiFi_W.png", UriKind.Relative)));
443
            _readCont(false);
444
        }
2324 - 445
        bool _bToggle = false;
2287 - 446
        void timerEvent(object sender, EventArgs e)
447
        {
448
            if (bReadContinously)
449
            {
450
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
451
 
452
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
453
 
454
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
455
                check_HWError = true;
456
                _getVersion();
457
                Thread.Sleep(10);
458
                if (_OSDAutorefresh)
459
                {
460
                    if (iOSDMax == 0 | cbOSD.Items.Count != iOSDMax)
461
                        _initOSDCB();
462
                    _OSDMenueAutoRefresh();
463
                }
464
                if (_iLifeCounter > 0)
465
                {
466
                    Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_G.png", UriKind.Relative)));
467
                  //  Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.LightGreen));
468
                    _iLifeCounter = 0;
469
                    _bConnErr = false;
2327 - 470
                    if(_bAirborne && _bGPXLog)
2324 - 471
                    {
472
                        drGPX[0] = dtGPX.Rows.Count;
473
                        dtGPX.Rows.Add(new object[] { drGPX[0], drGPX[1], drGPX[2], drGPX[3], drGPX[4] });
474
                    }
2327 - 475
                    Dispatcher.Invoke((Action)(() => tbSideBarGPXLog.Background = (_bAirborne && _bGPXLog && _bToggle) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));
476
                    Dispatcher.Invoke((Action)(() => tbSideBarGPXLog.Foreground = (_bAirborne && _bGPXLog) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));
477
                    Dispatcher.Invoke((Action)(() => tbSideBarGPXLog.BorderBrush = (_bAirborne && _bGPXLog) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));
2324 - 478
                    _bToggle = !_bToggle;
2287 - 479
                }
480
                else
481
                {
482
                    if (!_bConnErr)
483
                    {
484
                        Log(LogMsgType.Error, "No communication to NC/FC!");
485
                        Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_R.png", UriKind.Relative)));
486
                       // Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.Red));
487
                        _bConnErr = true;
488
                    }
489
                }
490
            }
491
        }
492
 
493
        private void labelData_MouseDown(object sender, MouseButtonEventArgs e)
494
        {
495
            GridData.Visibility = GridData.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
496
            GridSettings.Visibility = GridWP.Visibility = Visibility.Collapsed;
497
        }
498
        private void labelMotorData_MouseDown(object sender, MouseButtonEventArgs e)
499
        {
500
            GridMotors.Visibility = GridMotors.Visibility == Visibility.Hidden ? Visibility.Visible : Visibility.Hidden;
501
            if (GridMotors.IsVisible)
502
                _setMotorGridSize();
503
        }
504
        private void labelSettings_MouseDown(object sender, MouseButtonEventArgs e)
505
        {
506
            GridData.Visibility = GridWP.Visibility = Visibility.Collapsed;
507
            GridSettings.Visibility = GridSettings.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
508
        }
509
        private void labelLog_MouseDown(object sender, MouseButtonEventArgs e)
510
        {
511
            GridLog.Visibility = GridLog.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
512
        }
513
        private void labelOSD_MouseDown(object sender, MouseButtonEventArgs e)
514
        {
515
            GridOSD.Visibility = GridOSD.Visibility == Visibility.Hidden ? Visibility.Visible : Visibility.Hidden;
516
        }
517
        private void labelWaypoints_MouseDown(object sender, MouseButtonEventArgs e)
518
        {
519
            GridData.Visibility = GridSettings.Visibility = Visibility.Collapsed;
520
            GridWP.Visibility = GridWP.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
521
        }
522
 
523
        private void btnGetWP_Click(object sender, RoutedEventArgs e)
524
        {
525
            Thread t = new Thread(new ThreadStart(_getWP));
526
            t.Start();
527
        }
528
        private void btnSendWPList_Click(object sender, RoutedEventArgs e)
529
        {
2313 - 530
            Thread t = new Thread(new ThreadStart(_sendWPList));
531
            t.Start();
2287 - 532
        }
533
 
534
        private void btnConnectToCopter_Click(object sender, RoutedEventArgs e)
535
        {
536
            if (!serialPortCtrl.Port.IsOpen)
537
                serialPortCtrl.Connect(true);
538
            else
539
                _readCont(!bReadContinously);
540
        }
541
        private void btnSetHP_Click(object sender, RoutedEventArgs e)
542
        {
543
            setHomePos();
544
        }
545
        private void btnClearHP_Click(object sender, RoutedEventArgs e)
546
        {
547
            clearHomePos();
548
        }
549
        private void btnGotoHP_Click(object sender, RoutedEventArgs e)
550
        {
551
            if (home != null && MainMap.Markers.Contains(home))
552
                MainMap.Position = home.Position;
553
        }
2295 - 554
        private void checkBoxAutoSetHP_Click(object sender, RoutedEventArgs e)
555
        {
556
            _bAutoHome = (bool)checkBoxAutoSetHP.IsChecked;
557
        }
2287 - 558
        private void chkBoxSaveNormalState_Click(object sender, RoutedEventArgs e)
559
        {
560
            _bSaveWinStateNormal = (bool)chkBoxSaveNormalState.IsChecked;
561
        }
562
        private void chkBoxSaveFullScreenState_Click(object sender, RoutedEventArgs e)
563
        {
564
            _bSaveWinStateFull = (bool)chkBoxSaveFullScreenState.IsChecked;
565
        }
566
 
2291 - 567
        #region thresholds
2287 - 568
        private void sliderThresholdVoltageWarn_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
569
        {
570
            if(!_init)
571
                _dThresholdVoltageWarn = sliderThresholdVoltageWarn.Value;
572
        }
573
        private void sliderThresholdVoltageCrit_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
574
        {
575
            if(!_init)
576
                _dThresholdVoltageCrit = sliderThresholdVoltageCrit.Value;
577
        }
578
        private void checkBoxThresholdVoltageVoice_Click(object sender, RoutedEventArgs e)
579
        {
580
            _bVoiceVoltPlay = (bool)checkBoxThresholdVoltageVoice.IsChecked;
581
        }
2291 - 582
 
583
        private void sliderThresholdDistanceWarn_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
584
        {
585
            if(!_init)
586
                _dThresholdDistanceWarn = sliderThresholdDistanceWarn.Value;
587
        }
588
        private void checkBoxThresholdDistanceVoice_Click(object sender, RoutedEventArgs e)
589
        {
590
            _bVoiceDistancePlay = (bool)checkBoxThresholdDistanceVoice.IsChecked;
591
        }
592
 
593
        private void checkBoxSatfixLost_Click(object sender, RoutedEventArgs e)
594
        {
595
            _bVoiceSatFixPlay = (bool)checkBoxSatfixLost.IsChecked;
596
        }
597
        private void checkBoxMagneticField_Click(object sender, RoutedEventArgs e)
598
        {
599
            _bVoiceMagneticFieldPlay = (bool)checkBoxMagneticField.IsChecked;
600
        }
601
        private void checkBoxRClevel_Click(object sender, RoutedEventArgs e)
602
        {
603
            _bVoiceRCLevelPlay = (bool)checkBoxRClevel.IsChecked;
604
        }
605
        #endregion thresholds
606
 
2287 - 607
        private void buttonSwitchNC_Click(object sender, RoutedEventArgs e)
608
        {
609
            _switchToNC();
610
        }
611
 
612
        private void Window_Loaded(object sender, RoutedEventArgs e)
613
        {
614
            stbVoltageCritAnim = TryFindResource("VoltageCritAnim") as Storyboard;
2291 - 615
            stbSatFixLostAnim = TryFindResource("SatFixLostAnim") as Storyboard;
616
            stbMagneticFieldAnim = TryFindResource("MagneticFieldCritAnim") as Storyboard;
617
            stbDistanceWarnAnim = TryFindResource("DistanceCritAnim") as Storyboard;
618
            stbRCLevelAnim = TryFindResource("RCCritAnim") as Storyboard;
2287 - 619
            _setMotorGridSize();
620
        }
2310 - 621
        private void Window_Closing(object sender, CancelEventArgs e)
622
        {
623
            _writeIni();
2324 - 624
            if(_bGPXLog && dtGPX.Rows.Count > 0)
625
                _saveGPXLog();
2310 - 626
        }
2287 - 627
        #endregion events
628
 
629
        #region GMap
630
 
631
        void _setupMap()
632
        {
633
            MainMap.Manager.Mode = AccessMode.ServerAndCache;
634
            MainMap.MapProvider = GMapProviders.BingHybridMap;
635
            MainMap.SetPositionByKeywords("Landshut");
636
            MainMap.MinZoom = 0;
637
            MainMap.MaxZoom = 24;
638
            MainMap.Zoom = 16;
639
            MainMap.ShowCenter = true;
640
            MainMap.ShowTileGridLines = false;
641
            sliderMapZoom.Value = 16;
642
            comboBoxMapType.ItemsSource = providerList;
643
            comboBoxMapType.DisplayMemberPath = "Name";
644
            comboBoxMapType.SelectedItem = MainMap.MapProvider;
645
 
646
            // acccess mode
647
            comboBoxMode.ItemsSource = Enum.GetValues(typeof(AccessMode));
648
            comboBoxMode.SelectedItem = MainMap.Manager.Mode;
649
 
650
        }
651
 
652
        /// <summary>
653
        /// selection of relevant map providers --> if You need more, You can change the line:
654
        ///     comboBoxMapType.ItemsSource = providerList; 
655
        /// to:
656
        ///     comboBoxMapType.ItemsSource = GMapProviders.List;
657
        /// in _setupMap()
658
        /// or add items here:
659
        /// </summary>
660
        List<GMap.NET.MapProviders.GMapProvider> providerList = new List<GMap.NET.MapProviders.GMapProvider>
661
        { GMap.NET.MapProviders.GMapProviders.OpenCycleMap, GMap.NET.MapProviders.GMapProviders.OpenCycleLandscapeMap, GMap.NET.MapProviders.GMapProviders.OpenCycleTransportMap,
662
        GMap.NET.MapProviders.GMapProviders.BingMap,GMap.NET.MapProviders.GMapProviders.BingSatelliteMap,GMap.NET.MapProviders.GMapProviders.BingHybridMap,
663
        GMap.NET.MapProviders.GMapProviders.GoogleMap,GMap.NET.MapProviders.GMapProviders.GoogleSatelliteMap,GMap.NET.MapProviders.GMapProviders.GoogleHybridMap,GMap.NET.MapProviders.GMapProviders.GoogleTerrainMap,
664
        GMap.NET.MapProviders.GMapProviders.OviMap,GMap.NET.MapProviders.GMapProviders.OviSatelliteMap,GMap.NET.MapProviders.GMapProviders.OviHybridMap,GMap.NET.MapProviders.GMapProviders.OviTerrainMap};
665
 
666
        private void MainMap_Loaded(object sender, RoutedEventArgs e)
667
        {
668
            MainMap.Manager.Mode = AccessMode.ServerAndCache;
669
            copter = new GMapMarker(MainMap.Position);
2318 - 670
 
671
            copter.Shape = new CustomMarkerCopter(this, copter, MainMap.Position.Lat.ToString("0.#######°") + System.Environment.NewLine + MainMap.Position.Lng.ToString("0.#######°"),"red");
672
            if (comboBoxCopterColor.SelectionBoxItem != null)
673
            {
674
                string s = comboBoxCopterColor.SelectionBoxItem.ToString();
675
                ((CustomMarkerCopter)(copter.Shape)).setColor(s);
676
            }
2287 - 677
            copter.Offset = new System.Windows.Point(-18, -18);
678
            copter.ZIndex = int.MaxValue;
679
            MainMap.Markers.Add(copter);
680
            copter.Position = MainMap.Position;
681
        }
682
        void setHomePos()
683
        {
684
            pHome = MainMap.Position;
685
            if (!MainMap.Markers.Contains(home))
686
            {
687
                home = new GMapMarker(MainMap.Position);
688
                home.Shape = new CustomMarkerHome(this, home, MainMap.Position.Lat.ToString("0.#######°") + System.Environment.NewLine + MainMap.Position.Lng.ToString("0.#######°"));
689
                home.Offset = new System.Windows.Point(-18, -18);
690
                // home.ZIndex = int.MaxValue;
691
                MainMap.Markers.Add(home);
692
            }
693
            home.Position = MainMap.Position;
694
            ((CustomMarkerHome)(home.Shape)).setText(MainMap.Position.Lat.ToString("0.#######°") + System.Environment.NewLine + MainMap.Position.Lng.ToString("0.#######°"));
695
        }
696
        void clearHomePos()
697
        {
698
            MainMap.Markers.Remove(home);
699
        }
2335 - 700
        void _clearMapMarkers(Type markerType)
701
        {
702
            for (int k = 0; k < MainMap.Markers.Count;)
703
            {
704
                GMapMarker p = MainMap.Markers[k];
705
                if (p.GetType() == markerType | p.Shape.GetType() == markerType)
706
                    MainMap.Markers.Remove(p);
707
                else
708
                    k++;
709
            }
2287 - 710
 
2335 - 711
        }
712
 
2287 - 713
        // access mode
714
        private void comboBoxMode_DropDownClosed(object sender, EventArgs e)
715
        {
716
            MainMap.Manager.Mode = (AccessMode)comboBoxMode.SelectedItem;
717
            MainMap.ReloadMap();
718
        }
719
        // zoom up
720
        private void czuZoomUp_Click(object sender, RoutedEventArgs e)
721
        {
722
            MainMap.Zoom = ((int)MainMap.Zoom) + 1;
723
        }
724
 
725
        // zoom down
726
        private void czuZoomDown_Click(object sender, RoutedEventArgs e)
727
        {
728
            MainMap.Zoom = ((int)(MainMap.Zoom + 0.99)) - 1;
729
        }
730
 
731
        // prefetch
732
        private void buttonPrefetch_Click(object sender, RoutedEventArgs e)
733
        {
734
            RectLatLng area = MainMap.SelectedArea;
735
            if (!area.IsEmpty)
736
            {
737
                for (int i = (int)MainMap.Zoom; i <= MainMap.MaxZoom; i++)
738
                {
739
                    MessageBoxResult res = MessageBox.Show("Ready ripp at Zoom = " + i + " ?", "GMap.NET", MessageBoxButton.YesNoCancel);
740
 
741
                    if (res == MessageBoxResult.Yes)
742
                    {
743
                        TilePrefetcher obj = new TilePrefetcher();
744
                        obj.Owner = this;
745
                        obj.ShowCompleteMessage = true;
746
                        obj.Start(area, i, MainMap.MapProvider, 100);
747
                    }
748
                    else if (res == MessageBoxResult.No)
749
                    {
750
                        continue;
751
                    }
752
                    else if (res == MessageBoxResult.Cancel)
753
                    {
754
                        break;
755
                    }
756
                }
757
            }
758
            else
759
            {
760
                MessageBox.Show("Select map area holding ALT", "GMap.NET", MessageBoxButton.OK, MessageBoxImage.Exclamation);
761
            }
762
        }
763
 
764
        // goto by geocoder
765
        private void buttonGeoCoding_Click(object sender, RoutedEventArgs e)
766
        {
767
            _goto_byGeoCoder();
768
        }
769
        // goto by geocoder
770
        private void textBoxGeo_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
771
        {
772
            if (e.Key == System.Windows.Input.Key.Enter)
773
                _goto_byGeoCoder();
774
        }
775
        void _goto_byGeoCoder()
776
        {
777
            GeoCoderStatusCode status = MainMap.SetPositionByKeywords(textBoxGeo.Text);
778
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
779
            {
780
                MessageBox.Show("Geocoder can't find: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButton.OK, MessageBoxImage.Exclamation);
781
            }
782
        }
783
        private void buttonGeoLoc_Click(object sender, RoutedEventArgs e)
784
        {
785
            try
786
            {
787
                double lat = double.Parse(textBoxLat.Text, System.Globalization.CultureInfo.InvariantCulture);
788
                double lng = double.Parse(textBoxLng.Text, System.Globalization.CultureInfo.InvariantCulture);
789
 
790
                MainMap.Position = new PointLatLng(lat, lng);
791
            }
792
            catch (Exception ex)
793
            {
794
                MessageBox.Show("incorrect coordinate format: " + ex.Message);
795
            }
796
 
797
        }
798
 
799
        private void ReloadMap_Click(object sender, RoutedEventArgs e)
800
        {
801
            MainMap.ReloadMap();
802
        }
803
 
804
        private void MainMap_OnPositionChanged(PointLatLng point)
805
        {
806
            if (_bFollowCopter)
807
                _setCopterData(MainMap.Position);
808
        }
809
 
810
        private void MainMap_OnMapZoomChanged()
811
        {
812
            if (_bFollowCopter)
813
                _setCopterData(MainMap.Position);
814
            if((int)sliderMapZoom.Value != MainMap.Zoom)
815
                sliderMapZoom.Value = MainMap.Zoom;
816
        }
817
 
818
        void _setCopterData(PointLatLng p)
819
        {
820
            Dispatcher.Invoke(() =>
821
            {
822
                copter.Position = p;
823
                ((CustomMarkerCopter)(copter.Shape)).setText(p.Lat.ToString("0.#######°") + System.Environment.NewLine + p.Lng.ToString("0.#######°"));
824
                textBoxLat_currentPos.Text = p.Lat.ToString() + "°";
825
                textBoxLng_currentPos.Text = p.Lng.ToString() + "°";
826
            });
827
            if (home != null && MainMap.Markers.Contains(home))
828
            {
829
                Dispatcher.Invoke(() => ArtHor.rotateHome = GMapProviders.EmptyProvider.Projection.GetBearing(copter.Position, home.Position));
830
                double d = GMapProviders.EmptyProvider.Projection.GetDistance(home.Position, copter.Position);
831
                Dispatcher.Invoke(() => tbTopDistanceHP.Text = (d * 1000).ToString("0.0 m"));
2291 - 832
 
833
                if(d*1000 < _dThresholdDistanceWarn)
834
                {
835
                    _iDistanceJitter = 0; _bVoiceDistanceActive = false;
836
                    if (stbDistanceWarnAnim != null && _bAnimDistanceActive)
837
                    {
838
                        Dispatcher.Invoke(() => stbDistanceWarnAnim.Stop());
839
                        _bAnimDistanceActive = false;
840
                    }
841
                }
842
                else
843
                {
844
                    if (_iDistanceJitter < 20)
845
                    { _iDistanceJitter++; }
846
                    if (_iDistanceJitter == 20)
847
                    {
848
                        if (stbDistanceWarnAnim != null && !_bAnimDistanceActive)
849
                        {
850
                            Dispatcher.Invoke(() => stbDistanceWarnAnim.Begin());
851
                            _bAnimDistanceActive = true;
852
                        }
853
                        if (_bVoiceDistancePlay && !_bVoiceDistanceActive)
854
                        {
2295 - 855
                            Thread t = new Thread(()=>_mediaPlayer("Voice\\Distance.mp3"));
856
                            t.Start();
2291 - 857
                            _bVoiceDistanceActive = true;
858
                        }
859
                        _iDistanceJitter++;
860
                    }
861
                }
2287 - 862
            }
863
        }
864
 
865
        private void checkBoxFollowCopter_Click(object sender, RoutedEventArgs e)
866
        {
867
            _bFollowCopter = (bool)checkBoxFollowCopter.IsChecked;
868
        }
869
 
870
        private void sliderMapZoom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
871
        {
872
            if (MainMap.Zoom != sliderMapZoom.Value)
873
                MainMap.Zoom = (int)sliderMapZoom.Value;
874
        }
875
        #region Touch zooming hackattack ;) 
876
        /// <summary>
877
        /// inspired by http://www.codeproject.com/Articles/692286/WPF-and-multi-touch
878
        /// </summary>
879
        bool bFirstAccess = true;
880
        double dDistance = 0;
881
        int iZoom;
882
        private void MainMap_StylusDown(object sender, StylusDownEventArgs e)
883
        {
884
            var id = e.StylusDevice.Id;
885
            e.StylusDevice.Capture(MainMap);
886
            if (iFirstStylusID == -1)
887
            {
888
                iFirstStylusID = id;
889
            }
890
            else
891
            {
892
 
893
                MainMap.CanDragMap = false;
894
            }
895
        }
896
        private void MainMap_StylusUp(object sender, StylusEventArgs e)
897
        {
898
            MainMap.ReleaseStylusCapture();
899
            iFirstStylusID = -1;
900
            bFirstAccess = true;
901
            MainMap.CanDragMap = true;
902
            iZoom = 0;
903
        }
904
        private void MainMap_StylusMove(object sender, StylusEventArgs e)
905
        {
906
            var id = e.StylusDevice.Id;
907
            var tp = e.GetPosition(MainMap);
908
 
909
            // This is the first Stylus point; just record its position. 
910
            if (id == iFirstStylusID)
911
            {
912
                pTouch1.X = tp.X;
913
                pTouch1.Y = tp.Y;
914
            }
915
            else
916
            if (iFirstStylusID > -1)
917
            {
918
                pTouch2.X = tp.X;
919
                pTouch2.Y = tp.Y;
920
                double distance = Point.Subtract(pTouch1, pTouch2).Length;
921
                if (!bFirstAccess)
922
                {
923
                    if (distance > dDistance)
924
                        iZoom++;
925
                    else
926
                        if (distance < dDistance)
927
                        iZoom--;
928
                }
929
                if (iZoom > 30)
930
                {
931
                    iZoom = 0;
932
                    Dispatcher.Invoke(() => sliderMapZoom.Value += 1);
933
                }
934
                if (iZoom < -30)
935
                {
936
                    iZoom = 0;
937
                    Dispatcher.Invoke(() => sliderMapZoom.Value -= 1);
938
                }
939
                dDistance = distance;
940
                bFirstAccess = false;
941
            }
942
        }
943
        #endregion Touch zooming hackattack ;)
944
 
945
        #endregion GMap
946
 
947
        #region settings
948
        private void cBoxTimingsDebug_DropDownClosed(object sender, EventArgs e)
949
        {
950
            if(! _bCBInit && cBoxTimingsDebug.SelectedIndex > -1)
951
                debugInterval = (byte)(Convert.ToInt16(cBoxTimingsDebug.SelectedItem) / 10);
952
        }
953
        private void cBoxTimingsNav_DropDownClosed(object sender, EventArgs e)
954
        {
955
            if(! _bCBInit && cBoxTimingsNav.SelectedIndex > -1)
956
                navctrlInterval = (byte)(Convert.ToInt16(cBoxTimingsNav.SelectedItem) / 10);
957
        }
958
        private void cBoxTimingsBl_DropDownClosed(object sender, EventArgs e)
959
        {
960
            if (!_bCBInit && cBoxTimingsBl.SelectedIndex > -1)
961
                blctrlInterval = (byte)(Convert.ToInt16(cBoxTimingsBl.SelectedItem) / 10);
962
        }
963
        private void cBoxTimingsOSD_DropDownClosed(object sender, EventArgs e)
964
        {
965
            if (!_bCBInit && cBoxTimingsOSD.SelectedIndex > -1)
966
                OSDInterval = (byte)(Convert.ToInt16(cBoxTimingsOSD.SelectedItem) / 10);
967
        }
968
        private void chkbAutoDbg_Click(object sender, RoutedEventArgs e)
969
        {
970
            if (!_init) _debugDataAutorefresh = (bool)chkbAutoDbg.IsChecked;
971
        }
972
        private void chkbAutoNav_Click(object sender, RoutedEventArgs e)
973
        {
974
            if (!_init) _navCtrlDataAutorefresh = (bool)chkbAutoNav.IsChecked;
975
        }
976
        private void chkbAutoBL_Click(object sender, RoutedEventArgs e)
977
        {
978
            if (!_init) _blctrlDataAutorefresh = (bool)chkbAutoBL.IsChecked;
979
        }
980
        private void chkbAutoOSD_Click(object sender, RoutedEventArgs e)
981
        {
982
            if (!_init) _OSDAutorefresh = (bool)chkbAutoOSD.IsChecked;
983
        }
984
 
985
        private void cBoxLiPoCells_DropDownClosed(object sender, EventArgs e)
986
        {
987
            if (cBoxLiPoCells.SelectedIndex > -1)
988
            {
989
                _LipoCells = cBoxLiPoCells.SelectedIndex + 3;
990
                _LipoMinMax();
991
            }
992
        }
993
        void _LipoMinMax()
994
        {
995
            _dLipoVMax = (double)(_LipoCells) * 4.22;
996
            _dLipoVMin = (double)_LipoCells * 3;
997
            pbTopVoltage.Maximum = _dLipoVMax;
998
            pbTopVoltage.Minimum = _dLipoVMin;
999
            sliderThresholdVoltageWarn.Maximum = _dLipoVMax;
1000
            sliderThresholdVoltageWarn.Minimum = _dLipoVMin;
1001
        }
1002
        private void cBoxMotors_DropDownClosed(object sender, EventArgs e)
1003
        {
1004
            if (cBoxMotors.SelectedIndex > -1)
1005
            {
1006
                _iMotors = cBoxMotors.SelectedIndex + 3;
1007
                Dispatcher.Invoke(() =>
1008
                {
1009
                    dgvMotors1.Height = (272 / 12.6) * (_iMotors + 1);  //272 / 12.6 --> Workaround, cause the headerheight = NaN...?
1010
                    GridMotors.Height = dgvMotors1.Height + 10;
1011
                });
1012
            }
1013
        }
1014
        void _setMotorGridSize()
1015
        {
1016
            if (dgvMotors1.Columns.Count > 2)
1017
            {
1018
                dgvMotors1.Columns[0].Width = 24;
1019
                dgvMotors1.Columns[1].Width = 50;
1020
                dgvMotors1.Columns[2].Width = 50;
1021
                dgvMotors1.Height = (272 / 12.6) * (_iMotors + 1);
1022
                GridMotors.Height = dgvMotors1.Height + 10;
1023
            }
1024
 
1025
        }
1026
        #endregion settings
1027
 
1028
        #region functions  
1029
 
1030
        #region logging      
1031
        /// <summary> Log data to the terminal window. </summary>
1032
        /// <param name="msgtype"> The type of message to be written. </param>
1033
        /// <param name="msg"> The string containing the message to be shown. </param>
1034
        private void Log(LogMsgType msgtype, string msg)
1035
        {
1036
            Dispatcher.Invoke(() =>
1037
            {
1038
               // rtfTerminal.CaretPosition = rtfTerminal.CaretPosition.DocumentEnd;
1039
               // rtfTerminal.Foreground = new SolidColorBrush(LogMsgTypeColor[(int)msgtype]);
1040
//                rtfTerminal.AppendText(msg + "\r");
1041
                TextRange tr = new TextRange(rtfTerminal.Document.ContentEnd,rtfTerminal.Document.ContentEnd);
1042
                tr.Text = msg;
1043
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(LogMsgTypeColor[(int)msgtype]));
1044
                rtfTerminal.AppendText("\r");
1045
                rtfTerminal.ScrollToEnd();
1046
            });
1047
        }
1048
        private void ErrorLog(LogMsgType msgtype, string msg)
1049
        {
1050
            Dispatcher.Invoke(() =>
1051
            {
1052
                TextRange tr = new TextRange(rtfError.Document.ContentEnd, rtfError.Document.ContentEnd);
1053
                tr.Text = msg;
1054
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(LogMsgTypeColor[(int)msgtype]));
1055
                rtfError.AppendText("\r");
1056
                rtfError.ScrollToEnd();
1057
 
1058
                _bErrorLog = true;
1059
            });
1060
        }
1061
        /// <summary>
1062
        /// Clear the line in the  errorlog window 
1063
        /// containing the error string when error has ceased
1064
        /// </summary>
1065
        /// <param name="s">substring of errrormessage</param>
1066
        void _clearErrorLog(string s)
1067
        {
1068
            Dispatcher.Invoke((Action)(() =>
1069
            {
1070
                TextRange searchRange = new TextRange(rtfError.Document.ContentStart, rtfError.Document.ContentEnd);
1071
                TextRange foundRange = FindTextInRange(searchRange, s);
1072
 
1073
                int iStart = searchRange.Text.IndexOf(s, StringComparison.OrdinalIgnoreCase);
1074
 
1075
 
1076
                if (iStart > -1)
1077
                {
1078
                    int iLength = 0;
1079
                    int iEnd = searchRange.Text.IndexOf('\r', iStart);
1080
                    if (iEnd > 0)
1081
                    {
1082
                        iLength = iEnd + 1;
1083
                        int iHttp = searchRange.Text.IndexOf("http", iEnd);
1084
                        if (iHttp == iLength)
1085
                        {
1086
                            int iEnd2 = searchRange.Text.IndexOf('\r', iLength);
1087
                            if (iEnd2 > iLength)
1088
                            {
1089
                                iLength = iEnd2 + 1;
1090
                              //  TextRange result = new TextRange(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), GetTextPositionAtOffset(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), iLength));
1091
 
1092
                                rtfError.Selection.Select(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), GetTextPositionAtOffset(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), iLength));
1093
                                rtfError.Selection.Text = string.Empty;
1094
                                if (rtfError.Document.ContentEnd.GetTextRunLength(LogicalDirection.Backward) < 2) _bErrorLog = false;
1095
                            }
1096
 
1097
                        }
1098
                        else
1099
                        {
1100
                            rtfError.Selection.Select(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), GetTextPositionAtOffset(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), iLength));
1101
                            rtfError.Selection.Text = string.Empty;
1102
                            if (rtfError.Document.ContentEnd.GetTextRunLength(LogicalDirection.Backward) < 2) _bErrorLog = false;
1103
                        }
1104
                    }
1105
                }
1106
            }));
1107
 
1108
        }
1109
        public TextRange FindTextInRange(TextRange searchRange, string searchText)
1110
        {
1111
            int offset = searchRange.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
1112
            if (offset < 0)
1113
                return null;  // Not found
1114
 
1115
            var start = GetTextPositionAtOffset(searchRange.Start, offset);
1116
            TextRange result = new TextRange(start, GetTextPositionAtOffset(start, searchText.Length));
1117
 
1118
            return result;
1119
        }
1120
        TextPointer GetTextPositionAtOffset(TextPointer position, int characterCount)
1121
        {
1122
            while (position != null)
1123
            {
1124
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
1125
                {
1126
                    int count = position.GetTextRunLength(LogicalDirection.Forward);
1127
                    if (characterCount <= count)
1128
                    {
1129
                        return position.GetPositionAtOffset(characterCount);
1130
                    }
1131
 
1132
                    characterCount -= count;
1133
                }
1134
 
1135
                TextPointer nextContextPosition = position.GetNextContextPosition(LogicalDirection.Forward);
1136
                if (nextContextPosition == null)
1137
                    return position;
1138
 
1139
                position = nextContextPosition;
1140
            }
1141
 
1142
            return position;
1143
        }
1144
        #endregion logging
1145
 
1146
        #region processing received data
1147
 
1148
        private void processMessage(byte[] message)
1149
        {
1150
            if (message.Length > 0)
1151
            {
1152
                _iLifeCounter++;
1153
                //Log(LogMsgType.Incoming, BitConverter.ToString(message));
1154
                //Log(LogMsgType.Incoming, message.Length.ToString());
1155
                string s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, message.Length));
1156
                char cmdID;
1157
                byte adr;
1158
                byte[] data;
1159
                byte[] tmp = null;
1160
                if (message[0] != '#')
1161
                {
1162
                    int iFound = -1;
1163
                    for (int i = 0; i < message.Length; i++)   //Sometimes the FC/NC sends strings without termination (like WP messages)
1164
                    {                                   //so this is a workaround to not spam the log box
1165
                        if (message[i] == 35)
1166
                        {
1167
                            iFound = i;
1168
                            break;
1169
                        }
1170
                    }
1171
                    if (iFound > 0)
1172
                    {
1173
                        s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, iFound));
1174
                        tmp = new byte[message.Length - iFound];
1175
                        Buffer.BlockCopy(message, iFound, tmp, 0, message.Length - iFound);
1176
                    }
1177
                    s = s.Trim('\0', '\n', '\r');
1178
                    if (s.Length > 0)
1179
                        Log(LogMsgType.Normal, s);
1180
                    if (tmp != null)
1181
                    {
1182
                        s = new string(ASCIIEncoding.ASCII.GetChars(tmp, 0, tmp.Length));
1183
                        processMessage(tmp);
1184
                    }
1185
                }
1186
                //Debug.Print(s);
1187
                else
1188
                {
1189
                    FlightControllerMessage.ParseMessage(message, out cmdID, out adr, out data);
1190
 
1191
                    if (adr == 255) { crcError++; }
1192
                    else crcError = 0;
1193
                    Dispatcher.Invoke(() => tbCrc.Text = crcError.ToString());
1194
                    //display the active controller (FC / NC) 
1195
                    if (adr > 0 && adr < 3 && adr != _iCtrlAct) //adr < 3: temporary workaround cause when I've connected the FC alone it always switches between mk3mag & FC every second...???
1196
                    {
1197
                        _iCtrlAct = adr;
1198
                        switch (adr)
1199
                        {
1200
                            case 1:
1201
                                Dispatcher.Invoke(() => tbCtrl.Text = "FC");
2298 - 1202
                                Dispatcher.Invoke(() => buttonSwitchNC.Visibility = Visibility.Visible);
2287 - 1203
                                //Dispatcher.Invoke(() => labelSwitchToNavi.Visibility = Visibility.Visible);
1204
                              //  _setFieldsNA(); //display fields NA for FC 
1205
                                break;
1206
                            case 2:
1207
                                Dispatcher.Invoke(() => tbCtrl.Text = "NC");
1208
                                //Dispatcher.Invoke(() => buttonSwitchNC.Visibility = Visibility.Hidden);
1209
                                //Dispatcher.Invoke(() => labelSwitchToNavi.Visibility = Visibility.Hidden);
1210
                                break;
1211
                            //case 3:
1212
                            //    lblCtrl.Invoke((Action)(() => lblCtrl.Text = "MK3MAG"));
1213
                            //    break;
1214
                            //case 4:
1215
                            //    lblCtrl.Invoke((Action)(() => lblCtrl.Text = "BL-CTRL"));
1216
                            //    break;
1217
                            default:
1218
                                Dispatcher.Invoke(() => tbCtrl.Text = "NA");
1219
                                break;
1220
                        }
1221
                       // _loadLabelNames();
1222
                    }
1223
                    // else
1224
                    //     Debug.Print("Address == 0?");
1225
 
1226
                    if (data != null && data.Length > 0)
1227
                    {
1228
                        s = new string(ASCIIEncoding.ASCII.GetChars(data, 1, data.Length - 1));
1229
                        s = s.Trim('\0', '\n');
1230
 
1231
                        switch (cmdID)
1232
                        {
1233
                            //case 'A': //Label names
1234
                            //    _processLabelNames(s);
1235
                            //    break;
1236
 
1237
                            case 'D': //Debug data
1238
                                _processDebugVals(adr, data);
1239
                                break;
1240
 
1241
                            case 'V': //Version
1242
                                _processVersion(adr, data);
1243
                                break;
1244
 
1245
                            case 'K'://BL-CTRL data
1246
                                _processBLCtrl(data);
1247
                                break;
1248
 
1249
                            case 'O': //NC Data
1250
                                _processNCData(data);
1251
                                break;
1252
 
1253
                            case 'E': //NC error-string
1254
                                ErrorLog(LogMsgType.Error, "NC Error: " + s);
1255
                                break;
1256
 
1257
                            case 'L': //OSD Menue (called by pagenumber)
1258
                                _processOSDSingle(data);
1259
                                break;
1260
 
1261
                            case 'H': //OSD Menue (with autoupdate - called by Key)
1262
                                _processOSDAuto(data);
1263
                                break;
1264
 
1265
                            case 'X': //Waypoint data
1266
                                _processWPData(data);
1267
                                break;
1268
 
2313 - 1269
                            case 'W': //return new Waypoint items count after sending waypoint to copter
1270
                                _iWPCount = data[0];
1271
                                break;
2287 - 1272
                                //default:
1273
                                //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
1274
                                //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
1275
                                //    break;
1276
                        }
1277
                    }
1278
                    //else
1279
                    //{
1280
                    //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
1281
                    //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
1282
                    //}
1283
                }
1284
            }
1285
        }
1286
        /// <summary>
1287
        /// Analog label names 'A'
1288
        /// each label name is returned as a single string 
1289
        /// and added to string array sAnalogLabel[]
1290
        /// and the datatable dtAnalog
1291
        /// </summary>
1292
        /// <param name="s">the label name</param>
1293
        void _processLabelNames(string s)
1294
        {
1295
            //if (iLableIndex < 32)
1296
            //{
1297
            //    sAnalogLabel[iLableIndex] = s;
1298
            //    if (dtAnalog.Rows.Count < 32)
1299
            //        dtAnalog.Rows.Add(s, "");
1300
            //    else
1301
            //        dtAnalog.Rows[iLableIndex].SetField(0, s);
1302
 
1303
            //  //  _getAnalogLabels(iLableIndex + 1);
1304
            //}
1305
            //Debug.Print(s);
1306
        }
1307
        /// <summary>
1308
        /// Debug values 'D'
1309
        /// </summary>
1310
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
1311
        /// <param name="data">the received byte array to process</param>
1312
        void _processDebugVals(byte adr, byte[] data)
1313
        {
1314
            if (data.Length == 66)
1315
            {
2324 - 1316
 
2287 - 1317
                double v;
1318
                int index = 0;
1319
                Int16 i16 = 0;
1320
                double dTemp = 0;
1321
                for (int i = 2; i < 66; i += 2)
1322
                {
1323
                    i16 = data[i + 1];
1324
                    i16 = (Int16)(i16 << 8);
1325
                    iAnalogData[index] = data[i] + i16;
1326
                    sAnalogData[index] = (data[i] + i16).ToString();
1327
                   // dtAnalog.Rows[index].SetField(1, sAnalogData[index]);
1328
 
1329
                    if (adr == 2) //NC
1330
                    {
1331
                        switch (index)
1332
                        {
1333
                            case 0: //pitch (German: nick)
1334
                                Dispatcher.Invoke(() => ArtHor.Pitch = ((double)iAnalogData[index] / (double)10));
1335
                                Dispatcher.Invoke((Action)(() => tbPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
1336
                                break;
1337
                            case 1: //roll
1338
                                Dispatcher.Invoke(() => ArtHor.Roll = ((double)iAnalogData[index] / (double)10));
1339
                                Dispatcher.Invoke((Action)(() => tbRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
1340
                                break;
1341
                            case 4: //altitude
1342
                                Dispatcher.Invoke(() => tbAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m"));
1343
                                Dispatcher.Invoke(() => tbTopHeight.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m"));
2324 - 1344
                                Dispatcher.Invoke(() => { drGPX[3] = (double)iAnalogData[index] / (double)10; });
2287 - 1345
                                break;
1346
                            case 7: //Voltage
1347
                                v = (double)iAnalogData[index] / (double)10;
1348
                                Dispatcher.Invoke(() => tbVolt.Text = v.ToString("0.0 V"));
1349
                                Dispatcher.Invoke(() => tbTopVoltage.Text = v.ToString("0.0 V"));
1350
                                Dispatcher.Invoke(() => pbTopVoltage.Value = v);
1351
                                if (v - _dLipoVMin < 1 | v < _dThresholdVoltageWarn)
1352
                                {
1353
                                    if (v == _dVoltLast)
1354
                                        if(_iVoltJitter < 20) _iVoltJitter++;
1355
                                    else
1356
                                    {
1357
                                        _iVoltJitter = 0;
1358
                                        _dVoltLast = v;
1359
                                    }
1360
                                    if (_iVoltJitter == 20)
1361
                                    {
1362
                                        Dispatcher.Invoke(() => pbTopVoltage.Foreground = Brushes.Orange);
1363
 
1364
                                        if (v - _dLipoVMin < 1 | v < _dThresholdVoltageCrit)
1365
                                        {
1366
                                            Dispatcher.Invoke(() => pbTopVoltage.Foreground = Brushes.Red);
1367
                                            if (stbVoltageCritAnim != null && !_bCritAnimVoltActive)
1368
                                            {
1369
                                                Dispatcher.Invoke(() => stbVoltageCritAnim.Begin());
1370
                                                _bCritAnimVoltActive = true;
1371
                                            }
1372
                                            if (_bVoiceVoltPlay && !_bCritVoiceVoltActive)
1373
                                            {
2295 - 1374
                                                Thread t = new Thread(() => _mediaPlayer("Voice\\CriticalBattery.mp3"));
1375
                                                t.Start();
2287 - 1376
                                                _bCritVoiceVoltActive = true;
1377
                                            }
1378
                                        }
1379
                                        else
1380
                                        {
1381
                                            if (stbVoltageCritAnim != null && _bCritAnimVoltActive)
1382
                                            {
1383
                                                Dispatcher.Invoke(() => stbVoltageCritAnim.Stop());
1384
                                                _bCritAnimVoltActive = false;
1385
                                            }
1386
                                            _bCritVoiceVoltActive = false;
1387
 
2291 - 1388
                                            if (_bVoiceVoltPlay && !_bWarnVoiceVoltActive)
2287 - 1389
                                            {
2295 - 1390
                                                Thread t = new Thread(() => _mediaPlayer("Voice\\LowBattery.mp3"));
1391
                                                t.Start();
2291 - 1392
                                                _bWarnVoiceVoltActive = true;
2287 - 1393
                                            }
1394
                                        }
1395
                                    }
1396
                                }
1397
                                else
1398
                                {
1399
                                    Dispatcher.Invoke(() => pbTopVoltage.Foreground = new SolidColorBrush(Color.FromArgb(255, 107, 195, 123)));
1400
                                    if (stbVoltageCritAnim != null && _bCritAnimVoltActive)
1401
                                    {
1402
                                        Dispatcher.Invoke(() => stbVoltageCritAnim.Stop());
1403
                                        _bCritAnimVoltActive = false;
1404
                                    }
1405
                                    _bCritVoiceVoltActive = false;
2291 - 1406
                                    _bWarnVoiceVoltActive = false;
2287 - 1407
                                    _iVoltJitter = 0;
1408
                                }
1409
                                break;
1410
                            case 8: // Current
1411
                                Dispatcher.Invoke(() => tbCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A"));
1412
                                Dispatcher.Invoke(() => tbTopCurrent.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A"));
1413
                                break;
1414
                            case 10: //heading
2291 - 1415
                                Dispatcher.Invoke((Action)(() => tbHeading.Text = sAnalogData[index] + "°"));
2287 - 1416
                                Dispatcher.Invoke(() => ArtHor.rotate = iAnalogData[index]);
1417
                                break;
1418
                            case 12: // SPI error
2291 - 1419
                                Dispatcher.Invoke((Action)(() => tbSPI.Text = sAnalogData[index]));
2287 - 1420
                                break;
1421
                            case 14: //i2c error
2291 - 1422
                                Dispatcher.Invoke((Action)(() => tbI2C.Text = sAnalogData[index]));
2287 - 1423
                                break;
1424
                            case 20: //Earthmagnet field
2291 - 1425
                                Dispatcher.Invoke((Action)(() => tbMagF.Text = sAnalogData[index] + "%"));
1426
                                Dispatcher.Invoke((Action)(() => tbTopEarthMag.Text = sAnalogData[index] + "%"));
1427
 
1428
                                if (Math.Abs(100 - iAnalogData[index]) < _iThresholdMagField)
1429
                                {
1430
                                    Dispatcher.Invoke(() => imageEarthMag.Source = new BitmapImage(new Uri("Images/EarthMag.png", UriKind.Relative)));
1431
                                    _iMagneticFieldJitter = 0; _bVoiceMagneticFieldActive = false;
1432
                                    if (stbMagneticFieldAnim != null && _bAnimMagneticFieldActive)
1433
                                    {
1434
                                        Dispatcher.Invoke(() => stbMagneticFieldAnim.Stop());
1435
                                        _bAnimMagneticFieldActive = false;
1436
                                    }
1437
                                }
1438
                                else
1439
                                {
1440
                                    Dispatcher.Invoke(() => imageEarthMag.Source = new BitmapImage(new Uri("Images/EarthMag_R.png", UriKind.Relative)));
1441
                                    if(_iMagneticFieldLast >= Math.Abs(100 - iAnalogData[index]))
1442
                                    {
1443
                                        if (_iMagneticFieldJitter < 20)
1444
                                            _iMagneticFieldJitter++;
1445
                                    }
1446
                                    else
1447
                                    {
1448
                                        _iMagneticFieldJitter = 0;
1449
                                        _iMagneticFieldLast = Math.Abs(100 - iAnalogData[index]);
1450
                                    }
1451
                                    if(_iMagneticFieldJitter == 20)
1452
                                    {
1453
                                        if (stbMagneticFieldAnim != null && !_bAnimMagneticFieldActive)
1454
                                        {
1455
                                            Dispatcher.Invoke(() => stbMagneticFieldAnim.Begin());
1456
                                            _bAnimMagneticFieldActive = true;
1457
                                        }
1458
                                        if (_bVoiceMagneticFieldPlay && !_bVoiceMagneticFieldActive)
1459
                                        {
2295 - 1460
                                            Thread t = new Thread(() => _mediaPlayer("Voice\\MagneticField.mp3"));
1461
                                            t.Start();
2291 - 1462
                                            _bVoiceMagneticFieldActive = true;
1463
                                        }
1464
                                    }
1465
                                }
2287 - 1466
                                break;
1467
                            case 21: //GroundSpeed
1468
                                     Dispatcher.Invoke((Action)(() => tbSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
1469
                                     Dispatcher.Invoke((Action)(() => tbTopSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
1470
                                break;
2291 - 1471
 
1472
                            ///**********   needs testing --> not sure what position this is  ***************
2287 - 1473
                            case 28: //Distance East from saved home position -> calculate distance with distance N + height
1474
                                    dTemp = Math.Pow((double)iAnalogData[index], 2) + Math.Pow((double)iAnalogData[index - 1], 2);
1475
                                    dTemp = Math.Sqrt(dTemp) / (double)10; //'flat' distance from HP with N/E
1476
                                                                           //  lblNCDist.Invoke((Action)(() => lblNCDist.Text = dTemp.ToString("0.00")));
1477
                                    dTemp = Math.Pow(dTemp, 2) + Math.Pow(((double)iAnalogData[4] / (double)10), 2); //adding 'height' into calculation
1478
                                    dTemp = Math.Sqrt(dTemp) / (double)10;
1479
                               //     Dispatcher.Invoke((Action)(() => tbTopDistanceHP.Text = dTemp.ToString("0.0 m")));
1480
                                    Dispatcher.Invoke((Action)(() => tbHP1.Text = dTemp.ToString("0.0 m")));
1481
                                break;
2291 - 1482
 
2287 - 1483
                            case 31: //Sats used
1484
                                     Dispatcher.Invoke((Action)(() => tbSats.Text = sAnalogData[index]));
1485
                                    // Dispatcher.Invoke((Action)(() => tbTopSats.Text = sAnalogData[index]));                                   
1486
                                break;
1487
                        }
1488
                    }
1489
                    index++;
1490
                }
1491
            }
1492
            else
1493
                Debug.Print("wrong data-length (66): " + data.Length.ToString());
1494
        }
1495
        /// <summary>
1496
        /// Version string 'V'
1497
        /// </summary>
1498
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
1499
        /// <param name="data">the received byte array to process</param>
1500
        void _processVersion(byte adr, byte[] data)
1501
        {
1502
            if (data.Length == 12)
1503
            {
1504
                if (!check_HWError)
1505
                {
1506
                    string[] sVersionStruct = new string[10] { "SWMajor: ", "SWMinor: ", "ProtoMajor: ", "LabelTextCRC: ", "SWPatch: ", "HardwareError 1: ", "HardwareError 2: ", "HWMajor: ", "BL_Firmware: ", "Flags: " };
1507
                    string sVersion = "";
1508
                    //sbyte[] signed = Array.ConvertAll(data, b => unchecked((sbyte)b));
1509
                    Log(LogMsgType.Warning, (adr == 1 ? "FC-" : "NC-") + "Version: ");
1510
                    sVersion = "HW V" + (data[7] / 10).ToString() + "." + (data[7] % 10).ToString();
1511
                    Log(LogMsgType.Incoming, sVersion);
1512
                    sVersion = "SW V" + (data[0]).ToString() + "." + (data[1]).ToString() + ((char)(data[4] + 'a')).ToString();
1513
                    Log(LogMsgType.Incoming, sVersion);
1514
                    Log(LogMsgType.Incoming, "BL-Firmware: V" + (data[8] / 100).ToString() + "." + (data[8] % 100).ToString());
1515
                }
1516
                if (data[5] > 0) //error0 
1517
                {
1518
                    if (adr == 1)
1519
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[5].ToString() + ": " + ((FC_HWError0)data[5]).ToString());
1520
                    if (adr == 2)
1521
                        ErrorLog(LogMsgType.Error, "NC - HW-Error " + data[5].ToString() + ": " + ((NC_HWError0)data[5]).ToString());
1522
                }
1523
                if (data[6] > 0) //error1 
1524
                {
1525
                    if (adr == 1)
1526
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[6].ToString() + ": " + ((FC_HWError1)data[6]).ToString());
1527
                    if (adr == 2)
1528
                        ErrorLog(LogMsgType.Error, "NC - Unknown HW-ERROR: " + data[6].ToString()); //@moment NC has only one error field
1529
                }
1530
                if ((data[5] + data[6] == 0) && _bErrorLog)
1531
                    _clearErrorLog(adr == 1 ? "FC - HW-Error" : "NC - HW-Error");
1532
 
1533
            }
1534
            check_HWError = false;
1535
        }
1536
        /// <summary>
1537
        /// BL-Ctrl data 'K'
1538
        /// for FC you have to use a customized firmware
1539
        /// </summary>
1540
        /// <param name="data">the received byte array to process</param>
1541
        void _processBLCtrl(byte[] data)
1542
        {
1543
            if (data.Length % 6 == 0) //data.Length up to 96 (16 motors x 6 byte data) --> new datastruct in FC -> not standard!
1544
            {
1545
                bool bAvailable = false;
1546
                for (int i = 0; i < data.Length && data[i] < _iMotors; i += 6) // data[i] < _iMotors -- only show set number of motors (12 max @ moment)
1547
                {
1548
 
1549
                    if ((data[i + 4] & 128) == 128) //Status bit at pos 7 = 128 dec -- if true, motor is available
1550
                        bAvailable = true;
1551
                    else
1552
                        bAvailable = false;
1553
 
1554
                    if (data[i] < _iMotors)
1555
                    {
1556
                        if (bAvailable)
1557
                        {
2315 - 1558
                            dtMotors.Rows[data[i]].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
1559
                            dtMotors.Rows[data[i]].SetField(2, data[i + 2].ToString("0 °C"));
2287 - 1560
                        }
1561
                        else
1562
                        {
2315 - 1563
                            dtMotors.Rows[data[i]].SetField(1, "NA");
1564
                            dtMotors.Rows[data[i]].SetField(2, "NA");
2287 - 1565
                        }
1566
                    }
1567
                    //if (data[i] > 3 && data[i] < 8)
1568
                    //{
1569
                    //    if (bAvailable)
1570
                    //    {
1571
                    //        dtMotors2.Rows[data[i] - 4].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
1572
                    //        dtMotors2.Rows[data[i] - 4].SetField(2, data[i + 2].ToString("0 °C"));
1573
                    //    }
1574
                    //    else
1575
                    //    {
1576
                    //        dtMotors2.Rows[data[i] - 4].SetField(1, "NA");
1577
                    //        dtMotors2.Rows[data[i] - 4].SetField(2, "NA");
1578
                    //    }
1579
                    //}
1580
                }
1581
            }
1582
        }
1583
        /// <summary>
1584
        /// Navi-Ctrl data 'O'
1585
        /// GPS-Position, capacatiy, flying time...
1586
        /// </summary>
1587
        /// <param name="data">the received byte array to process</param>
1588
        void _processNCData(byte[] data)
1589
        {
1590
            int i_32, i_16, iVal;
1591
            double d;
1592
            i_32 = data[4];
1593
            iVal = i_32 << 24;
1594
            i_32 = data[3];
1595
            iVal += i_32 << 16;
1596
            i_32 = data[2];
1597
            iVal += i_32 << 8;
1598
            iVal += data[1];
1599
            d = (double)iVal / Math.Pow(10, 7);
2324 - 1600
            Dispatcher.Invoke(() => { drGPX[2] = d; });
1601
 
2287 - 1602
            PointLatLng p = new PointLatLng();
1603
 
1604
            p.Lng = d;
1605
          //  lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = d.ToString("0.######°"))); //GPS-Position: Longitude in decimal degree
1606
            //lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = _convertDegree(d))); //GPS-Position: Longitude in minutes, seconds
1607
 
1608
            i_32 = data[8];
1609
            iVal = i_32 << 24;
1610
            i_32 = data[7];
1611
            iVal += i_32 << 16;
1612
            i_32 = data[6];
1613
            iVal += i_32 << 8;
1614
            iVal += data[5];
1615
            d = (double)iVal / Math.Pow(10, 7);
2324 - 1616
            Dispatcher.Invoke(() => { drGPX[1] = d; });
1617
            Dispatcher.Invoke(() => { drGPX[4] = DateTime.UtcNow.ToString("u", System.Globalization.CultureInfo.InvariantCulture); }); //2011-01-14T01:59:01Z });
2287 - 1618
            p.Lat = d;
2291 - 1619
            if (data[50] > 4)//if more than 4 sats in use . otherwise the map would jump and scroll insane at beginning
1620
            {
1621
                _bSatFix = true; _iSatsJitter = 0; _bVoiceSatFixActive = false;
2295 - 1622
                if(_bAutoHome && !_bFirstSatFix)
1623
                {
1624
                    if (_iFirstSatFix < 3)
1625
                        _iFirstSatFix++;
1626
                    else
1627
                    {
1628
                        _bFirstSatFix = true;
1629
                        Dispatcher.Invoke(() => setHomePos());
1630
                    }
1631
                }
2291 - 1632
                if (stbSatFixLostAnim != null && _bAnimSatFixActive)
1633
                {
1634
                    Dispatcher.Invoke(() => stbSatFixLostAnim.Stop());
1635
                    _bAnimSatFixActive = false;
1636
                }
1637
                if (!_bFollowCopter)
1638
                {
1639
                    _setCopterData(p);
1640
                    if (!MainMap.ViewArea.Contains(p))
1641
                        Dispatcher.Invoke(() => MainMap.Position = p);
2287 - 1642
 
2291 - 1643
                }
1644
                else
2287 - 1645
                    Dispatcher.Invoke(() => MainMap.Position = p);
1646
            }
1647
            else
2291 - 1648
            {
1649
                if(_bSatFix)
1650
                {
1651
                    if (data[50] == _iSatsLast)
1652
                    {
1653
                        if (_iSatsJitter < 20) _iSatsJitter++;
1654
                    }
1655
                    else
1656
                    {
1657
                        _iSatsJitter = 0;
1658
                        _iSatsLast = data[50];
1659
                    }
2287 - 1660
 
2291 - 1661
                    if (_iSatsJitter == 20)
1662
                    {
1663
                        if (stbSatFixLostAnim != null && !_bAnimSatFixActive)
1664
                        {
1665
                            Dispatcher.Invoke(() => stbSatFixLostAnim.Begin());
1666
                            _bAnimSatFixActive = true;
1667
                        }
1668
                        if (_bVoiceSatFixPlay && !_bVoiceSatFixActive)
1669
                        {
2335 - 1670
                            Thread th = new Thread(() => _mediaPlayer("Voice\\SatFixLost.mp3"));
2295 - 1671
                            th.Start();
2291 - 1672
                            _bVoiceSatFixActive = true;
1673
                        }
1674
 
1675
                        _bSatFix = false;
1676
                    }
1677
                }
1678
            }
1679
 
2287 - 1680
            //  lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = d.ToString("0.######°"))); //GPS-Position: Latitude in decimal degree
1681
            //lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = _convertDegree(d))); //GPS-Position: Latitude in minutes, seconds
1682
 
1683
            i_16 = data[28];
1684
            i_16 = (Int16)(i_16 << 8);
1685
            iVal = data[27] + i_16;
1686
            Dispatcher.Invoke((Action)(() => tbWP.Text = ((double)iVal / (double)10).ToString("0.0 m"))); //Distance to next WP
1687
 
1688
            i_16 = data[45];
1689
            i_16 = (Int16)(i_16 << 8);
1690
            iVal = data[44] + i_16;
1691
        //    Dispatcher.Invoke((Action)(() => tbTopDistanceHP.Text = ((double)iVal / (double)10).ToString("0.0 m"))); //Distance to HP set by GPS on
1692
            Dispatcher.Invoke((Action)(() => tbHP.Text = ((double)iVal / (double)10).ToString("0.0 m"))); //Distance to HP set by GPS on
1693
 
1694
            Dispatcher.Invoke((Action)(() => tbWPIndex.Text = data[48].ToString())); //Waypoint index
1695
            Dispatcher.Invoke((Action)(() => tbWPCount.Text = data[49].ToString())); //Waypoints count
1696
 
1697
            Dispatcher.Invoke((Action)(() => tbTopSats.Text = data[50].ToString())); //Satellites
1698
 
1699
 
1700
            //--------------- Capacity used ------------------------
1701
            i_16 = data[81];
1702
            i_16 = (Int16)(i_16 << 8);
1703
            iVal = data[80] + i_16;
1704
            Dispatcher.Invoke((Action)(() => tbCapacity.Text = iVal.ToString() + " mAh"));
1705
            Dispatcher.Invoke((Action)(() => tbTopCapacity.Text = iVal.ToString() + " mAh"));
1706
 
1707
            //--------------- Flying time ------------------------
1708
            i_16 = data[56];
1709
            i_16 = (Int16)(i_16 << 8);
1710
            iVal = data[55] + i_16;
1711
            TimeSpan t = TimeSpan.FromSeconds(iVal);
1712
            string Text = t.Hours.ToString("D2") + ":" + t.Minutes.ToString("D2") + ":" + t.Seconds.ToString("D2");
1713
            Dispatcher.Invoke((Action)(() => tbFTime.Text = Text.ToString()));
1714
            Dispatcher.Invoke((Action)(() => tbTopFTime.Text = Text.ToString()));
1715
 
1716
            //--------------- RC quality ------------------------
1717
            Dispatcher.Invoke((Action)(() => tbRCQ.Text = data[66].ToString()));
1718
            Dispatcher.Invoke((Action)(() => tbTopRC.Text = data[66].ToString()));
1719
 
2291 - 1720
            if(data[66] > _iThresholdRC)
1721
            {
1722
                _iRCLevelJitter = 0; _bVoiceRCLevelActive = false;
1723
                if (stbRCLevelAnim != null && _bAnimRCLevelActive)
1724
                {
1725
                    Dispatcher.Invoke(() => stbRCLevelAnim.Stop());
1726
                    _bAnimRCLevelActive = false;
1727
                }
1728
            }
1729
            else
1730
            {
1731
                if (_iRCLevelJitter < 20) _iRCLevelJitter++;
1732
                if (_iRCLevelJitter == 20)
1733
                {
1734
                    if (stbRCLevelAnim != null && !_bAnimRCLevelActive)
1735
                    {
1736
                        Dispatcher.Invoke(() => stbRCLevelAnim.Begin());
1737
                        _bAnimRCLevelActive = true;
1738
                    }
1739
                    if (_bVoiceRCLevelPlay && !_bVoiceRCLevelActive)
1740
                    {
2295 - 1741
                        Thread th = new Thread(() => _mediaPlayer("Voice\\RCLevel.mp3"));
1742
                        th.Start();
2291 - 1743
                        _bVoiceRCLevelActive = true;
1744
                    }
1745
                        _iRCLevelJitter++;
1746
                }
1747
            }
1748
 
2287 - 1749
            //--------------- NC Error ------------------------
1750
            Dispatcher.Invoke((Action)(() => tbNCErr.Text = data[69].ToString()));  //NC Errornumber
1751
            if (data[69] > 0)
1752
                _readNCError();
1753
            if (data[69] > 0 & data[69] < 44)
1754
                ErrorLog(LogMsgType.Error, "NC Error [" + data[69].ToString() + "]: " + NC_Error[data[69]]);
1755
            else
1756
                if (_bErrorLog) _clearErrorLog("NC Error");
1757
 
2298 - 1758
            //-------------FC / NC Status Flags
1759
            Dispatcher.Invoke((Action)(() => FC1_1.Background = ((data[67] & 1) ==1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_MOTOR_RUN                             0x01
1760
            Dispatcher.Invoke((Action)(() => FC1_2.Background = ((data[67] & 2) ==2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_FLY                                   0x02
1761
            Dispatcher.Invoke((Action)(() => FC1_3.Background = ((data[67] & 4) ==4) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_CALIBRATE                             0x04
1762
            Dispatcher.Invoke((Action)(() => FC1_4.Background = ((data[67] & 8) ==8) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_START                                 0x08
1763
            Dispatcher.Invoke((Action)(() => FC1_5.Background = ((data[67] & 16) ==16) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_EMERGENCY_LANDING                      0x10
1764
            Dispatcher.Invoke((Action)(() => FC1_6.Background = ((data[67] & 32) ==32) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_LOWBAT                         0x20
1765
 
1766
            Dispatcher.Invoke((Action)(() => FC2_1.Background = ((data[74] & 1) ==1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_CAREFREE                             0x01
1767
            Dispatcher.Invoke((Action)(() => FC2_2.Background = ((data[74] & 2) ==2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_ALTITUDE_CONTROL                     0x02
1768
            Dispatcher.Invoke((Action)(() => FC2_3.Background = ((data[74] & 4) ==4) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_RC_FAILSAVE_ACTIVE                      0x04
1769
            Dispatcher.Invoke((Action)(() => FC2_4.Background = ((data[74] & 8) ==8) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_OUT1_ACTIVE                          0x08
1770
            Dispatcher.Invoke((Action)(() => FC2_5.Background = ((data[74] & 16) ==16) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_OUT2_ACTIVE                        0x10
1771
            Dispatcher.Invoke((Action)(() => FC2_6.Background = ((data[74] & 32) ==32) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_WAIT_FOR_TAKEOFF                   0x20   // Motor Running, but still on the ground
1772
            Dispatcher.Invoke((Action)(() => FC2_7.Background = ((data[74] & 64) ==64) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_AUTO_STARTING                              0x40
1773
            Dispatcher.Invoke((Action)(() => FC2_8.Background = ((data[74] & 128) ==128) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_AUTO_LANDING                             0x80
1774
 
1775
            Dispatcher.Invoke((Action)(() => NC1_2.Background = ((data[68] & 2) == 2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_PH                                     0x02
1776
            Dispatcher.Invoke((Action)(() => NC1_3.Background = ((data[68] & 4) == 4) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_CH                                     0x04
1777
            Dispatcher.Invoke((Action)(() => NC1_4.Background = ((data[68] & 8) == 8) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_RANGE_LIMIT                               0x08
1778
            Dispatcher.Invoke((Action)(() => NC1_5.Background = ((data[68] & 16) == 16) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_NOSERIALLINK                            0x10
1779
            Dispatcher.Invoke((Action)(() => NC1_6.Background = ((data[68] & 32) == 32) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_TARGET_REACHED                               0x20
1780
            Dispatcher.Invoke((Action)(() => NC1_7.Background = ((data[68] & 64) == 64) ? new SolidColorBrush(Colors.DodgerBlue) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_MANUAL_CONTROL                          0x40
1781
            Dispatcher.Invoke((Action)(() => NC1_8.Background = ((data[68] & 128) == 128) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_GPS_OK                                     0x80
2299 - 1782
 
1783
            //Sidebar StatusSymbols
1784
            Dispatcher.Invoke((Action)(() => tbSideBarStatusMotors.Background = ((data[67] & 1) ==1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_MOTOR_RUN                             0x01
1785
            Dispatcher.Invoke((Action)(() => tbSideBarStatusMotors.Foreground = ((data[67] & 1) ==1) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255,211,210,210))));// FC_STATUS_MOTOR_RUN                                0x01
1786
            Dispatcher.Invoke((Action)(() => tbSideBarStatusMotors.BorderBrush = ((data[67] & 1) ==1) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS_MOTOR_RUN                            0x01
1787
 
1788
            Dispatcher.Invoke((Action)(() => tbSideBarStatusCF.Background = ((data[74] & 1) == 1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_CAREFREE                                0x01
1789
            Dispatcher.Invoke((Action)(() => tbSideBarStatusCF.Foreground = ((data[74] & 1) == 1) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS2_CAREFREE                                0x01
1790
            Dispatcher.Invoke((Action)(() => tbSideBarStatusCF.BorderBrush = ((data[74] & 1) ==1) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS2_CAREFREE                                0x01
1791
 
1792
            Dispatcher.Invoke((Action)(() => tbSideBarStatusEmergencyLanding.Background = ((data[67] & 16) == 16) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_EMERGENCY_LANDING                   0x10
2304 - 1793
            Dispatcher.Invoke((Action)(() => tbSideBarStatusEmergencyLanding.Foreground = ((data[67] & 16) == 16) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS_EMERGENCY_LANDING                0x10
1794
            Dispatcher.Invoke((Action)(() => tbSideBarStatusEmergencyLanding.BorderBrush = ((data[67] & 16) == 16) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS_EMERGENCY_LANDING               0x10
2299 - 1795
 
1796
            Dispatcher.Invoke((Action)(() => tbSideBarStatusAC.Background = ((data[74] & 2) ==2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_ALTITUDE_CONTROL                         0x02
1797
            Dispatcher.Invoke((Action)(() => tbSideBarStatusAC.Foreground = ((data[74] & 2) ==2) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS2_ALTITUDE_CONTROL                         0x02
1798
            Dispatcher.Invoke((Action)(() => tbSideBarStatusAC.BorderBrush = ((data[74] & 2) ==2) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// FC_STATUS2_ALTITUDE_CONTROL                        0x02
1799
 
1800
            Dispatcher.Invoke((Action)(() => tbSideBarStatusPH.Text = ((data[68] & 4) == 4) ? "CH" : "PH"));// NC_FLAG_PH 0x02 / NC_FLAG_CH 0x04
2304 - 1801
            Dispatcher.Invoke((Action)(() => tbSideBarStatusPH.Background = (((data[68] & 2) == 2)|((data[68] & 4) == 4)) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_PH 0x02 / NC_FLAG_CH 0x04
1802
            Dispatcher.Invoke((Action)(() => tbSideBarStatusPH.Foreground = (((data[68] & 2) == 2)|((data[68] & 4) == 4)) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// NC_FLAG_PH 0x02 / NC_FLAG_CH 0x04
1803
            Dispatcher.Invoke((Action)(() => tbSideBarStatusPH.BorderBrush = (((data[68] & 2) == 2)|((data[68] & 4) == 4)) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));// NC_FLAG_PH 0x02 / NC_FLAG_CH 0x04
2299 - 1804
 
2324 - 1805
            _bAirborne = (data[67] & 2) == 2 ? true : false;
2287 - 1806
        }
1807
        /// <summary>
1808
        /// Navi-Ctrl WP data struct 'X'
1809
        /// called by index
1810
        /// </summary>
1811
        /// <param name="data">the received byte array to process</param>
1812
        void _processWPData(byte[] data)
1813
        {
2313 - 1814
            _iWPCount = data[0];
2287 - 1815
            _bGetWPCount = false;
1816
            if (data.Length >= 28)
1817
            {
1818
                Dispatcher.Invoke(() => lblWPIndex.Content = data[1].ToString());
1819
                Dispatcher.Invoke(() => lblWPCount.Content = data[0].ToString());
1820
                if (_bGetWP)
1821
                {
1822
                    if (data[1] == 1)
2315 - 1823
                    {
2333 - 1824
                        if(mRouteWP != null)
1825
                            Dispatcher.Invoke(() => MainMap.Markers.Remove(mRouteWP));
2328 - 1826
                        wpList.Clear();
1827
 
1828
                        Dispatcher.Invoke(() => lblWPRouteDistance.Content = "0 m");
2287 - 1829
                        dtWaypoints.Rows.Clear();
2333 - 1830
                        Dispatcher.Invoke(() =>
1831
                        {
2318 - 1832
                            for (int k = 0; k < MainMap.Markers.Count;)
1833
                            {
1834
                                GMapMarker p = MainMap.Markers[k];
1835
                                if (p.Shape.GetType() == typeof(CustomMarkerWP))
1836
                                    MainMap.Markers.Remove(p);
1837
                                else
1838
                                    k++;
1839
                            }
1840
                        });
2315 - 1841
                    }
2287 - 1842
                    DataRow dr = dtWaypoints.NewRow();
1843
                    dr = Waypoints.toDataRow(data, dr);
2313 - 1844
                    dtWaypoints.Rows.Add(dr);
2318 - 1845
                    Dispatcher.Invoke(() => {
1846
                        GMapMarker wp = new GMapMarker(new PointLatLng((double)dr[3], (double)dr[4]));
1847
                        wp.Shape = new CustomMarkerWP(this, wp, (string)dr[2],(int)dr[1]);
2333 - 1848
                        wp.Offset = new System.Windows.Point(-11.5, -11.5);
2318 - 1849
                        _setMarkerColor(wp, (int)dr[1]);
1850
                        MainMap.Markers.Add(wp);
1851
                    });
2313 - 1852
                    Dispatcher.Invoke(() => dgvWP.Items.Refresh());
1853
                    Dispatcher.Invoke(() => _iWPIndex = data[1]);
2335 - 1854
                    if ((int)dr[1] == 0)
1855
                        wpList.Add(new PointLatLng((double)dr[3], (double)dr[4]));
2287 - 1856
                    if (data[1] == data[0])
1857
                    {
1858
                        _bGetWP = false;
1859
                        Dispatcher.Invoke(() => dgvWP.Items.Refresh());
2328 - 1860
 
1861
                        Dispatcher.Invoke(() =>
1862
                        {
1863
                            if (comboBoxRouteColor.SelectionBoxItem != null)
1864
                            {
1865
                                string s = comboBoxRouteColor.SelectionBoxItem.ToString();
1866
                                mRouteWP = new GMapRoute(wpList, _getBrush(s));
1867
                            }
1868
                            else
1869
                                mRouteWP = new GMapRoute(wpList, null);
1870
 
1871
                            if (_bShowWPRoute)
1872
                                MainMap.Markers.Add(mRouteWP);
1873
                        });
1874
                        MapRoute mr = new MapRoute(wpList, "WPList");
2333 - 1875
                        Dispatcher.Invoke(() => lblWPRouteDistance.Content = (mr.Distance * 1000).ToString("0 m"));
2287 - 1876
                    }
1877
 
1878
                }
1879
            }
1880
            else
1881
            {
1882
                Dispatcher.Invoke(() => lblWPIndex.Content = 0);
1883
                Dispatcher.Invoke(() => lblWPCount.Content = 0);
1884
            }
1885
        }
1886
        /// <summary>
1887
        /// OSD Menue 'L'
1888
        /// single page called by pagenumber
1889
        /// no autoupdate
1890
        /// </summary>
1891
        /// <param name="data">the received byte array to process</param>
1892
        void _processOSDSingle(byte[] data)
1893
        {
1894
            if (data.Length == 84)
1895
            {
1896
                string sMessage = "";
1897
                iOSDPage = data[0];
1898
                iOSDMax = data[1];
1899
                if (cbOSD.Items.Count != iOSDMax) _initOSDCB();
1900
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 2, data.Length - 4));
1901
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20)+ "\r", true);
1902
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20)+ "\r", false);
1903
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20)+ "\r", false);
1904
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20), false);
1905
                Dispatcher.Invoke(() => { cbOSD.SelectedValue = iOSDPage; });
1906
              //  lblOSDPageNr.Invoke((Action)(() => lblOSDPageNr.Text = iOSDPage.ToString("[0]")));
1907
 
1908
            }
1909
            //else
1910
            //    OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 84)");
1911
 
1912
        }
1913
        /// <summary>
1914
        /// OSD Menue 'H'
1915
        /// called by keys (0x01,0x02,0x03,0x04)
1916
        /// autoupdate
1917
        /// </summary>
1918
        /// <param name="data">the received byte array to process</param>
1919
        void _processOSDAuto(byte[] data)
1920
        {
1921
            if (data.Length == 81)
1922
            {
1923
                string sMessage = "";
1924
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length - 1));
1925
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20)+ "\r", true);
1926
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20)+ "\r", false);
1927
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20)+ "\r", false);
1928
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20), false);
1929
 
1930
            }
1931
            //else
1932
            //    OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 81)");
1933
        }
1934
 
1935
        #endregion processing received data
1936
 
1937
        #region controller messages
1938
        /// <summary> send message to controller to request data
1939
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
1940
        /// </summary>
1941
        /// <param name="CMDID"> the command ID </param>
1942
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
1943
        private void _sendControllerMessage(char CMDID, byte address)
1944
        {
1945
            if (serialPortCtrl.Port.IsOpen)
1946
            {
1947
                Stream serialStream = serialPortCtrl.Port.BaseStream;
1948
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address);
1949
                serialStream.Write(bytes, 0, bytes.Length);
1950
 
1951
            }
1952
            else
1953
                Log(LogMsgType.Error, "NOT CONNECTED!");
1954
        }
1955
        /// <summary> send message to controller to request data
1956
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
1957
        /// </summary>
1958
        /// <param name="CMDID"> the command ID </param>
1959
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
1960
        /// <param name="data"> additional data for the request</param>
1961
        private void _sendControllerMessage(char CMDID, byte address, byte[] data)
1962
        {
1963
            if (serialPortCtrl.Port.IsOpen)
1964
            {
1965
                Stream serialStream = serialPortCtrl.Port.BaseStream;
1966
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address, data);
1967
                serialStream.Write(bytes, 0, bytes.Length);
1968
 
1969
            }
1970
            else
1971
                Log(LogMsgType.Error, "NOT CONNECTED!");
1972
        }
1973
 
1974
        /// <summary>
1975
        /// start/stop continous polling of controller values
1976
        /// </summary>
1977
        /// <param name="b">start/stop switch</param>
1978
        void _readCont(bool b)
1979
        {
1980
            bReadContinously = b;
1981
            if (bReadContinously)
1982
            {
1983
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
1984
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
1985
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
1986
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); Thread.Sleep(10); }
1987
                // Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.LightGreen));
1988
                Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_G.png", UriKind.Relative)));
1989
            }
1990
            else
1991
            {
1992
                // Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.LightGray));
1993
                Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_W.png", UriKind.Relative)));
1994
                _bConnErr = false;
1995
            }
1996
            _iLifeCounter = 0;
1997
        }
1998
 
1999
        private void _getVersion()
2000
        {
2001
            _sendControllerMessage('v', 0);
2002
        }
2003
        /// <summary>
2004
        /// get FC version struct via NC
2005
        /// by sending '1' as data (not documented in wiki...)
2006
        /// returns HW error 255 (comment in uart1.c : tells the KopterTool that it is the FC-version)
2007
        /// </summary>
2008
        /// <param name="ctrl">controller number 1=FC</param> 
2009
        private void _getVersion(byte ctrl)
2010
        {
2011
            _sendControllerMessage('v', 0, new byte[1] { ctrl });
2012
        }
2013
        /// <summary>
2014
        /// Switch back to NC by sending the 'Magic Packet' 0x1B,0x1B,0x55,0xAA,0x00
2015
        /// </summary>
2016
        private void _switchToNC()
2017
        {
2018
            if (serialPortCtrl.Port.IsOpen)
2019
            {
2020
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2021
                byte[] bytes = new byte[5] { 0x1B, 0x1B, 0x55, 0xAA, 0x00 };
2022
                serialStream.Write(bytes, 0, bytes.Length);
2023
 
2024
                Thread.Sleep(100);
2025
                _getVersion();
2026
                Thread.Sleep(100);
2027
               // _OSDMenue(0);
2028
            }
2029
            else
2030
                Log(LogMsgType.Error, "NOT CONNECTED!");
2031
        }
2032
        /// <summary>
2033
        /// switch to FC
2034
        /// </summary>
2035
        private void _switchToFC()
2036
        {
2037
            _sendControllerMessage('u', 2, new byte[1] { (byte)0 });
2038
            Thread.Sleep(100);
2039
            _getVersion();
2040
            Thread.Sleep(100);
2041
          //  _OSDMenue(0);
2042
        }
2043
        /// <summary>
2044
        /// send RESET signal to FC
2045
        /// </summary>
2046
        private void _resetCtrl()
2047
        {
2048
            _sendControllerMessage('R', 1);
2049
        }
2050
        /// <summary>
2051
        /// poll the debug data (4sec subscription)
2052
        /// </summary>
2053
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
2054
        private void _readDebugData(bool auto)
2055
        {
2056
            byte interval = auto ? debugInterval : (byte)0;
2057
            _sendControllerMessage('d', 0, new byte[1] { debugInterval });
2058
        }
2059
        /// <summary>
2060
        /// poll the BL-CTRL status via NC (4sec subscription)
2061
        /// </summary>
2062
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
2063
        private void _readBLCtrl(bool auto)
2064
        {
2065
            byte interval = auto ? blctrlInterval : (byte)0;
2066
            _sendControllerMessage('k', 0, new byte[1] { interval });
2067
        }
2068
        /// <summary>
2069
        /// poll the NC data struct (4sec subscription)
2070
        /// </summary>
2071
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
2072
        private void _readNavData(bool auto)
2073
        {
2074
            byte interval = auto ? navctrlInterval : (byte)0;
2075
            _sendControllerMessage('o', 2, new byte[1] { interval });
2076
        }
2077
        /// <summary>
2078
        /// get the errortext for pending NC error
2079
        /// </summary>
2080
        private void _readNCError()
2081
        {
2082
            _sendControllerMessage('e', 2);
2083
        }
2084
        /// <summary>
2085
        /// request the Waypoint at index
2086
        /// </summary>
2087
        /// <param name="index"></param>
2088
        void _getpWP(int index)
2089
        {
2090
            if (serialPortCtrl.Port.IsOpen)
2091
            {
2092
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2093
                byte[] bytes = FlightControllerMessage.CreateMessage('x', 2, new byte[1] { (byte)index });
2094
                serialStream.Write(bytes, 0, bytes.Length);
2095
            }
2096
            else
2097
                Log(LogMsgType.Error, "NOT CONNECTED!");
2098
 
2099
        }
2100
        void _getWP()
2101
        {
2335 - 2102
            int iTimeout = 0;
2287 - 2103
            _bGetWPCount = true;
2315 - 2104
            _getpWP(1); //get the itemscount of wp
2335 - 2105
            while (_bGetWPCount & iTimeout < _iWPTimeout * 5)
2106
            {
2107
                Thread.Sleep(10);
2108
                iTimeout++;
2109
            }
2110
            if (_iWPCount > 0 & !_bGetWPCount)
2287 - 2111
                _getWPList();
2112
        }
2113
        void _getWPList()
2114
        {
2115
            _bGetWP = true;
2313 - 2116
            int iTimeout=0;
2117
            for (int j = 0; j < _iWPCount; j++)
2287 - 2118
            {
2119
                _getpWP(j + 1);
2313 - 2120
                iTimeout = 0;
2121
                while (_iWPIndex != j + 1 & iTimeout < _iWPTimeout * 5)
2122
                {
2123
                    Thread.Sleep(1);
2124
                    iTimeout++;
2125
                }
2287 - 2126
            }
2127
        }
2313 - 2128
        void _sendWPList()
2129
        {
2335 - 2130
            int iTimeout = 0;
2313 - 2131
            if (serialPortCtrl.Port.IsOpen)
2132
            {
2133
                byte[] bData = new byte[30];
2134
                for (int i = 0; i < 30; i++)
2135
                    bData[i] = 0;
2136
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2137
                byte[] bytes = FlightControllerMessage.CreateMessage('w', 2, bData); //delete all WP on Copter by sending 'invalid'(==0) at index 0
2138
                serialStream.Write(bytes, 0, bytes.Length);
2287 - 2139
 
2313 - 2140
                _iWPCount = -1;
2335 - 2141
                while (_iWPCount == -1 & iTimeout < _iWPTimeout * 5)
2142
                {
2313 - 2143
                    Thread.Sleep(10);
2335 - 2144
                    iTimeout++;
2145
                }
2313 - 2146
                Dispatcher.Invoke(() => lblWPCount.Content = _iWPCount.ToString());
2335 - 2147
                if (_iWPCount > -1)
2313 - 2148
                {
2149
 
2335 - 2150
                    int iVal;
2151
                    double dVal;
2152
                    NumberFormatInfo nfi = new NumberFormatInfo();
2153
                    nfi.NumberDecimalSeparator = ",";
2154
                    for (int i = 0; i < dtWaypoints.Rows.Count; i++)
2155
                    {
2156
                        //longitude
2157
                        dVal = Convert.ToDouble(dtWaypoints.Rows[i][4], nfi);
2158
                        iVal = (int)(dVal * Math.Pow(10, 7));
2159
                        bData[0] = (byte)(iVal & 0xff);
2160
                        bData[1] = (byte)((iVal >> 8) & 0xff);
2161
                        bData[2] = (byte)((iVal >> 16) & 0xff);
2162
                        bData[3] = (byte)(iVal >> 24);
2163
                        //latitude
2164
                        dVal = Convert.ToDouble(dtWaypoints.Rows[i][3], nfi);
2165
                        iVal = (int)(dVal * Math.Pow(10, 7));
2166
                        bData[4] = (byte)(iVal & 0xff);
2167
                        bData[5] = (byte)((iVal >> 8) & 0xff);
2168
                        bData[6] = (byte)((iVal >> 16) & 0xff);
2169
                        bData[7] = (byte)(iVal >> 24);
2170
                        //altitude
2171
                        dVal = Convert.ToDouble(dtWaypoints.Rows[i][5], nfi);
2172
                        iVal = (int)(dVal * 10);
2173
                        bData[8] = (byte)(iVal & 0xff);
2174
                        bData[9] = (byte)((iVal >> 8) & 0xff);
2175
                        bData[10] = (byte)((iVal >> 16) & 0xff);
2176
                        bData[11] = (byte)(iVal >> 24);
2177
                        //Status 'NEWDATA'
2178
                        bData[12] = 1;
2179
                        //heading
2180
                        iVal = Convert.ToInt16(dtWaypoints.Rows[i][6]);
2181
                        bData[13] = (byte)(iVal & 0xff);
2182
                        bData[14] = (byte)((iVal >> 8) & 0xff);
2183
                        //ToleranceRadius
2184
                        bData[15] = Convert.ToByte(dtWaypoints.Rows[i][9]);
2185
                        //HoldTime
2186
                        bData[16] = Convert.ToByte(dtWaypoints.Rows[i][10]);
2187
                        //Event_Flag
2188
                        bData[17] = Convert.ToByte(dtWaypoints.Rows[i][13]);
2189
                        //Index
2190
                        bData[18] = Convert.ToByte((int)dtWaypoints.Rows[i][0]);
2191
                        //Type
2192
                        bData[19] = Convert.ToByte(dtWaypoints.Rows[i][1]);
2193
                        //WP_EventChannelValue
2194
                        bData[20] = Convert.ToByte(dtWaypoints.Rows[i][14]);
2195
                        //AltitudeRate
2196
                        bData[21] = Convert.ToByte(dtWaypoints.Rows[i][8]);
2197
                        //Speed
2198
                        bData[22] = Convert.ToByte(dtWaypoints.Rows[i][7]);
2199
                        //CamAngle
2200
                        bData[23] = (byte)Convert.ToInt16(dtWaypoints.Rows[i][12]);
2201
                        //Name
2202
                        byte[] name = ASCIIEncoding.ASCII.GetBytes((string)dtWaypoints.Rows[i][2]);
2203
                        bData[24] = name.Length > 0 ? name[0] : (byte)0;
2204
                        bData[25] = name.Length > 1 ? name[1] : (byte)0;
2205
                        bData[26] = name.Length > 2 ? name[2] : (byte)0;
2206
                        bData[27] = name.Length > 3 ? name[3] : (byte)0;
2207
                        //Autotrigger
2208
                        bData[28] = Convert.ToByte(dtWaypoints.Rows[i][11]);
2313 - 2209
 
2335 - 2210
                        bytes = FlightControllerMessage.CreateMessage('w', 2, bData);
2211
                        serialStream.Write(bytes, 0, bytes.Length);
2212
 
2213
                        _iWPCount = -1;
2214
                        iTimeout = 0;
2215
                        while (_iWPCount == -1 & iTimeout < _iWPTimeout * 5)
2216
                        {
2217
                            Thread.Sleep(10);
2218
                            iTimeout++;
2219
                        }
2220
                        if (_iWPCount == -1)
2221
                        {
2222
                            Log(LogMsgType.Error, "Timeout while sending list!");
2223
                            break;
2224
                        }
2225
                        Dispatcher.Invoke(() => lblWPCount.Content = _iWPCount.ToString());
2226
                    }
2313 - 2227
                }
2335 - 2228
                else
2229
                    Log(LogMsgType.Error, "Timeout while sending list!");
2313 - 2230
            }
2231
            else
2232
                Log(LogMsgType.Error, "NOT CONNECTED!");
2233
 
2234
        }
2235
 
2287 - 2236
        #region OSD-Menue
2237
 
2238
        /// <summary>
2239
        /// one time query of the OSD Menue with pagenumber
2240
        /// </summary>
2241
        /// <param name="iMenue">Menue page</param>
2242
        void _OSDMenue(int iMenue)
2243
        {
2244
            if (serialPortCtrl.Port.IsOpen)
2245
            {
2246
                if (iMenue > iOSDMax)
2247
                    iMenue = 0;
2248
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2249
                byte[] bytes = FlightControllerMessage.CreateMessage('l', 0, new byte[1] { (byte)iMenue });
2250
                serialStream.Write(bytes, 0, bytes.Length);
2251
            }
2252
            else
2253
                Log(LogMsgType.Error, "NOT CONNECTED!");
2254
 
2255
        }
2256
        /// <summary>
2257
        /// call the OSDMenue and start autorefresh
2258
        ///  usually by sending a menuekey
2259
        /// a bit tricky - but by sending inverted value of 32 (32 = 0010 0000) you can start the OSD menue with autoupdate (abo) without switching the page with the keyvalues (0x1, 0x2)
2260
        /// therefore the value has to be negative (inverted) in order to distinguish from old (2 line) menuestyle
2261
        /// and must not have any bits of the menue keys 0x1 0x2 0x4 0x8 (0x10?) --> 0x20 = -33
2262
        /// </summary>
2263
        void _OSDMenueAutoRefresh()
2264
        {
2265
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)(-33)), OSDInterval });
2266
        }
2267
        void _OSDMenueAutoRefresh(byte key)
2268
        {
2269
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)~key), OSDInterval });
2270
        }
2271
        /// <summary>
2272
        /// initialize the OSD menue combobox
2273
        /// combox is filled by numbers from 0 to max pagenumber
2274
        /// </summary>
2275
        void _initOSDCB()
2276
        {
2277
            _bCBInit = true;
2278
            if (iOSDMax == 0)
2279
            {
2280
                _OSDMenue(0);
2281
                Thread.Sleep(10);
2282
            }
2283
            Dispatcher.Invoke((Action)(() => cbOSD.Items.Clear()));
2284
            for (int i = 0; i <= iOSDMax; i++)
2285
            {
2286
                Dispatcher.Invoke((Action)(() => cbOSD.Items.Add(i)));
2287
            }
2288
            Dispatcher.Invoke((Action)(() => cbOSD.SelectedItem = iOSDPage));
2289
            _bCBInit = false;
2290
        }
2291
        private void btnOSDForward_Click(object sender, RoutedEventArgs e)
2292
        {
2293
            iOSDPage++;
2294
            if (iOSDPage > iOSDMax)
2295
                iOSDPage = 0;
2296
 
2297
            _OSDMenue(iOSDPage);
2298
        }
2299
        private void btnOSDBackward_Click(object sender, RoutedEventArgs e)
2300
        {
2301
            iOSDPage--;
2302
            if (iOSDPage < 0)
2303
                iOSDPage = iOSDMax;
2304
 
2305
            _OSDMenue(iOSDPage);
2306
        }
2307
        private void btnOSDLeave_Click(object sender, RoutedEventArgs e)
2308
        {
2309
            _OSDMenueAutoRefresh(8);
2310
        }
2311
        private void btnOSDEnter_Click(object sender, RoutedEventArgs e)
2312
        {
2313
            _OSDMenueAutoRefresh(4);
2314
        }
2315
        private void cbOSD_DropDownClosing(object sender, EventArgs e)
2316
        {
2317
            if (!_bCBInit && cbOSD.SelectedIndex > -1)
2318
                _OSDMenue(cbOSD.SelectedIndex);
2319
        }
2320
        private void OSD(LogMsgType msgtype, string msg, bool bNew)
2321
        {
2322
            Dispatcher.Invoke(() =>
2323
            {
2324
                TextRange tr;
2325
                if (bNew)
2326
                {
2327
                    rtfOSD.SelectAll();
2328
                    rtfOSD.Selection.Text = string.Empty;
2329
                }
2330
                tr = new TextRange(rtfOSD.Document.ContentEnd, rtfOSD.Document.ContentEnd);
2331
                tr.Text = msg;
2332
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(LogMsgTypeColor[(int)msgtype]));
2333
                //     rtfOSD.AppendText("\r");
2334
                rtfOSD.ScrollToEnd();
2335
 
2336
            });
2337
        }
2338
 
2339
        #endregion OSD-Menue
2340
 
2341
        #endregion controller messages
2342
 
2295 - 2343
        void _mediaPlayer(string file)
2344
        {
2345
            if (File.Exists(file))
2346
            {
2347
                MediaPlayer.MediaPlayer mp = new MediaPlayer.MediaPlayer();
2348
                mp.Open(file);
2349
                mp.Play();
2350
            }
2351
        }
2310 - 2352
 
2353
        /// <summary>
2354
        /// Switch between fullscreen and normal window mode
2355
        /// save & restore scaling settings
2356
        /// </summary>
2357
        /// <param name="sender"></param>
2358
        /// <param name="e"></param>
2287 - 2359
        private void imageFullscreen_MouseDown(object sender, MouseButtonEventArgs e)
2360
        {
2361
            if (winState.isMaximized)
2362
            {
2363
                winState.Restore(this);
2364
                imageFullscreen.Source = new BitmapImage(new Uri("Images/Fullscreen.png", UriKind.Relative));
2365
                if(_bSaveWinStateFull)
2366
                    _saveScaleSliders(true);
2367
                if(_bSaveWinStateNormal)
2368
                    _setScaleSliders(false);
2369
            }
2370
            else
2371
            {
2372
                winState.Maximize(this);
2373
                imageFullscreen.Source = new BitmapImage(new Uri("Images/RestoreScreen.png", UriKind.Relative));
2374
                if(_bSaveWinStateNormal)
2375
                    _saveScaleSliders(false);
2376
                if(_bSaveWinStateFull)
2377
                    _setScaleSliders(true);
2378
            }
2379
        }
2380
 
2381
        /// <summary>
2382
        /// reset the scaling of all UI elements to default
2383
        /// </summary>
2384
        /// <param name="sender"></param>
2385
        /// <param name="e"></param>
2386
        private void buttonUIScaleReset_Click(object sender, RoutedEventArgs e)
2387
        {
2388
            UIScaleHorizonSlider.Value =
2389
                UIScaleLOGSlider.Value =
2390
                UIScaleMotorsSlider.Value =
2391
                UIScaleOSDSlider.Value =
2392
                UIScaleSlider.Value =
2393
                UIScaleTopSlider.Value = 1;
2394
        }
2395
        /// <summary>
2396
        /// adjust the top postion of UI elements below the top bar to fit the bottom position of the bar when scaling the top bar
2397
        /// </summary>
2398
        /// <param name="sender"></param>
2399
        /// <param name="e"></param>
2400
        private void UIScaleTopSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
2401
        {
2402
            GridSettings.Margin = new Thickness(GridSettings.Margin.Left, 36 * UIScaleTopSlider.Value, GridSettings.Margin.Right, GridSettings.Margin.Bottom);
2403
            if (GridMotors != null)
2404
                GridMotors.Margin = new Thickness(GridMotors.Margin.Left, 36 * UIScaleTopSlider.Value, GridMotors.Margin.Right, GridMotors.Margin.Bottom);
2405
            if (GridSideBar != null)
2406
                GridSideBar.Margin = new Thickness(GridSideBar.Margin.Left, 36 * UIScaleTopSlider.Value, GridSideBar.Margin.Right, GridSideBar.Margin.Bottom);
2407
            if (GridOSD != null)
2408
                GridOSD.Margin = new Thickness(GridOSD.Margin.Left, 36 * UIScaleTopSlider.Value, GridOSD.Margin.Right, GridOSD.Margin.Bottom);
2409
            if (GridData != null)
2410
                GridData.Margin = new Thickness(GridData.Margin.Left, 36 * UIScaleTopSlider.Value, GridData.Margin.Right, GridData.Margin.Bottom);
2411
            if (GridWP != null)
2412
                GridWP.Margin = new Thickness(GridWP.Margin.Left, 36 * UIScaleTopSlider.Value, GridWP.Margin.Right, GridWP.Margin.Bottom);
2413
        }
2310 - 2414
        /// <summary>
2415
        /// restore the saved scalings for the fullscreen/normal window mode
2416
        /// </summary>
2417
        /// <param name="bFull">the mode the window is set to</param>
2287 - 2418
        void _setScaleSliders(bool bFull)
2419
        {
2420
            if(bFull)
2421
            {
2422
                UIScaleSlider.Value = scaleFullAll;
2423
                UIScaleTopSlider.Value = scaleFullTopBar;
2424
                UIScaleMotorsSlider.Value = scaleFullMotors;
2425
                UIScaleOSDSlider.Value = scaleFullOSD;
2426
                UIScaleLOGSlider.Value = scaleFullLOG;
2427
                UIScaleHorizonSlider.Value = scaleFullHorizon;
2428
            }
2429
            else
2430
            {
2431
                UIScaleSlider.Value = scaleNormalAll;
2432
                UIScaleTopSlider.Value = scaleNormalTopBar;
2433
                UIScaleMotorsSlider.Value = scaleNormalMotors;
2434
                UIScaleOSDSlider.Value = scaleNormalOSD;
2435
                UIScaleLOGSlider.Value = scaleNormalLOG;
2436
                UIScaleHorizonSlider.Value = scaleNormalHorizon;
2437
            }
2438
        }
2439
 
2310 - 2440
        /// <summary>
2441
        /// save the scalings for the actual window mode
2442
        /// </summary>
2443
        /// <param name="bFull">the actual window mode</param>
2287 - 2444
        void _saveScaleSliders(bool bFull)
2445
        {
2446
 
2447
            if (bFull)
2448
            {
2449
                scaleFullAll = UIScaleSlider.Value;
2450
                scaleFullTopBar = UIScaleTopSlider.Value;
2451
                scaleFullMotors = UIScaleMotorsSlider.Value;
2452
                scaleFullOSD = UIScaleOSDSlider.Value;
2453
                scaleFullLOG = UIScaleLOGSlider.Value;
2454
                scaleFullHorizon = UIScaleHorizonSlider.Value;
2455
            }
2456
            else
2457
            {
2458
                scaleNormalAll = UIScaleSlider.Value;
2459
                scaleNormalTopBar = UIScaleTopSlider.Value;
2460
                scaleNormalMotors = UIScaleMotorsSlider.Value;
2461
                scaleNormalOSD = UIScaleOSDSlider.Value;
2462
                scaleNormalLOG = UIScaleLOGSlider.Value;
2463
                scaleNormalHorizon = UIScaleHorizonSlider.Value;
2464
            }
2465
        }
2466
 
2467
        /// <summary>
2468
        /// read settings from ini-file
2469
        /// </summary>
2470
        void _readIni()
2471
        {
2472
            if (!File.Exists(filePath + "\\MKLiveViewSettings.ini"))
2473
                _writeIni();
2474
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
2475
            ini.path = filePath + "\\MKLiveViewSettings.ini";
2312 - 2476
            try
2477
            {
2287 - 2478
 
2312 - 2479
                string sVal = ini.IniReadValue("timings", "AutorefreshDebugData");
2480
                if (sVal != "") _debugDataAutorefresh = Convert.ToBoolean(sVal);
2481
                sVal = ini.IniReadValue("timings", "AutorefreshNavCtrlData");
2482
                if (sVal != "") _navCtrlDataAutorefresh = Convert.ToBoolean(sVal);
2483
                sVal = ini.IniReadValue("timings", "AutorefreshBLCtrlData");
2484
                if (sVal != "") _blctrlDataAutorefresh = Convert.ToBoolean(sVal);
2485
                sVal = ini.IniReadValue("timings", "AutorefreshOSDData");
2486
                if (sVal != "") _OSDAutorefresh = Convert.ToBoolean(sVal);
2287 - 2487
 
2312 - 2488
                sVal = ini.IniReadValue("timings", "IntervalDebugData");
2489
                if (sVal != "") debugInterval = (byte)Convert.ToInt16(sVal);
2490
                sVal = ini.IniReadValue("timings", "IntervalNavCtrlData");
2491
                if (sVal != "") navctrlInterval = (byte)Convert.ToInt16(sVal);
2492
                sVal = ini.IniReadValue("timings", "IntervalBLCtrlData");
2493
                if (sVal != "") blctrlInterval = (byte)Convert.ToInt16(sVal);
2494
                sVal = ini.IniReadValue("timings", "IntervalOSDData");
2495
                if (sVal != "") OSDInterval = (byte)Convert.ToInt16(sVal);
2287 - 2496
 
2312 - 2497
                sVal = ini.IniReadValue("topBar", "voltage");
2498
                if (sVal != "") chkBoxTopBarShowVoltage.IsChecked = Convert.ToBoolean(sVal);
2499
                sVal = ini.IniReadValue("topBar", "capacity");
2500
                if (sVal != "") chkBoxTopBarShowCapacity.IsChecked = Convert.ToBoolean(sVal);
2501
                sVal = ini.IniReadValue("topBar", "current");
2502
                if (sVal != "") chkBoxTopBarShowCurrent.IsChecked = Convert.ToBoolean(sVal);
2503
                sVal = ini.IniReadValue("topBar", "flightTime");
2504
                if (sVal != "") chkBoxTopBarShowFlightTime.IsChecked = Convert.ToBoolean(sVal);
2505
                sVal = ini.IniReadValue("topBar", "distanceHP");
2506
                if (sVal != "") chkBoxTopBarShowDistanceHP.IsChecked = Convert.ToBoolean(sVal);
2507
                sVal = ini.IniReadValue("topBar", "height");
2508
                if (sVal != "") chkBoxTopBarShowHeight.IsChecked = Convert.ToBoolean(sVal);
2509
                sVal = ini.IniReadValue("topBar", "speed");
2510
                if (sVal != "") chkBoxTopBarShowSpeed.IsChecked = Convert.ToBoolean(sVal);
2511
                sVal = ini.IniReadValue("topBar", "magneticField");
2512
                if (sVal != "") chkBoxTopBarShowMF.IsChecked = Convert.ToBoolean(sVal);
2513
                sVal = ini.IniReadValue("topBar", "satellites");
2514
                if (sVal != "") chkBoxTopBarShowSatellites.IsChecked = Convert.ToBoolean(sVal);
2515
                sVal = ini.IniReadValue("topBar", "rc");
2516
                if (sVal != "") chkBoxTopBarShowRC.IsChecked = Convert.ToBoolean(sVal);
2287 - 2517
 
2312 - 2518
                sVal = ini.IniReadValue("style", "saveFullScreen");
2519
                if (sVal != "") chkBoxSaveFullScreenState.IsChecked = Convert.ToBoolean(sVal);
2520
                sVal = ini.IniReadValue("style", "saveNormalState");
2521
                if (sVal != "") chkBoxSaveNormalState.IsChecked = Convert.ToBoolean(sVal);
2287 - 2522
 
2312 - 2523
                sVal = ini.IniReadValue("style", "scaleNormalAll");
2524
                if (sVal != "") scaleNormalAll = Convert.ToDouble(sVal);
2525
                sVal = ini.IniReadValue("style", "scaleNormalTopBar");
2526
                if (sVal != "") scaleNormalTopBar = Convert.ToDouble(sVal);
2527
                sVal = ini.IniReadValue("style", "scaleNormalMotors");
2528
                if (sVal != "") scaleNormalMotors = Convert.ToDouble(sVal);
2529
                sVal = ini.IniReadValue("style", "scaleNormalOSD");
2530
                if (sVal != "") scaleNormalOSD = Convert.ToDouble(sVal);
2531
                sVal = ini.IniReadValue("style", "scaleNormalLOG");
2532
                if (sVal != "") scaleNormalLOG = Convert.ToDouble(sVal);
2533
                sVal = ini.IniReadValue("style", "scaleNormalHorizon");
2534
                if (sVal != "") scaleNormalHorizon = Convert.ToDouble(sVal);
2287 - 2535
 
2312 - 2536
                sVal = ini.IniReadValue("style", "scaleFullAll");
2537
                if (sVal != "") scaleFullAll = Convert.ToDouble(sVal);
2538
                sVal = ini.IniReadValue("style", "scaleFullTopBar");
2539
                if (sVal != "") scaleFullTopBar = Convert.ToDouble(sVal);
2540
                sVal = ini.IniReadValue("style", "scaleFullMotors");
2541
                if (sVal != "") scaleFullMotors = Convert.ToDouble(sVal);
2542
                sVal = ini.IniReadValue("style", "scaleFullOSD");
2543
                if (sVal != "") scaleFullOSD = Convert.ToDouble(sVal);
2544
                sVal = ini.IniReadValue("style", "scaleFullLOG");
2545
                if (sVal != "") scaleFullLOG = Convert.ToDouble(sVal);
2546
                sVal = ini.IniReadValue("style", "scaleFullHorizon");
2547
                if (sVal != "") scaleFullHorizon = Convert.ToDouble(sVal);
2287 - 2548
 
2312 - 2549
                sVal = ini.IniReadValue("general", "LiPoCells");
2550
                _LipoCells = Convert.ToInt16(sVal);
2551
                sVal = ini.IniReadValue("general", "Motors");
2552
                if (sVal != "") _iMotors = Convert.ToInt16(sVal);
2287 - 2553
 
2312 - 2554
                sVal = ini.IniReadValue("map", "followMe");
2555
                if (sVal != "") _bFollowCopter = Convert.ToBoolean(sVal);
2556
                sVal = ini.IniReadValue("map", "AutoSetHome");
2557
                if (sVal != "") _bAutoHome = Convert.ToBoolean(sVal);
2324 - 2558
                sVal = ini.IniReadValue("map", "GPXLog");
2559
                if (sVal != "") _bGPXLog = Convert.ToBoolean(sVal);
2287 - 2560
 
2312 - 2561
                sVal = ini.IniReadValue("threshold", "VoltageWarning");
2562
                if(sVal != "") _dThresholdVoltageWarn = Convert.ToDouble(sVal);
2563
                sVal = ini.IniReadValue("threshold", "VoltageCritical");
2564
                if(sVal != "") _dThresholdVoltageCrit = Convert.ToDouble(sVal);
2565
                sVal = ini.IniReadValue("threshold", "VoiceVoltageEnable");
2566
                if(sVal != "") _bVoiceVoltPlay = Convert.ToBoolean(sVal);
2567
                sVal = ini.IniReadValue("threshold", "VoiceSatFixEnable");
2568
                if(sVal != "") _bVoiceSatFixPlay = Convert.ToBoolean(sVal);
2569
                sVal = ini.IniReadValue("threshold", "VoiceMagFieldEnable");
2570
                if(sVal != "") _bVoiceMagneticFieldPlay = Convert.ToBoolean(sVal);
2571
                sVal = ini.IniReadValue("threshold", "DistanceWarning");
2572
                if(sVal != "") _dThresholdDistanceWarn = Convert.ToDouble(sVal);
2573
                sVal = ini.IniReadValue("threshold", "VoiceDistanceWarnEnable");
2574
                if(sVal != "") _bVoiceDistancePlay = Convert.ToBoolean(sVal);
2575
                sVal = ini.IniReadValue("threshold", "VoiceRCLevelWarnEnable");
2576
                if(sVal != "") _bVoiceRCLevelPlay = Convert.ToBoolean(sVal);
2577
                sVal = ini.IniReadValue("threshold", "MaxDistance");
2578
                if(sVal != "") _dThresholdDistanceMax = Convert.ToDouble(sVal);
2579
                sVal = ini.IniReadValue("threshold", "RCThreshold");
2580
                if(sVal != "") _iThresholdRC = Convert.ToInt32(sVal);
2581
                sVal = ini.IniReadValue("threshold", "MagFieldThreshold");
2582
                if(sVal != "") _iThresholdMagField = Convert.ToInt32(sVal);
2321 - 2583
 
2584
                sVal = ini.IniReadValue("waypoints", "wpcolor");
2585
                if(sVal != "") comboBoxWPColor.SelectedIndex = Convert.ToInt32(sVal);
2586
                sVal = ini.IniReadValue("waypoints", "poicolor");
2587
                if(sVal != "") comboBoxPOIColor.SelectedIndex = Convert.ToInt32(sVal);
2588
                sVal = ini.IniReadValue("waypoints", "fscolor");
2589
                if(sVal != "") comboBoxFSColor.SelectedIndex = Convert.ToInt32(sVal);
2590
                sVal = ini.IniReadValue("waypoints", "coptercolor");
2591
                if(sVal != "") comboBoxCopterColor.SelectedIndex = Convert.ToInt32(sVal);
2328 - 2592
                sVal = ini.IniReadValue("waypoints", "routecolor");
2593
                if(sVal != "") comboBoxRouteColor.SelectedIndex = Convert.ToInt32(sVal);
2594
                sVal = ini.IniReadValue("waypoints", "showWPRoute");
2595
                if(sVal != "") _bShowWPRoute = Convert.ToBoolean(sVal);
2312 - 2596
            }
2597
            catch (Exception e)
2598
            {
2287 - 2599
 
2312 - 2600
                MessageBox.Show("Error parsing ini-file!" + Environment.NewLine + e.Message,"Read ini-file" ,MessageBoxButton.OK,MessageBoxImage.Error);
2601
            }
2602
 
2287 - 2603
        }
2604
 
2605
        /// <summary>
2606
        /// save settings to ini-file
2607
        /// </summary>
2608
        void _writeIni()
2609
        {
2610
 
2611
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
2612
            ini.path = filePath + "\\MKLiveViewSettings.ini";
2613
 
2312 - 2614
            try
2615
            {
2287 - 2616
 
2312 - 2617
                ini.IniWriteValue("timings", "AutorefreshDebugData", _debugDataAutorefresh ? "true" : "false");
2618
                ini.IniWriteValue("timings", "AutorefreshNavCtrlData", _navCtrlDataAutorefresh ? "true" : "false");
2619
                ini.IniWriteValue("timings", "AutorefreshBLCtrlData", _blctrlDataAutorefresh ? "true" : "false");
2620
                ini.IniWriteValue("timings", "AutorefreshOSDData", _OSDAutorefresh ? "true" : "false");
2287 - 2621
 
2312 - 2622
                ini.IniWriteValue("timings", "IntervalDebugData", debugInterval.ToString());
2623
                ini.IniWriteValue("timings", "IntervalNavCtrlData", navctrlInterval.ToString());
2624
                ini.IniWriteValue("timings", "IntervalBLCtrlData", blctrlInterval.ToString());
2625
                ini.IniWriteValue("timings", "IntervalOSDData", OSDInterval.ToString());
2287 - 2626
 
2312 - 2627
                ini.IniWriteValue("general", "LiPoCells", _LipoCells.ToString());
2628
                ini.IniWriteValue("general", "Motors", _iMotors.ToString());
2287 - 2629
 
2312 - 2630
                ini.IniWriteValue("map", "followMe", _bFollowCopter.ToString());
2631
                ini.IniWriteValue("map", "AutoSetHome", _bAutoHome.ToString());
2324 - 2632
                ini.IniWriteValue("map", "GPXLog", _bGPXLog.ToString());
2287 - 2633
 
2312 - 2634
                ini.IniWriteValue("topBar", "voltage", chkBoxTopBarShowVoltage.IsChecked.ToString());
2635
                ini.IniWriteValue("topBar", "capacity", chkBoxTopBarShowCapacity.IsChecked.ToString());
2636
                ini.IniWriteValue("topBar", "current", chkBoxTopBarShowCurrent.IsChecked.ToString());
2637
                ini.IniWriteValue("topBar", "flightTime", chkBoxTopBarShowFlightTime.IsChecked.ToString());
2638
                ini.IniWriteValue("topBar", "distanceHP", chkBoxTopBarShowDistanceHP.IsChecked.ToString());
2639
                ini.IniWriteValue("topBar", "height", chkBoxTopBarShowHeight.IsChecked.ToString());
2640
                ini.IniWriteValue("topBar", "speed", chkBoxTopBarShowSpeed.IsChecked.ToString());
2641
                ini.IniWriteValue("topBar", "magneticField", chkBoxTopBarShowMF.IsChecked.ToString());
2642
                ini.IniWriteValue("topBar", "satellites", chkBoxTopBarShowSatellites.IsChecked.ToString());
2643
                ini.IniWriteValue("topBar", "rc", chkBoxTopBarShowRC.IsChecked.ToString());
2287 - 2644
 
2312 - 2645
                ini.IniWriteValue("style", "saveFullScreen", chkBoxSaveFullScreenState.IsChecked.ToString());
2646
                ini.IniWriteValue("style", "saveNormalState", chkBoxSaveNormalState.IsChecked.ToString());
2287 - 2647
 
2312 - 2648
                ini.IniWriteValue("style", "scaleNormalAll", scaleNormalAll.ToString());
2649
                ini.IniWriteValue("style", "scaleNormalTopBar", scaleNormalTopBar.ToString());
2650
                ini.IniWriteValue("style", "scaleNormalMotors", scaleNormalMotors.ToString());
2651
                ini.IniWriteValue("style", "scaleNormalOSD", scaleNormalOSD.ToString());
2652
                ini.IniWriteValue("style", "scaleNormalLOG", scaleNormalLOG.ToString());
2653
                ini.IniWriteValue("style", "scaleNormalHorizon", scaleNormalHorizon.ToString());
2287 - 2654
 
2312 - 2655
                ini.IniWriteValue("style", "scaleFullAll", scaleFullAll.ToString());
2656
                ini.IniWriteValue("style", "scaleFullTopBar", scaleFullTopBar.ToString());
2657
                ini.IniWriteValue("style", "scaleFullMotors", scaleFullMotors.ToString());
2658
                ini.IniWriteValue("style", "scaleFullOSD", scaleFullOSD.ToString());
2659
                ini.IniWriteValue("style", "scaleFullLOG", scaleFullLOG.ToString());
2660
                ini.IniWriteValue("style", "scaleFullHorizon", scaleFullHorizon.ToString());
2287 - 2661
 
2312 - 2662
                ini.IniWriteValue("style", "horizon", chkBoxShowHorizon.IsChecked.ToString());
2663
 
2664
                ini.IniWriteValue("threshold", "VoltageWarning", _dThresholdVoltageWarn.ToString());
2665
                ini.IniWriteValue("threshold", "VoltageCritical", _dThresholdVoltageCrit.ToString());
2666
                ini.IniWriteValue("threshold", "VoiceVoltageEnable", _bVoiceVoltPlay.ToString());
2667
                ini.IniWriteValue("threshold", "VoiceSatFixEnable", _bVoiceSatFixPlay.ToString());
2668
                ini.IniWriteValue("threshold", "VoiceMagFieldEnable", _bVoiceMagneticFieldPlay.ToString());
2669
                ini.IniWriteValue("threshold", "VoiceDistanceWarnEnable", _bVoiceDistancePlay.ToString());
2670
                ini.IniWriteValue("threshold", "VoiceRCLevelWarnEnable", _bVoiceRCLevelPlay.ToString());
2671
                ini.IniWriteValue("threshold", "DistanceWarning", _dThresholdDistanceWarn.ToString());
2672
                ini.IniWriteValue("threshold", "MaxDistance", _dThresholdDistanceMax.ToString());
2673
                ini.IniWriteValue("threshold", "RCThreshold", _iThresholdRC.ToString());
2674
                ini.IniWriteValue("threshold", "MagFieldThreshold", _iThresholdMagField.ToString());
2321 - 2675
 
2676
                ini.IniWriteValue("waypoints", "wpcolor", comboBoxWPColor.SelectedIndex.ToString());
2677
                ini.IniWriteValue("waypoints", "poicolor", comboBoxPOIColor.SelectedIndex.ToString());
2678
                ini.IniWriteValue("waypoints", "fscolor", comboBoxFSColor.SelectedIndex.ToString());
2679
                ini.IniWriteValue("waypoints", "coptercolor", comboBoxCopterColor.SelectedIndex.ToString());
2328 - 2680
                ini.IniWriteValue("waypoints", "routecolor", comboBoxRouteColor.SelectedIndex.ToString());
2681
                ini.IniWriteValue("waypoints", "showWPRoute", _bShowWPRoute.ToString());
2312 - 2682
            }
2683
            catch (Exception e)
2684
            {
2685
 
2686
                MessageBox.Show("Error writing ini-file!" + Environment.NewLine + "Please make sure that the programm is in a location where it is allowed to write" + Environment.NewLine + e.Message, "Write ini-file", MessageBoxButton.OK, MessageBoxImage.Error);
2687
            }
2287 - 2688
        }
2312 - 2689
 
2315 - 2690
        #region WP
2312 - 2691
        void _readWPLFile()
2692
        {
2693
            Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
2694
            fd.Filter = "Waypointlists | *.wpl";
2695
            fd.Multiselect = false;
2696
            if (fd.ShowDialog().Value)
2697
            {
2698
                string file = fd.SafeFileName;
2699
                IniFile ini = new IniFile(fd.SafeFileName);
2700
                ini.path = fd.FileName;
2701
 
2702
                try
2703
                {
2704
                    string sVal = ini.IniReadValue("General", "FileVersion");
2705
                    if (sVal == "")
2706
                        MessageBox.Show("The file has no version declared - can't go on...", "", MessageBoxButton.OK, MessageBoxImage.Information);
2707
                    else
2708
                    {
2709
                        if (Convert.ToInt16(sVal) < 3)
2710
                            MessageBox.Show("The file version is not supported - can't go on...", "", MessageBoxButton.OK, MessageBoxImage.Information);
2711
                        else
2712
                        {
2713
                            sVal = ini.IniReadValue("General", "NumberOfWaypoints");
2714
                            if (sVal == "")
2715
                                MessageBox.Show("The file has no number of waypoints declared - can't go on...", "", MessageBoxButton.OK, MessageBoxImage.Information);
2716
                            else
2717
                            {
2718
                                int wpnum = Convert.ToInt16(sVal);
2719
                                string wp;
2720
                                int i;
2313 - 2721
                                NumberFormatInfo nfi = new NumberFormatInfo();
2722
                                nfi.NumberDecimalSeparator = ".";
2312 - 2723
                                dtWaypoints.Rows.Clear();
2327 - 2724
                                //for(int k = 0; k < MainMap.Markers.Count;)
2725
                                //{
2726
                                //    GMapMarker p = MainMap.Markers[k];
2727
                                //    if (p.Shape.GetType() == typeof(CustomMarkerWP))
2728
                                //        MainMap.Markers.Remove(p);
2729
                                //    else
2730
                                //        k++;
2731
                                //}
2732
                                _clearMapMarkers(typeof(CustomMarkerWP));
2328 - 2733
                                wpList.Clear();
2734
                                if (mRouteWP != null)
2735
                                    MainMap.Markers.Remove(mRouteWP);
2736
                                Dispatcher.Invoke(() => lblWPRouteDistance.Content = "0 m");
2737
 
2312 - 2738
                                for (int k = 1; k <= wpnum; k++)
2739
                                {
2740
                                    DataRow dr = dtWaypoints.NewRow();
2741
                                    dr.ItemArray = new object[16];
2742
                                    object[] o = new object[16];
2743
                                    i = 0;
2744
                                    wp = "Point" + k.ToString();
2745
                                    o[i] = k;
2746
                                    i++;
2747
                                    sVal = ini.IniReadValue(wp, "Type");
2748
                                    if (sVal != "")
2315 - 2749
                                        o[i] = Convert.ToInt16(sVal) - 1;
2312 - 2750
                                    i++;
2751
                                    sVal = ini.IniReadValue(wp, "Prefix");
2752
                                    if (sVal != "")
2753
                                        o[i] = sVal == "0" ? "P" + k.ToString() : sVal + k.ToString();
2754
                                    i++;
2313 - 2755
                                    sVal = ini.IniReadValue(wp, "Latitude");
2312 - 2756
                                    if (sVal != "")
2313 - 2757
                                        o[i] = Convert.ToDouble(sVal, nfi);
2312 - 2758
                                    i++;
2313 - 2759
                                    sVal = ini.IniReadValue(wp, "Longitude");
2312 - 2760
                                    if (sVal != "")
2313 - 2761
                                        o[i] = Convert.ToDouble(sVal, nfi);
2312 - 2762
                                    i++;
2763
                                    sVal = ini.IniReadValue(wp, "Altitude");
2764
                                    if (sVal != "")
2313 - 2765
                                        o[i] = Convert.ToDouble(sVal, nfi);
2312 - 2766
                                    i++;
2767
                                    sVal = ini.IniReadValue(wp, "Heading");
2768
                                    if (sVal != "")
2769
                                        o[i] = Convert.ToInt16(sVal);
2770
                                    i++;
2771
                                    sVal = ini.IniReadValue(wp, "Speed");
2772
                                    if (sVal != "")
2315 - 2773
                                        o[i] = Convert.ToInt16(sVal);
2312 - 2774
                                    i++;
2775
                                    sVal = ini.IniReadValue(wp, "ClimbRate");
2776
                                    if (sVal != "")
2777
                                        o[i] = Convert.ToInt16(sVal);
2778
                                    i++;
2779
                                    sVal = ini.IniReadValue(wp, "Radius");
2780
                                    if (sVal != "")
2781
                                        o[i] = Convert.ToInt16(sVal);
2782
                                    i++;
2783
                                    sVal = ini.IniReadValue(wp, "DelayTime");
2784
                                    if (sVal != "")
2785
                                        o[i] = Convert.ToInt16(sVal);
2786
                                    i++;
2787
                                    sVal = ini.IniReadValue(wp, "AutoTrigger");
2788
                                    if (sVal != "")
2789
                                        o[i] = Convert.ToInt16(sVal); ;
2790
                                    i++;
2791
                                    sVal = ini.IniReadValue(wp, "CAM-Nick");
2792
                                    if (sVal != "")
2313 - 2793
                                        o[i] = Convert.ToInt16(sVal);
2312 - 2794
                                    i++;
2795
                                    o[i] = 0;
2796
                                    i++;
2797
                                    sVal = ini.IniReadValue(wp, "WP_Event_Channel_Value");
2798
                                    if (sVal != "")
2799
                                        o[i] = Convert.ToInt16(sVal);
2800
                                    i++;
2801
                                    o[i] = "New";
2802
 
2803
                                    dr.ItemArray = o;
2804
                                    dtWaypoints.Rows.Add(dr);
2315 - 2805
                                    GMapMarker wpMarker = new GMapMarker(new PointLatLng((double)o[3], (double)o[4]));
2806
                                    wpMarker.Shape = new CustomMarkerWP(this, wpMarker, (string)dr[2], (int)o[1]);
2328 - 2807
                                    wpMarker.Offset = new System.Windows.Point(-11.5, -11.5);
2808
                                    wpMarker.ZIndex = 100;
2315 - 2809
                                    _setMarkerColor(wpMarker, (int)o[1]);
2810
                                    MainMap.Markers.Add(wpMarker);
2328 - 2811
                                    if((int)o[1] == 0)
2812
                                        wpList.Add(new PointLatLng((double)o[3], (double)o[4]));
2315 - 2813
 
2312 - 2814
                                    Dispatcher.Invoke(() => lblWPIndex.Content = k.ToString());
2815
                                    Dispatcher.Invoke(() => lblWPCount.Content = k.ToString());
2816
                                    Dispatcher.Invoke(() => dgvWP.Items.Refresh());
2817
                                    Thread.Sleep(10);
2818
                                }
2328 - 2819
                                Dispatcher.Invoke(() =>
2820
                                {
2821
                                    if (comboBoxRouteColor.SelectionBoxItem != null)
2822
                                    {
2823
                                        string s = comboBoxRouteColor.SelectionBoxItem.ToString();
2824
                                        mRouteWP = new GMapRoute(wpList, _getBrush(s));
2825
                                    }
2826
                                    else
2827
                                        mRouteWP = new GMapRoute(wpList, null);
2828
 
2829
                                    if (_bShowWPRoute)
2830
                                        MainMap.Markers.Add(mRouteWP);
2831
                                });
2832
 
2833
                                MapRoute mr = new MapRoute(wpList, "WPList");
2834
                                Dispatcher.Invoke(() => lblWPRouteDistance.Content = (mr.Distance * 1000).ToString("0 m"));
2835
 
2312 - 2836
                            }
2837
                        }
2838
                    }
2839
 
2840
                }
2841
                catch (Exception e)
2842
                {
2843
 
2844
                    MessageBox.Show("Error parsing wpl-file!" + Environment.NewLine + e.Message, "Read wpl-file", MessageBoxButton.OK, MessageBoxImage.Error);
2845
                }
2846
 
2847
            }
2848
        }
2328 - 2849
        Brush _getBrush(string color)
2850
        {
2851
            switch (color)
2852
            {
2853
                case "red":
2854
                    return Brushes.Red;
2855
                case "green":
2856
                    return Brushes.Lime;
2857
                case "blue":
2858
                    return Brushes.Aqua;
2859
                case "pink":
2860
                    return Brushes.Magenta;
2861
                case "yellow":
2862
                    return Brushes.Yellow;
2863
                default:
2864
                    return Brushes.Magenta;
2865
            }
2866
        }
2315 - 2867
        void _setMarkerColor(GMapMarker wpMarker,int iType)
2868
        {
2869
            Dispatcher.Invoke(() =>
2870
            {
2871
                switch (iType)
2872
                {
2873
                    case 0:
2874
                        if (comboBoxWPColor.SelectionBoxItem != null)
2875
                        {
2876
                            string s = comboBoxWPColor.SelectionBoxItem.ToString();
2877
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
2878
                        }
2879
                        else
2880
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("red");
2881
                        break;
2882
                    case 1:
2883
                        if (comboBoxPOIColor.SelectionBoxItem != null)
2884
                        {
2885
                            string s = comboBoxPOIColor.SelectionBoxItem.ToString();
2886
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
2887
                        }
2888
                        else
2889
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("red");
2890
                        break;
2891
                    case 2:
2892
                        if (comboBoxFSColor.SelectionBoxItem != null)
2893
                        {
2894
                            string s = comboBoxFSColor.SelectionBoxItem.ToString();
2895
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
2896
                        }
2897
                        else
2898
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("red");
2899
                        break;
2900
                    default:
2901
                        ((CustomMarkerWP)(wpMarker.Shape)).setColor("red");
2902
                        break;
2903
                }
2904
            });
2312 - 2905
 
2315 - 2906
        }
2907
        private void comboBoxWPColor_DropDownClosed(object sender, EventArgs e)
2312 - 2908
        {
2315 - 2909
            Dispatcher.Invoke(() =>
2910
            {
2911
                if (comboBoxWPColor.SelectionBoxItem != null)
2912
                {
2913
                    for (int k = 0; k < MainMap.Markers.Count;k++)
2914
                    {
2915
                        GMapMarker p = MainMap.Markers[k];
2916
                        if (p.Shape.GetType() == typeof(CustomMarkerWP))
2917
                        {
2918
                            if (((CustomMarkerWP)p.Shape).WPType == 0)
2919
                            {
2920
                                string s = comboBoxWPColor.SelectionBoxItem.ToString();
2921
                                ((CustomMarkerWP)(p.Shape)).setColor(s);
2922
                            }
2923
                        }
2924
                    }
2925
                }
2926
            });
2312 - 2927
        }
2315 - 2928
        private void comboBoxPOIColor_DropDownClosed(object sender, EventArgs e)
2929
        {
2930
            Dispatcher.Invoke(() =>
2931
            {
2932
                if (comboBoxPOIColor.SelectionBoxItem != null)
2933
                {
2934
                    for (int k = 0; k < MainMap.Markers.Count; k++)
2935
                    {
2936
                        GMapMarker p = MainMap.Markers[k];
2937
                        if (p.Shape.GetType() == typeof(CustomMarkerWP))
2938
                        {
2939
                            if (((CustomMarkerWP)p.Shape).WPType == 1)
2940
                            {
2941
                                string s = comboBoxPOIColor.SelectionBoxItem.ToString();
2942
                                ((CustomMarkerWP)(p.Shape)).setColor(s);
2943
                            }
2944
                        }
2945
                    }
2946
                }
2947
            });
2287 - 2948
 
2315 - 2949
        }
2950
        private void comboBoxFSColor_DropDownClosed(object sender, EventArgs e)
2287 - 2951
        {
2315 - 2952
            Dispatcher.Invoke(() =>
2953
            {
2954
                if (comboBoxFSColor.SelectionBoxItem != null)
2955
                {
2956
                    for (int k = 0; k < MainMap.Markers.Count; k++)
2957
                    {
2958
                        GMapMarker p = MainMap.Markers[k];
2959
                        if (p.Shape.GetType() == typeof(CustomMarkerWP))
2960
                        {
2961
                            if (((CustomMarkerWP)p.Shape).WPType == 2)
2962
                            {
2963
                                string s = comboBoxFSColor.SelectionBoxItem.ToString();
2964
                                ((CustomMarkerWP)(p.Shape)).setColor(s);
2965
                            }
2966
                        }
2967
                    }
2968
                }
2969
            });
2287 - 2970
        }
2318 - 2971
        private void comboBoxCopterColor_DropDownClosed(object sender, EventArgs e)
2972
        {
2973
            Dispatcher.Invoke(() => {
2974
                if (comboBoxCopterColor.SelectionBoxItem != null)
2975
                {
2976
                    string s = comboBoxCopterColor.SelectionBoxItem.ToString();
2977
                    ((CustomMarkerCopter)(copter.Shape)).setColor(s);
2978
                }
2979
                else
2980
                    ((CustomMarkerCopter)(copter.Shape)).setColor("red");
2981
            });
2982
        }
2328 - 2983
        private void comboBoxRouteColor_DropDownClosed(object sender, EventArgs e)
2984
        {
2985
            Dispatcher.Invoke(() =>
2986
            {
2987
                if (comboBoxRouteColor.SelectionBoxItem != null)
2988
                {
2989
                    string s = comboBoxRouteColor.SelectionBoxItem.ToString();
2990
                    MainMap.Markers.Remove(mRouteWP);
2991
                    mRouteWP = new GMapRoute(wpList, _getBrush(s));
2992
                    if (_bShowWPRoute)
2993
                        MainMap.Markers.Add(mRouteWP);
2994
                }
2995
            });
2996
        }
2997
        private void checkBoxShowWPRoute_Click(object sender, RoutedEventArgs e)
2998
        {
2999
            _bShowWPRoute = (bool)checkBoxShowWPRoute.IsChecked;
3000
            if (_bShowWPRoute)
3001
            {
3002
                if (mRouteWP != null)
3003
                    MainMap.Markers.Add(mRouteWP);
3004
            }
3005
            else
3006
            {
3007
                if (mRouteWP != null)
3008
                    MainMap.Markers.Remove(mRouteWP);
3009
            }
3010
        }
2315 - 3011
        private void btnLoadWPLFile_Click(object sender, RoutedEventArgs e)
2287 - 3012
        {
2315 - 3013
            _readWPLFile();
2287 - 3014
        }
2335 - 3015
        private void btnClearWPList_Click(object sender, RoutedEventArgs e)
3016
        {
3017
            _clearMapMarkers(typeof(CustomMarkerWP));
3018
            wpList.Clear();
3019
            if (mRouteWP != null)
3020
                MainMap.Markers.Remove(mRouteWP);
3021
            dtWaypoints.Rows.Clear();
3022
            Dispatcher.Invoke(() => dgvWP.Items.Refresh());
3023
            Dispatcher.Invoke(() => lblWPIndex.Content = 0);
3024
            Dispatcher.Invoke(() => lblWPCount.Content = 0);
3025
            Dispatcher.Invoke(() => lblWPRouteDistance.Content = "0 m");
3026
        }
2315 - 3027
        #endregion WP
2335 - 3028
 
2324 - 3029
        #region GPX
3030
        private void checkBoxGPXLog_Click(object sender, RoutedEventArgs e)
3031
        {
3032
            _bGPXLog = (bool)checkBoxGPXLog.IsChecked;
3033
        }
3034
        void _gpxAdd(double lat,double lon, int elevation)
3035
        {
3036
            DataRow dr = dtGPX.NewRow();
3037
            dr[0] = dtGPX.Rows.Count - 1;
3038
            dr[1] = lat;
3039
            dr[2] = lon;
3040
            dr[3] = elevation;
3041
            dr[4] = DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture); //2011-01-14T01:59:01Z
3042
            dtGPX.Rows.Add(dr);
3043
        }
3044
        void _saveGPXLog()
3045
        {
3046
            if (!Directory.Exists("GPXLog"))
3047
                Directory.CreateDirectory("GPXLog");
3048
            string SaveFileName = "GPXLog\\" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".gpx";
3049
            XmlTextWriter myXmlTextWriter = null;
3050
            myXmlTextWriter = new XmlTextWriter(SaveFileName, null);
3051
            NumberFormatInfo nfi = new NumberFormatInfo();
3052
            nfi.NumberDecimalSeparator = ".";
2315 - 3053
 
2324 - 3054
            try
3055
            {
3056
                myXmlTextWriter.Formatting = Formatting.Indented;
3057
 
3058
                myXmlTextWriter.WriteStartDocument();
3059
 
3060
                myXmlTextWriter.WriteStartElement("gpx");
3061
 
3062
                myXmlTextWriter.WriteAttributeString("version", "1.0");
3063
                myXmlTextWriter.WriteAttributeString("creator", "MKLiveView v1.0");
3064
                myXmlTextWriter.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
3065
                myXmlTextWriter.WriteAttributeString("xmlns", "http://www.topografix.com/GPX/1/1");
3066
                myXmlTextWriter.WriteAttributeString("xsi:schemaLocation", "http://www.topografix.com/GPX/1/1/gpx.xsd");
3067
 
3068
                myXmlTextWriter.WriteElementString("time", DateTime.UtcNow.ToString("u", System.Globalization.CultureInfo.InvariantCulture));
3069
 
3070
                myXmlTextWriter.WriteStartElement("trk");
3071
                myXmlTextWriter.WriteStartElement("trkseg");
3072
                for(int i = 0; i< dtGPX.Rows.Count;i++)
3073
                {
3074
                    myXmlTextWriter.WriteStartElement("trkpt");
3075
                    myXmlTextWriter.WriteAttributeString("lat", dtGPX.Rows[i][1].ToString() != "" ? ((double)dtGPX.Rows[i][1]).ToString(nfi) : "");
3076
                    myXmlTextWriter.WriteAttributeString("lon", dtGPX.Rows[i][2].ToString() != "" ? ((double)dtGPX.Rows[i][2]).ToString(nfi) : "");
3077
                    myXmlTextWriter.WriteElementString("ele", dtGPX.Rows[i][3].ToString());
3078
                    myXmlTextWriter.WriteElementString("time", dtGPX.Rows[i][4].ToString());
3079
                    myXmlTextWriter.WriteEndElement();
3080
                }
3081
                myXmlTextWriter.WriteEndElement();
3082
                myXmlTextWriter.WriteEndElement();
3083
                myXmlTextWriter.WriteEndElement();
3084
            }
3085
            catch (Exception e)
3086
            {
3087
                Console.WriteLine("Exception: {0}", e.ToString());
3088
            }
3089
            finally
3090
            {
3091
                if (myXmlTextWriter != null)
3092
                {
3093
                    myXmlTextWriter.Close();
3094
                }
3095
            }
3096
        }
3097
 
3098
        private void btnLoadGPXLog_Click(object sender, RoutedEventArgs e)
3099
        {
3100
            _loadGPXLog();
3101
        }
3102
 
2327 - 3103
        private void btnClearRoute_Click(object sender, RoutedEventArgs e)
3104
        {
3105
            _clearMapMarkers(typeof(GMapRoute));
3106
        }
3107
 
2324 - 3108
        void _loadGPXLog()
3109
        {
3110
 
3111
            Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
3112
            fd.Filter = "GPX-Logfile | *.gpx";
3113
            fd.Multiselect = false;
3114
            if (fd.ShowDialog().Value)
3115
            {
3116
                string file = fd.FileName;
3117
                try
3118
                {
3119
                    XDocument gpxDoc = XDocument.Load(file);
3120
                    XNamespace gpx = XNamespace.Get("http://www.topografix.com/GPX/1/1");
3121
 
3122
                    NumberFormatInfo nfi = new NumberFormatInfo();
3123
                    nfi.NumberDecimalSeparator = ".";
3124
 
3125
                    var tracks = from track in gpxDoc.Descendants(gpx + "trk")
3126
                                 select new
3127
                                 {
3128
                                     Name = track.Element(gpx + "name") != null ? track.Element(gpx + "name").Value : null,
3129
                                     Segs = (
3130
                                         from trackpoint in track.Descendants(gpx + "trkpt")
3131
                                         select new
3132
                                         {
3133
                                             Latitude = trackpoint.Attribute("lat").Value,
3134
                                             Longitude = trackpoint.Attribute("lon").Value,
3135
                                             Elevation = trackpoint.Element(gpx + "ele") != null ?
3136
                                             trackpoint.Element(gpx + "ele").Value : null,
3137
                                             Time = trackpoint.Element(gpx + "time") != null ?
3138
                                             trackpoint.Element(gpx + "time").Value : null
3139
                                         }
3140
                                     )
3141
                                 };
3142
 
3143
                    List<PointLatLng> wpl = new List<PointLatLng>();
3144
                    foreach(var trk in tracks)
3145
                    {
3146
                        foreach(var trkseg in trk.Segs)
3147
                        {
3148
                            if(trkseg.Latitude != "" && trkseg.Longitude !="")
3149
                            wpl.Add(new PointLatLng(Convert.ToDouble(trkseg.Latitude, nfi), Convert.ToDouble(trkseg.Longitude, nfi)));
3150
                        }
3151
 
3152
                    }
3153
                    if(wpl.Count() > 0)
3154
                    {
2327 - 3155
                        _clearMapMarkers(typeof(GMapRoute));
3156
                        //for (int k = 0; k < MainMap.Markers.Count;)
3157
                        //{
3158
                        //    GMapMarker p = MainMap.Markers[k];
3159
                        //    if (p.Shape.GetType() == typeof(GMapRoute))
3160
                        //        MainMap.Markers.Remove(p);
3161
                        //    else
3162
                        //        k++;
3163
                        //}
2324 - 3164
                        MapRoute mr = new MapRoute(wpl, "flying");
2328 - 3165
                        Dispatcher.Invoke(() =>
3166
                        {
3167
                            GMapRoute mRoute;
3168
                            if (comboBoxRouteColor.SelectionBoxItem != null)
3169
                            {
3170
                                string s = comboBoxRouteColor.SelectionBoxItem.ToString();
3171
                                mRoute = new GMapRoute(wpList, _getBrush(s));
3172
                            }
3173
                            else
3174
                                mRoute = new GMapRoute(wpList, null);
2324 - 3175
 
2328 - 3176
                            MainMap.Markers.Add(mRoute);
3177
                        });
2324 - 3178
                    }
3179
 
3180
                }
3181
                catch (Exception e)
3182
                {
3183
                    Console.WriteLine("Exception: {0}", e.ToString());
3184
                }
3185
            }
3186
        }
3187
        #endregion GPX
2315 - 3188
        #endregion functions
2287 - 3189
    }
2315 - 3190
     /// <summary>
3191
    /// formats the wp datatable values for display in datagrid - this is bound in the datagrid as a converter
3192
    /// </summary>
2313 - 3193
    public class waypointsConverter : IValueConverter
3194
    {
3195
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
3196
        {
3197
            if (value != null)
3198
            {
3199
                switch ((string)parameter)
3200
                {
3201
                    case "Latitude":
3202
                        return value.ToString() + " °";
3203
                    case "Longitude":
3204
                        return value.ToString() + " °";
3205
                    case "Radius":
3206
                        return value.ToString() + " m";
3207
                    case "Altitude":
3208
                        return value.ToString() + " m";
3209
                    case "ClimbRate":
3210
                        return value.ToString() == "255" ? "Auto" : (System.Convert.ToDouble(value) / 10).ToString("0.0 m/s");
3211
                    case "DelayTime":
3212
                        return value.ToString() + " s";
3213
                    case "Heading":
3214
                        return Waypoints.Heading(System.Convert.ToInt32(value));
3215
                    case "Speed":
3216
                        return Waypoints.WPSpeed(System.Convert.ToInt16(value));
3217
                    case "CamAngle":
3218
                        return Waypoints.CAMAngle(System.Convert.ToInt16(value));
3219
                    case "Type":
3220
                        return ((Waypoints.pointType)(System.Convert.ToInt16(value))).ToString();
3221
                    case "AutoTrigger":
3222
                        return value.ToString() == "0" ? "- - -" : value.ToString() + " m";
3223
                    case "Status":
3224
                        return Waypoints.WPSpeed(System.Convert.ToInt16(value));
3225
                }
3226
 
3227
                return value.ToString();
3228
            }
3229
            else return value;
3230
        }
3231
 
3232
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
3233
        {
3234
            throw new NotImplementedException();
3235
        }
3236
    }
3237
 
2287 - 3238
    public class IniFile
3239
    {
3240
        public string path;
3241
 
3242
        [DllImport("kernel32")]
3243
        private static extern long WritePrivateProfileString(string section,
3244
          string key, string val, string filePath);
3245
 
3246
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
3247
        static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
3248
               uint nSize, string lpFileName);
3249
 
3250
        [DllImport("kernel32")]
3251
        private static extern int GetPrivateProfileString(string section,
3252
          string key, string def, StringBuilder retVal,
3253
          int size, string filePath);
3254
 
3255
        public IniFile(string INIPath)
3256
        {
3257
            path = INIPath;
3258
        }
3259
 
3260
        public void IniWriteValue(string Section, string Key, string Value)
3261
        {
3262
            WritePrivateProfileString(Section, Key, Value, this.path);
3263
        }
3264
 
3265
        public string IniReadValue(string Section, string Key)
3266
        {
3267
            StringBuilder temp = new StringBuilder(255);
3268
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
3269
            return temp.ToString();
3270
        }
3271
        //Ini_sections auslesen in String-Array
3272
        public string[] IniSectionNames()
3273
        {
3274
 
3275
            //  uint MAX_BUFFER = 32767;
3276
            uint MAX_BUFFER = 8388608;
3277
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
3278
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, this.path);
3279
            if (bytesReturned == 0)
3280
            {
3281
                Marshal.FreeCoTaskMem(pReturnedString);
3282
                return null;
3283
            }
3284
            string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
3285
            Marshal.FreeCoTaskMem(pReturnedString);
3286
            //use of Substring below removes terminating null for split
3287
            return local.Substring(0, local.Length - 1).Split('\0');
3288
 
3289
 
3290
        }
3291
    }
3292
 
3293
    /// <summary>
3294
    /// Selected Win AI Function Calls
3295
    /// </summary>
3296
    public class WinApi
3297
    {
3298
        [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
3299
        public static extern int GetSystemMetrics(int which);
3300
        [DllImport("user32.dll")]
3301
        public static extern void
3302
                SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
3303
                             int X, int Y, int width, int height, uint flags);
3304
 
3305
        private const int SM_CXSCREEN = 0;
3306
        private const int SM_CYSCREEN = 1;
3307
        private static IntPtr HWND_TOP = IntPtr.Zero;
3308
        private const int SWP_SHOWWINDOW = 64; // 0x0040
3309
 
3310
        public static int ScreenX
3311
        {
3312
            get { return GetSystemMetrics(SM_CXSCREEN); }
3313
        }
3314
 
3315
        public static int ScreenY
3316
        {
3317
            get { return GetSystemMetrics(SM_CYSCREEN); }
3318
        }
3319
 
3320
        public static void SetWinFullScreen(IntPtr hwnd)
3321
        {
3322
            SetWindowPos(hwnd, HWND_TOP, -8, -7, ScreenX+15, ScreenY+14, SWP_SHOWWINDOW);
3323
        }
3324
    }
3325
    /// <summary>
3326
    /// Class used to preserve / restore state of the window
3327
    /// </summary>
3328
    public class WinState
3329
    {
3330
        private WindowState winState;
3331
        private WindowStyle brdStyle;
3332
        private bool topMost;
3333
        private Rect restore;
3334
        private bool IsMaximized = false;
3335
 
3336
        public bool isMaximized
3337
        {
3338
            get { return IsMaximized; }
3339
        }
3340
        public void Maximize(Window targetForm)
3341
        {
3342
            if (!IsMaximized)
3343
            {
3344
                IsMaximized = true;
3345
                Save(targetForm);
3346
                targetForm.WindowState = WindowState.Maximized;
3347
                targetForm.WindowStyle = WindowStyle.None;
3348
                targetForm.Topmost = true;
3349
                WinApi.SetWinFullScreen(new WindowInteropHelper(targetForm).Handle);
3350
            }
3351
        }
3352
 
3353
        public void Save(Window targetForm)
3354
        {
3355
            winState = targetForm.WindowState;
3356
            brdStyle = targetForm.WindowStyle;
3357
            topMost = targetForm.Topmost;
3358
            restore = targetForm.RestoreBounds;
3359
        }
3360
        public void Restore(Window targetForm)
3361
        {
3362
            targetForm.WindowState = winState;
3363
            targetForm.WindowStyle = brdStyle;
3364
            targetForm.Topmost = topMost;
3365
 
3366
            targetForm.Left = restore.Left;
3367
            targetForm.Top = restore.Top;
3368
            targetForm.Height = restore.Height;
3369
            targetForm.Width = restore.Width;
3370
            IsMaximized = false;
3371
        }
3372
    }
3373
 
3374
}