Subversion Repositories Projects

Rev

Rev 2372 | 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;
2342 - 48
        GMapMarker wpActiveMarker;
2328 - 49
        List<PointLatLng> wpList = new List<PointLatLng>();
2324 - 50
        #region NC-Errors
2287 - 51
        String[] NC_Error = new string[44]
52
        {
53
            "No Error",
54
            "FC not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A1_.22FC_not_compatible_.22",
55
            "MK3Mag not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A2_.22MK3Mag_not_compatible_.22",
56
            "no FC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A3_.22no_FC_communication_.22",
57
            "no compass communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A4_.22no_compass_communication_.22",
58
            "no GPS communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A5_.22no_GPS_communication_.22",
59
            "bad compass value" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A6_.22bad_compass_value.22",
60
            "RC Signal lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A7_.22RC_Signal_lost_.22",
61
            "FC spi rx error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A8_.22FC_spi_rx_error_.22",
62
            "ERR: no NC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A9:_.22ERR:_no_NC_communication.22",
63
            "ERR: FC Nick Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A10_.22ERR:_FC_Nick_Gyro.22",
64
            "ERR: FC Roll Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A11_.22ERR:_FC_Roll_Gyro.22",
65
            "ERR: FC Yaw Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A12_.22ERR:_FC_Yaw_Gyro.22",
66
            "ERR: FC Nick ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A13_.22ERR:_FC_Nick_ACC.22",
67
            "ERR: FC Roll ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A14_.22ERR:_FC_Roll_ACC.22",
68
            "ERR: FC Z-ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A15_.22ERR:_FC_Z-ACC.22",
69
            "ERR: Pressure sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A16_.22ERR:_Pressure_sensor.22",
70
            "ERR: FC I2C" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A17_.22ERR:_FC_I2C.22",
71
            "ERR: Bl Missing" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A18_.22ERR:_Bl_Missing.22",
72
            "Mixer Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A19_.22Mixer_Error.22",
73
            "FC: Carefree Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A20_.22FC:_Carefree_Error.22",
74
            "ERR: GPS lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A21_.22ERR:_GPS_lost.22",
75
            "ERR: Magnet Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A22_.22ERR:_Magnet_Error.22",
76
            "Motor restart" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A23_.22Motor_restart.22",
77
            "BL Limitation" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A24_.22BL_Limitation.22",
78
            "Waypoint range" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A25_.22Waypoint_range.22",
79
            "ERR:No SD-Card" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A26_.22ERR:No_SD-Card.22",
80
            "ERR:SD Logging aborted" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A27_.22ERR:SD_Logging_aborted.22",
81
            "ERR:Flying range!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A28_.22ERR:Flying_range.21.22",
82
            "ERR:Max Altitude" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A29_.22ERR:Max_Altitude.22",
83
            "No GPS Fix" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A30_.22No_GPS_Fix.22",
84
            "compass not calibrated" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A31_.22compass_not_calibrated.22",
85
            "ERR:BL selftest" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A32_.22ERR:BL_selftest.22",
86
            "no ext. compass" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A33_.22no_ext._compass.22",
87
            "compass sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A34_.22compass_sensor.22",
88
            "FAILSAFE pos.!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A35_.22FAILSAFE_pos..21__.22",
89
            "ERR:Redundancy" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A36_.22ERR:Redundancy__.22",
90
            "Redundancy test" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A37_.22Redundancy_test_.22",
91
            "GPS Update rate" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A38_.22GPS_Update_rate.22",
92
            "ERR:Canbus" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A39_.22ERR:Canbus.22",
93
            "ERR: 5V RC-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A40_.22ERR:_5V_RC-Supply.22",
94
            "ERR:Power-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A41_.22ERR:Power-Supply.22",
95
            "ACC not calibr." + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A42_.22ACC_not_calibr..22",
96
            "ERR:Parachute!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A43_.22ERR:Parachute.21.22"
97
        };
2324 - 98
        #endregion NC-Errors
2287 - 99
        [FlagsAttribute]
100
        enum NC_HWError0 : short
101
        {
102
            None = 0,
103
            SPI_RX = 1,
104
            COMPASS_RX = 2,
105
            FC_INCOMPATIBLE = 4,
106
            COMPASS_INCOMPATIBLE = 8,
107
            GPS_RX = 16,
108
            COMPASS_VALUE = 32
109
        };
110
        [FlagsAttribute]
111
        enum FC_HWError0 : short
112
        {
113
            None = 0,
114
            GYRO_NICK = 1,
115
            GYRO_ROLL = 2,
116
            GYRO_YAW = 4,
117
            ACC_NICK = 8,
118
            ACC_ROLL = 16,
119
            ACC_TOP = 32,
120
            PRESSURE = 64,
121
            CAREFREE = 128
122
        };
123
        [FlagsAttribute]
124
        enum FC_HWError1 : short
125
        {
126
            None = 0,
127
            I2C = 1,
128
            BL_MISSING = 2,
129
            SPI_RX = 4,
130
            PPM = 8,
131
            MIXER = 16,
132
            RC_VOLTAGE = 32,
133
            ACC_NOT_CAL = 64,
134
            RES3 = 128
135
        };
136
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
137
        // Various colors for logging info
138
        private Color[] LogMsgTypeColor = { Color.FromArgb(255, 43, 145, 175), Colors.Green, Colors.Black, Colors.Orange, Colors.Red };
139
 
140
        bool _bCBInit = true;
141
        bool _init = true;
142
        bool check_HWError = false;
143
 
144
        string filePath = Directory.GetCurrentDirectory();
145
        bool bReadContinously = false;
146
        bool _debugDataAutorefresh = true;
147
        bool _navCtrlDataAutorefresh = true;
148
        bool _blctrlDataAutorefresh = true;
149
        bool _OSDAutorefresh = true;
150
        bool _bErrorLog = false;
151
        bool _bConnErr = false;
152
        bool _bFollowCopter = false;
2324 - 153
        bool _bGPXLog = false;
2376 - 154
        bool _Simulate = false;
2287 - 155
 
156
        bool _bSaveWinStateNormal = true;
157
        bool _bSaveWinStateFull = true;
158
 
159
        double scaleNormalAll = 1;
160
        double scaleNormalTopBar = 1;
161
        double scaleNormalMotors = 1;
162
        double scaleNormalOSD = 1;
163
        double scaleNormalLOG = 1;
164
        double scaleNormalHorizon = 1;
165
 
166
        double scaleFullAll = 1;
167
        double scaleFullTopBar = 1;
168
        double scaleFullMotors = 1;
169
        double scaleFullOSD = 1;
170
        double scaleFullLOG = 1;
171
        double scaleFullHorizon = 1;
172
 
173
        int _iCtrlAct = 0;
174
        int iOSDPage = 0;
175
        int iOSDMax = 0;
176
        int _iLifeCounter = 0;
177
        int crcError = 0;
178
 
2291 - 179
        bool _bSatFix = false;
180
        Storyboard stbSatFixLostAnim;
181
        bool _bAnimSatFixActive = false;
182
        bool _bVoiceSatFixActive = false;
183
        bool _bVoiceSatFixPlay = false;
184
        int _iSatsLast = 0;
185
        int _iSatsJitter = 0;
186
 
187
        bool _bMagneticFieldOK = false;
188
        Storyboard stbMagneticFieldAnim;
189
        bool _bAnimMagneticFieldActive = false;
190
        bool _bVoiceMagneticFieldActive = false;
191
        bool _bVoiceMagneticFieldPlay = false;
192
        int _iMagneticFieldLast = 0;
193
        int _iMagneticFieldJitter = 0;
194
 
195
        bool _bRCLevelOK = false;
196
        Storyboard stbRCLevelAnim;
197
        bool _bAnimRCLevelActive = false;
198
        bool _bVoiceRCLevelActive = false;
199
        bool _bVoiceRCLevelPlay = false;
200
        int _iRCLevelLast = 0;
201
        int _iRCLevelJitter = 0;
202
 
2287 - 203
        int _iMotors = 4;
204
        int _LipoCells = 4;
205
 
206
        double _dLipoVMax = 16.88;
207
        double _dLipoVMin = 12;
208
        double _dThresholdVoltageWarn = 0;
209
        double _dThresholdVoltageCrit = 0;
210
        Storyboard stbVoltageCritAnim;
211
        bool _bCritAnimVoltActive = false;
212
        bool _bCritVoiceVoltActive = false;
2291 - 213
        bool _bWarnVoiceVoltActive = false;
2287 - 214
        bool _bVoiceVoltPlay = false;
215
        double _dVoltLast = 0;
216
        int _iVoltJitter = 0;
217
 
2291 - 218
        double _dThresholdDistanceWarn = 100;
219
        Storyboard stbDistanceWarnAnim;
220
        bool _bAnimDistanceActive = false;
221
        bool _bVoiceDistanceActive = false;
222
        bool _bVoiceDistancePlay = false;
223
        double _dDistanceLast = 0;
224
        int _iDistanceJitter = 0;
225
 
226
        double _dThresholdDistanceMax = 1000;
227
        int _iThresholdRC = 160;
228
        int _iThresholdMagField = 15;
229
 
2295 - 230
        bool _bAutoHome = false;
231
        bool _bFirstSatFix = false;
232
        int _iFirstSatFix = 0;
2291 - 233
 
2287 - 234
        double _dTopHeight = 36;
235
 
236
        int[] serChan = new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
237
        int[] serChan_sub = new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
238
        string[] serChanTitle = new string[12];
239
 
240
        string[] sAnalogLabel = new string[32];
241
        string[] sAnalogData = new string[32];
2324 - 242
        int[] iAnalogData = new int[32];
2287 - 243
 
244
        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 };
245
        int[] iMotors = new int[] {3,4,5,6,7,8,9,10,11,12 };
246
        string[] sLiPoCells = new string[] { "3s", "4s", "5s", "6s" };
247
        /// <summary>
248
        /// interval for sending debugdata (multiplied by 10ms)
249
        /// </summary>
250
        byte debugInterval = 10; //(=> 100ms)
251
        /// <summary>
252
        /// interval for sending BL-CTRL status (multiplied by 10ms)
253
        /// </summary>
254
        byte blctrlInterval = 75;
255
        /// <summary>
256
        /// interval for sending NAV-CTRL status (multiplied by 10ms)
257
        /// </summary>
258
        byte navctrlInterval = 80;
259
        /// <summary>
260
        /// interval for sending OSD page update (multiplied by 10ms)
261
        /// </summary>
262
        byte OSDInterval = 85;
263
        /// <summary>
264
        /// datatable for the debug data array - displayed on settings tabpage in datagridview
265
        /// </summary>
266
        DataTable dtAnalog = new DataTable();
267
        /// <summary>
268
        /// datatable for motordata (current,temp)
269
        /// </summary>
2315 - 270
        DataTable dtMotors = new DataTable();
2287 - 271
 
272
        DataTable dtWaypoints = new DataTable();
2313 - 273
        static volatile int _iWPCount = -1;
274
        static volatile int _iWPIndex = -1;
275
        int _iWPTimeout = 1000;
2287 - 276
        bool _bGetWP = false;
2328 - 277
        bool _bShowWPRoute = false;
2287 - 278
        static volatile bool _bGetWPCount = false;
2324 - 279
        DataTable dtGPX = new DataTable();
280
        DataRow drGPX;
281
        bool _bAirborne = false;
2355 - 282
        int _wpIndex = -1, _wpCount = 0, _wpEdit = -1;
2340 - 283
 
2287 - 284
        DispatcherTimer timer = new DispatcherTimer();
285
 
286
        /// <summary>
287
        /// stuff for enabeling touch zoom for the map
288
        /// </summary>
289
        Point pTouch1 = new Point(0,0), pTouch2 = new Point(0,0);
290
        int iFirstStylusID = -1;
291
        public string connectButtonText
292
        {
293
            get
294
            {
295
                return bReadContinously ? "stop polling data" + System.Environment.NewLine + "from copter" : "start polling data" + System.Environment.NewLine + "from copter";
296
            }
297
        }
298
 
299
        WinState winState = new WinState();
2304 - 300
        #endregion declarations
2287 - 301
        public MainWindow()
302
        {
303
            InitializeComponent();
304
            _initForm();
305
            _dataTablesInit();
306
            _setupMap();
307
            _init = false;
308
            timer.Tick += new EventHandler(timerEvent);
309
            timer.Interval = new TimeSpan(0, 0, 1);
310
            timer.Start();
311
        }
312
 
313
        #region init
314
        void _initForm()
315
        {
316
            _readIni();
317
            if (_bSaveWinStateNormal)
318
                _setScaleSliders(false);
319
            cBoxTimingsDebug.ItemsSource =
320
                cBoxTimingsNav.ItemsSource =
321
                cBoxTimingsBl.ItemsSource =
322
                cBoxTimingsOSD.ItemsSource =
323
                iTimings;
324
            cBoxLiPoCells.ItemsSource = sLiPoCells;
325
            cBoxLiPoCells.SelectedItem = _LipoCells.ToString() + "s";
326
            _LipoMinMax();
327
            sliderThresholdVoltageWarn.Value = _dThresholdVoltageWarn;
328
            sliderThresholdVoltageCrit.Value = _dThresholdVoltageCrit;
329
            checkBoxThresholdVoltageVoice.IsChecked = _bVoiceVoltPlay;
2291 - 330
            checkBoxSatfixLost.IsChecked = _bVoiceSatFixPlay;
331
            checkBoxMagneticField.IsChecked = _bVoiceMagneticFieldPlay;
332
            checkBoxThresholdDistanceVoice.IsChecked = _bVoiceDistancePlay;
333
            sliderThresholdDistanceWarn.Value = _dThresholdDistanceWarn;
334
            checkBoxRClevel.IsChecked = _bVoiceRCLevelPlay;
2287 - 335
 
2291 - 336
            sliderThresholdDistanceWarn.Maximum = _dThresholdDistanceMax;
337
 
2287 - 338
            cBoxMotors.ItemsSource = iMotors;
339
            cBoxMotors.SelectedItem = _iMotors;
340
 
341
            serialPortCtrl.PortClosed += serialPortCtrl_PortClosed;
342
            serialPortCtrl.PortOpened += serialPortCtrl_PortOpened;
343
            serialPortCtrl.DataReceived += processMessage;
344
 
345
            chkbAutoBL.IsChecked = _blctrlDataAutorefresh;
346
            chkbAutoDbg.IsChecked = _debugDataAutorefresh;
347
            chkbAutoNav.IsChecked = _navCtrlDataAutorefresh;
348
            chkbAutoOSD.IsChecked = _OSDAutorefresh;
349
 
350
            cBoxTimingsDebug.SelectedItem = debugInterval * 10;
351
            cBoxTimingsNav.SelectedItem = navctrlInterval * 10;
352
            cBoxTimingsBl.SelectedItem = blctrlInterval * 10;
353
            cBoxTimingsOSD.SelectedItem = OSDInterval * 10;
2295 - 354
            checkBoxAutoSetHP.IsChecked = _bAutoHome;
2287 - 355
            checkBoxFollowCopter.IsChecked = _bFollowCopter;
2324 - 356
            checkBoxGPXLog.IsChecked = _bGPXLog;
2328 - 357
            checkBoxShowWPRoute.IsChecked = _bShowWPRoute;
2287 - 358
 
2349 - 359
            _initSerialCtrl();
2287 - 360
        }
361
        /// <summary>
362
        /// initialize the datatables
363
        /// with columnnames etc
364
        /// </summary>
365
        void _dataTablesInit()
366
        {
2315 - 367
            dtMotors.Columns.Add("#");
2313 - 368
            if (Thread.CurrentThread.CurrentUICulture.Name == "de-DE")
2315 - 369
                dtMotors.Columns.Add("Strom");
2313 - 370
            else
2315 - 371
                dtMotors.Columns.Add("Current");
372
            dtMotors.Columns.Add("Temp");
373
            dgvMotors1.DataContext = dtMotors.DefaultView;
2287 - 374
            _initDTMotors();
375
 
376
            Setter setter = new Setter(ContentControl.PaddingProperty, new Thickness(5,0,5,0));
377
            Style style = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
378
            style.Setters.Add(setter);
379
            setter = new Setter(ContentControl.BackgroundProperty, new SolidColorBrush(Colors.Transparent));
380
            style.Setters.Add(setter);
381
            setter = new Setter(ContentControl.ForegroundProperty, new SolidColorBrush(Colors.White));
382
            style.Setters.Add(setter);
2313 - 383
 
384
            dtWaypoints.Columns.Add("Index",typeof(int));
2315 - 385
            dtWaypoints.Columns.Add("Type", typeof(int));
2313 - 386
            dtWaypoints.Columns.Add("Name",typeof(string));
2315 - 387
            dtWaypoints.Columns.Add("Latitude",typeof(double));
388
            dtWaypoints.Columns.Add("Longitude",typeof(double));
2313 - 389
            dtWaypoints.Columns.Add("Altitude",typeof(string));
390
            dtWaypoints.Columns.Add("Heading",typeof(string));
391
            dtWaypoints.Columns.Add("Speed",typeof(string));
392
            dtWaypoints.Columns.Add("ClimbRate",typeof(string));
393
            dtWaypoints.Columns.Add("Radius",typeof(string));
394
            dtWaypoints.Columns.Add("HoldTime",typeof(string));
395
            dtWaypoints.Columns.Add("AutoTrigger",typeof(string));
396
            dtWaypoints.Columns.Add("CamAngle",typeof(string));
397
            dtWaypoints.Columns.Add("Event",typeof(string));
398
            dtWaypoints.Columns.Add("Out1Timer",typeof(string));
399
            dtWaypoints.Columns.Add("Status",typeof(string));
400
            dtWaypoints.PrimaryKey = new DataColumn[] { dtWaypoints.Columns["Index"] };
401
            dgvWP.ItemsSource = dtWaypoints.DefaultView;
2287 - 402
            dgvWP.ColumnHeaderStyle = new Style();
403
            dgvWP.ColumnHeaderStyle = style;
2313 - 404
 
2324 - 405
            dtGPX.Columns.Add("Index",typeof(int));
406
            dtGPX.Columns.Add("Latitude",typeof(double));
407
            dtGPX.Columns.Add("Longitude",typeof(double));
408
            dtGPX.Columns.Add("Elevation",typeof(int));
409
            dtGPX.Columns.Add("Time",typeof(string));
410
            dtGPX.PrimaryKey = new DataColumn[] { dtGPX.Columns["Index"] };
411
            drGPX = dtGPX.NewRow();
2313 - 412
 
2287 - 413
        }
414
        /// <summary>
2315 - 415
        /// initialize the datatable dtMotors for motor values
2313 - 416
        /// DataGridView dgvMotors1 is bound to dtMotors1
2287 - 417
        /// </summary>
418
        void _initDTMotors()
419
        {
420
            for (int i = 0; i < 12; i++)
421
            {
2315 - 422
                if (dtMotors.Rows.Count < 12)
423
                    dtMotors.Rows.Add((i + 1).ToString(), "NA", "NA");
2287 - 424
                else
425
                {
2315 - 426
                    dtMotors.Rows[i].SetField(1, "NA");
427
                    dtMotors.Rows[i].SetField(2, "NA");
2287 - 428
                }
429
            }
430
        }
431
 
432
        #endregion init
433
 
434
        #region events
435
        private void serialPortCtrl_PortOpened()
436
        {
437
            Dispatcher.Invoke(() => imageWiFi.Source = new BitmapImage(new Uri("Images/WiFi_G.png", UriKind.Relative)));
438
            _getVersion();
439
            Thread.Sleep(100);
440
            //_OSDMenue(0);
441
            //Thread.Sleep(200);
442
            //_sendSerialData();
443
            _readCont(true);
444
        }
445
        private void serialPortCtrl_PortClosed()
446
        {
447
            Dispatcher.Invoke(() => imageWiFi.Source = new BitmapImage(new Uri("Images/WiFi_W.png", UriKind.Relative)));
448
            _readCont(false);
449
        }
2324 - 450
        bool _bToggle = false;
2287 - 451
        void timerEvent(object sender, EventArgs e)
452
        {
453
            if (bReadContinously)
454
            {
455
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
456
 
457
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
458
 
459
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
460
                check_HWError = true;
461
                _getVersion();
462
                Thread.Sleep(10);
463
                if (_OSDAutorefresh)
464
                {
465
                    if (iOSDMax == 0 | cbOSD.Items.Count != iOSDMax)
466
                        _initOSDCB();
467
                    _OSDMenueAutoRefresh();
468
                }
469
                if (_iLifeCounter > 0)
470
                {
471
                    Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_G.png", UriKind.Relative)));
472
                  //  Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.LightGreen));
473
                    _iLifeCounter = 0;
474
                    _bConnErr = false;
2327 - 475
                    if(_bAirborne && _bGPXLog)
2324 - 476
                    {
477
                        drGPX[0] = dtGPX.Rows.Count;
478
                        dtGPX.Rows.Add(new object[] { drGPX[0], drGPX[1], drGPX[2], drGPX[3], drGPX[4] });
479
                    }
2327 - 480
                    Dispatcher.Invoke((Action)(() => tbSideBarGPXLog.Background = (_bAirborne && _bGPXLog && _bToggle) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));
481
                    Dispatcher.Invoke((Action)(() => tbSideBarGPXLog.Foreground = (_bAirborne && _bGPXLog) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));
482
                    Dispatcher.Invoke((Action)(() => tbSideBarGPXLog.BorderBrush = (_bAirborne && _bGPXLog) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Color.FromArgb(255, 211, 210, 210))));
2324 - 483
                    _bToggle = !_bToggle;
2287 - 484
                }
485
                else
486
                {
487
                    if (!_bConnErr)
488
                    {
489
                        Log(LogMsgType.Error, "No communication to NC/FC!");
490
                        Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_R.png", UriKind.Relative)));
491
                       // Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.Red));
492
                        _bConnErr = true;
493
                    }
494
                }
495
            }
496
        }
497
 
498
        private void labelData_MouseDown(object sender, MouseButtonEventArgs e)
499
        {
500
            GridData.Visibility = GridData.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
501
            GridSettings.Visibility = GridWP.Visibility = Visibility.Collapsed;
502
        }
503
        private void labelMotorData_MouseDown(object sender, MouseButtonEventArgs e)
504
        {
505
            GridMotors.Visibility = GridMotors.Visibility == Visibility.Hidden ? Visibility.Visible : Visibility.Hidden;
506
            if (GridMotors.IsVisible)
507
                _setMotorGridSize();
508
        }
509
        private void labelSettings_MouseDown(object sender, MouseButtonEventArgs e)
510
        {
511
            GridData.Visibility = GridWP.Visibility = Visibility.Collapsed;
512
            GridSettings.Visibility = GridSettings.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
513
        }
514
        private void labelLog_MouseDown(object sender, MouseButtonEventArgs e)
515
        {
516
            GridLog.Visibility = GridLog.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
517
        }
518
        private void labelOSD_MouseDown(object sender, MouseButtonEventArgs e)
519
        {
520
            GridOSD.Visibility = GridOSD.Visibility == Visibility.Hidden ? Visibility.Visible : Visibility.Hidden;
521
        }
522
        private void labelWaypoints_MouseDown(object sender, MouseButtonEventArgs e)
523
        {
524
            GridData.Visibility = GridSettings.Visibility = Visibility.Collapsed;
525
            GridWP.Visibility = GridWP.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
526
        }
527
 
528
        private void btnGetWP_Click(object sender, RoutedEventArgs e)
529
        {
530
            Thread t = new Thread(new ThreadStart(_getWP));
531
            t.Start();
532
        }
533
        private void btnSendWPList_Click(object sender, RoutedEventArgs e)
534
        {
2313 - 535
            Thread t = new Thread(new ThreadStart(_sendWPList));
536
            t.Start();
2287 - 537
        }
538
 
539
        private void btnConnectToCopter_Click(object sender, RoutedEventArgs e)
540
        {
541
            if (!serialPortCtrl.Port.IsOpen)
542
                serialPortCtrl.Connect(true);
543
            else
544
                _readCont(!bReadContinously);
545
        }
546
        private void btnSetHP_Click(object sender, RoutedEventArgs e)
547
        {
2347 - 548
            _setHomePos();
2287 - 549
        }
550
        private void btnClearHP_Click(object sender, RoutedEventArgs e)
551
        {
2347 - 552
            _clearHomePos();
2287 - 553
        }
554
        private void btnGotoHP_Click(object sender, RoutedEventArgs e)
555
        {
556
            if (home != null && MainMap.Markers.Contains(home))
557
                MainMap.Position = home.Position;
558
        }
2295 - 559
        private void checkBoxAutoSetHP_Click(object sender, RoutedEventArgs e)
560
        {
561
            _bAutoHome = (bool)checkBoxAutoSetHP.IsChecked;
562
        }
2287 - 563
        private void chkBoxSaveNormalState_Click(object sender, RoutedEventArgs e)
564
        {
565
            _bSaveWinStateNormal = (bool)chkBoxSaveNormalState.IsChecked;
566
        }
567
        private void chkBoxSaveFullScreenState_Click(object sender, RoutedEventArgs e)
568
        {
569
            _bSaveWinStateFull = (bool)chkBoxSaveFullScreenState.IsChecked;
570
        }
571
 
2291 - 572
        #region thresholds
2287 - 573
        private void sliderThresholdVoltageWarn_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
574
        {
575
            if(!_init)
576
                _dThresholdVoltageWarn = sliderThresholdVoltageWarn.Value;
577
        }
578
        private void sliderThresholdVoltageCrit_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
579
        {
580
            if(!_init)
581
                _dThresholdVoltageCrit = sliderThresholdVoltageCrit.Value;
582
        }
583
        private void checkBoxThresholdVoltageVoice_Click(object sender, RoutedEventArgs e)
584
        {
585
            _bVoiceVoltPlay = (bool)checkBoxThresholdVoltageVoice.IsChecked;
586
        }
2291 - 587
 
588
        private void sliderThresholdDistanceWarn_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
589
        {
590
            if(!_init)
591
                _dThresholdDistanceWarn = sliderThresholdDistanceWarn.Value;
592
        }
593
        private void checkBoxThresholdDistanceVoice_Click(object sender, RoutedEventArgs e)
594
        {
595
            _bVoiceDistancePlay = (bool)checkBoxThresholdDistanceVoice.IsChecked;
596
        }
597
 
598
        private void checkBoxSatfixLost_Click(object sender, RoutedEventArgs e)
599
        {
600
            _bVoiceSatFixPlay = (bool)checkBoxSatfixLost.IsChecked;
601
        }
602
        private void checkBoxMagneticField_Click(object sender, RoutedEventArgs e)
603
        {
604
            _bVoiceMagneticFieldPlay = (bool)checkBoxMagneticField.IsChecked;
605
        }
606
        private void checkBoxRClevel_Click(object sender, RoutedEventArgs e)
607
        {
608
            _bVoiceRCLevelPlay = (bool)checkBoxRClevel.IsChecked;
609
        }
610
        #endregion thresholds
611
 
2287 - 612
        private void buttonSwitchNC_Click(object sender, RoutedEventArgs e)
613
        {
614
            _switchToNC();
615
        }
616
 
617
        private void Window_Loaded(object sender, RoutedEventArgs e)
618
        {
619
            stbVoltageCritAnim = TryFindResource("VoltageCritAnim") as Storyboard;
2291 - 620
            stbSatFixLostAnim = TryFindResource("SatFixLostAnim") as Storyboard;
621
            stbMagneticFieldAnim = TryFindResource("MagneticFieldCritAnim") as Storyboard;
622
            stbDistanceWarnAnim = TryFindResource("DistanceCritAnim") as Storyboard;
623
            stbRCLevelAnim = TryFindResource("RCCritAnim") as Storyboard;
2287 - 624
            _setMotorGridSize();
625
        }
2310 - 626
        private void Window_Closing(object sender, CancelEventArgs e)
627
        {
628
            _writeIni();
2324 - 629
            if(_bGPXLog && dtGPX.Rows.Count > 0)
630
                _saveGPXLog();
2310 - 631
        }
2287 - 632
        #endregion events
633
 
634
        #region GMap
635
 
636
        void _setupMap()
637
        {
638
            MainMap.Manager.Mode = AccessMode.ServerAndCache;
639
            MainMap.MapProvider = GMapProviders.BingHybridMap;
640
            MainMap.SetPositionByKeywords("Landshut");
641
            MainMap.MinZoom = 0;
642
            MainMap.MaxZoom = 24;
643
            MainMap.Zoom = 16;
644
            MainMap.ShowCenter = true;
645
            MainMap.ShowTileGridLines = false;
646
            sliderMapZoom.Value = 16;
647
            comboBoxMapType.ItemsSource = providerList;
648
            comboBoxMapType.DisplayMemberPath = "Name";
649
            comboBoxMapType.SelectedItem = MainMap.MapProvider;
650
 
651
            // acccess mode
652
            comboBoxMode.ItemsSource = Enum.GetValues(typeof(AccessMode));
653
            comboBoxMode.SelectedItem = MainMap.Manager.Mode;
654
 
655
        }
656
 
657
        /// <summary>
658
        /// selection of relevant map providers --> if You need more, You can change the line:
659
        ///     comboBoxMapType.ItemsSource = providerList; 
660
        /// to:
661
        ///     comboBoxMapType.ItemsSource = GMapProviders.List;
662
        /// in _setupMap()
663
        /// or add items here:
664
        /// </summary>
665
        List<GMap.NET.MapProviders.GMapProvider> providerList = new List<GMap.NET.MapProviders.GMapProvider>
666
        { GMap.NET.MapProviders.GMapProviders.OpenCycleMap, GMap.NET.MapProviders.GMapProviders.OpenCycleLandscapeMap, GMap.NET.MapProviders.GMapProviders.OpenCycleTransportMap,
667
        GMap.NET.MapProviders.GMapProviders.BingMap,GMap.NET.MapProviders.GMapProviders.BingSatelliteMap,GMap.NET.MapProviders.GMapProviders.BingHybridMap,
668
        GMap.NET.MapProviders.GMapProviders.GoogleMap,GMap.NET.MapProviders.GMapProviders.GoogleSatelliteMap,GMap.NET.MapProviders.GMapProviders.GoogleHybridMap,GMap.NET.MapProviders.GMapProviders.GoogleTerrainMap,
669
        GMap.NET.MapProviders.GMapProviders.OviMap,GMap.NET.MapProviders.GMapProviders.OviSatelliteMap,GMap.NET.MapProviders.GMapProviders.OviHybridMap,GMap.NET.MapProviders.GMapProviders.OviTerrainMap};
670
 
671
        private void MainMap_Loaded(object sender, RoutedEventArgs e)
672
        {
673
            MainMap.Manager.Mode = AccessMode.ServerAndCache;
674
            copter = new GMapMarker(MainMap.Position);
2318 - 675
 
676
            copter.Shape = new CustomMarkerCopter(this, copter, MainMap.Position.Lat.ToString("0.#######°") + System.Environment.NewLine + MainMap.Position.Lng.ToString("0.#######°"),"red");
677
            if (comboBoxCopterColor.SelectionBoxItem != null)
678
            {
679
                string s = comboBoxCopterColor.SelectionBoxItem.ToString();
680
                ((CustomMarkerCopter)(copter.Shape)).setColor(s);
681
            }
2287 - 682
            copter.Offset = new System.Windows.Point(-18, -18);
683
            copter.ZIndex = int.MaxValue;
684
            MainMap.Markers.Add(copter);
685
            copter.Position = MainMap.Position;
686
        }
2347 - 687
        void _setHomePos()
2287 - 688
        {
689
            pHome = MainMap.Position;
690
            if (!MainMap.Markers.Contains(home))
691
            {
692
                home = new GMapMarker(MainMap.Position);
693
                home.Shape = new CustomMarkerHome(this, home, MainMap.Position.Lat.ToString("0.#######°") + System.Environment.NewLine + MainMap.Position.Lng.ToString("0.#######°"));
694
                home.Offset = new System.Windows.Point(-18, -18);
695
                // home.ZIndex = int.MaxValue;
696
                MainMap.Markers.Add(home);
697
            }
698
            home.Position = MainMap.Position;
699
            ((CustomMarkerHome)(home.Shape)).setText(MainMap.Position.Lat.ToString("0.#######°") + System.Environment.NewLine + MainMap.Position.Lng.ToString("0.#######°"));
700
        }
2347 - 701
        void _setActiveWP(int iIndex)
2287 - 702
        {
2347 - 703
            if (wpActiveMarker == null || !MainMap.Markers.Contains(wpActiveMarker))
704
            {
705
                Dispatcher.Invoke(() =>
706
                {
707
                    wpActiveMarker = new GMapMarker(wpList[iIndex]);
708
                    wpActiveMarker.Shape = new CustomMarkerWPActive(this, wpActiveMarker, "wpActive", 0);
709
                    wpActiveMarker.Offset = new Point(-17.5, -17.5);
710
                    MainMap.Markers.Add(wpActiveMarker);
711
                });
712
            }
713
            else
714
                Dispatcher.Invoke(() => wpActiveMarker.Position = wpList[iIndex]);
715
 
716
        }
717
        void _clearHomePos()
718
        {
2287 - 719
            MainMap.Markers.Remove(home);
720
        }
2335 - 721
        void _clearMapMarkers(Type markerType)
722
        {
723
            for (int k = 0; k < MainMap.Markers.Count;)
724
            {
725
                GMapMarker p = MainMap.Markers[k];
2340 - 726
                if (p.GetType() == markerType | (p.Shape != null && p.Shape.GetType() == markerType))
2335 - 727
                    MainMap.Markers.Remove(p);
728
                else
729
                    k++;
730
            }
2287 - 731
 
2335 - 732
        }
2369 - 733
 
734
        GMapMarker _findWPMarker(string name)
2368 - 735
        {
736
            for (int k = 0; k < MainMap.Markers.Count;)
737
            {
738
                GMapMarker p = MainMap.Markers[k];
739
                if (p.GetType() == typeof(CustomMarkerWP) | (p.Shape != null && p.Shape.GetType() == typeof(CustomMarkerWP)))
2369 - 740
                    if (((CustomMarkerWP)p.Shape).WPText == name)
741
                        return p;
2368 - 742
                    else
743
                        k++;
744
                else
745
                    k++;
746
            }
2369 - 747
            return null;
2368 - 748
        }
2369 - 749
        void _clearWPMarker(string name)
750
        {
751
            GMapMarker p = _findWPMarker(name);
752
            if(p != null)
753
                MainMap.Markers.Remove(p);
754
        }
2368 - 755
        void _renameWPMarker(string s1, string s2)
756
        {
2369 - 757
            GMapMarker p = _findWPMarker(s1);
758
            if (p != null)
759
                ((CustomMarkerWP)p.Shape).WPText = s2;
2368 - 760
        }
2372 - 761
        void _WPMarkerSetType(string text, int type)
762
        {
763
            GMapMarker p = _findWPMarker(text);
764
            if (p != null)
765
                ((CustomMarkerWP)p.Shape).WPType = type;
766
        }
2369 - 767
        void _repositionWPMarker(PointLatLng point, string name)
768
        {
769
            GMapMarker p = _findWPMarker(name);
770
            if (p != null)
771
                p.Position = point;
772
        }
773
 
2287 - 774
        // access mode
775
        private void comboBoxMode_DropDownClosed(object sender, EventArgs e)
776
        {
777
            MainMap.Manager.Mode = (AccessMode)comboBoxMode.SelectedItem;
778
            MainMap.ReloadMap();
779
        }
780
        // zoom up
781
        private void czuZoomUp_Click(object sender, RoutedEventArgs e)
782
        {
783
            MainMap.Zoom = ((int)MainMap.Zoom) + 1;
784
        }
785
 
786
        // zoom down
787
        private void czuZoomDown_Click(object sender, RoutedEventArgs e)
788
        {
789
            MainMap.Zoom = ((int)(MainMap.Zoom + 0.99)) - 1;
790
        }
791
 
792
        // prefetch
793
        private void buttonPrefetch_Click(object sender, RoutedEventArgs e)
794
        {
795
            RectLatLng area = MainMap.SelectedArea;
796
            if (!area.IsEmpty)
797
            {
798
                for (int i = (int)MainMap.Zoom; i <= MainMap.MaxZoom; i++)
799
                {
800
                    MessageBoxResult res = MessageBox.Show("Ready ripp at Zoom = " + i + " ?", "GMap.NET", MessageBoxButton.YesNoCancel);
801
 
802
                    if (res == MessageBoxResult.Yes)
803
                    {
804
                        TilePrefetcher obj = new TilePrefetcher();
805
                        obj.Owner = this;
806
                        obj.ShowCompleteMessage = true;
807
                        obj.Start(area, i, MainMap.MapProvider, 100);
808
                    }
809
                    else if (res == MessageBoxResult.No)
810
                    {
811
                        continue;
812
                    }
813
                    else if (res == MessageBoxResult.Cancel)
814
                    {
815
                        break;
816
                    }
817
                }
818
            }
819
            else
820
            {
821
                MessageBox.Show("Select map area holding ALT", "GMap.NET", MessageBoxButton.OK, MessageBoxImage.Exclamation);
822
            }
823
        }
824
 
825
        // goto by geocoder
826
        private void buttonGeoCoding_Click(object sender, RoutedEventArgs e)
827
        {
828
            _goto_byGeoCoder();
829
        }
830
        // goto by geocoder
831
        private void textBoxGeo_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
832
        {
833
            if (e.Key == System.Windows.Input.Key.Enter)
834
                _goto_byGeoCoder();
835
        }
836
        void _goto_byGeoCoder()
837
        {
838
            GeoCoderStatusCode status = MainMap.SetPositionByKeywords(textBoxGeo.Text);
839
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
840
            {
841
                MessageBox.Show("Geocoder can't find: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButton.OK, MessageBoxImage.Exclamation);
842
            }
843
        }
844
        private void buttonGeoLoc_Click(object sender, RoutedEventArgs e)
845
        {
846
            try
847
            {
848
                double lat = double.Parse(textBoxLat.Text, System.Globalization.CultureInfo.InvariantCulture);
849
                double lng = double.Parse(textBoxLng.Text, System.Globalization.CultureInfo.InvariantCulture);
850
 
851
                MainMap.Position = new PointLatLng(lat, lng);
852
            }
853
            catch (Exception ex)
854
            {
855
                MessageBox.Show("incorrect coordinate format: " + ex.Message);
856
            }
857
 
858
        }
859
 
860
        private void ReloadMap_Click(object sender, RoutedEventArgs e)
861
        {
862
            MainMap.ReloadMap();
863
        }
864
 
865
        private void MainMap_OnPositionChanged(PointLatLng point)
866
        {
867
            if (_bFollowCopter)
868
                _setCopterData(MainMap.Position);
869
        }
870
 
871
        private void MainMap_OnMapZoomChanged()
872
        {
873
            if (_bFollowCopter)
874
                _setCopterData(MainMap.Position);
875
            if((int)sliderMapZoom.Value != MainMap.Zoom)
876
                sliderMapZoom.Value = MainMap.Zoom;
877
        }
878
 
879
        void _setCopterData(PointLatLng p)
880
        {
881
            Dispatcher.Invoke(() =>
882
            {
883
                copter.Position = p;
884
                ((CustomMarkerCopter)(copter.Shape)).setText(p.Lat.ToString("0.#######°") + System.Environment.NewLine + p.Lng.ToString("0.#######°"));
885
                textBoxLat_currentPos.Text = p.Lat.ToString() + "°";
886
                textBoxLng_currentPos.Text = p.Lng.ToString() + "°";
887
            });
888
            if (home != null && MainMap.Markers.Contains(home))
889
            {
890
                Dispatcher.Invoke(() => ArtHor.rotateHome = GMapProviders.EmptyProvider.Projection.GetBearing(copter.Position, home.Position));
891
                double d = GMapProviders.EmptyProvider.Projection.GetDistance(home.Position, copter.Position);
892
                Dispatcher.Invoke(() => tbTopDistanceHP.Text = (d * 1000).ToString("0.0 m"));
2291 - 893
 
894
                if(d*1000 < _dThresholdDistanceWarn)
895
                {
896
                    _iDistanceJitter = 0; _bVoiceDistanceActive = false;
897
                    if (stbDistanceWarnAnim != null && _bAnimDistanceActive)
898
                    {
899
                        Dispatcher.Invoke(() => stbDistanceWarnAnim.Stop());
900
                        _bAnimDistanceActive = false;
901
                    }
902
                }
903
                else
904
                {
905
                    if (_iDistanceJitter < 20)
906
                    { _iDistanceJitter++; }
907
                    if (_iDistanceJitter == 20)
908
                    {
909
                        if (stbDistanceWarnAnim != null && !_bAnimDistanceActive)
910
                        {
911
                            Dispatcher.Invoke(() => stbDistanceWarnAnim.Begin());
912
                            _bAnimDistanceActive = true;
913
                        }
914
                        if (_bVoiceDistancePlay && !_bVoiceDistanceActive)
915
                        {
2295 - 916
                            Thread t = new Thread(()=>_mediaPlayer("Voice\\Distance.mp3"));
917
                            t.Start();
2291 - 918
                            _bVoiceDistanceActive = true;
919
                        }
920
                        _iDistanceJitter++;
921
                    }
922
                }
2287 - 923
            }
924
        }
925
 
926
        private void checkBoxFollowCopter_Click(object sender, RoutedEventArgs e)
927
        {
928
            _bFollowCopter = (bool)checkBoxFollowCopter.IsChecked;
929
        }
930
 
931
        private void sliderMapZoom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
932
        {
933
            if (MainMap.Zoom != sliderMapZoom.Value)
934
                MainMap.Zoom = (int)sliderMapZoom.Value;
935
        }
936
        #region Touch zooming hackattack ;) 
937
        /// <summary>
938
        /// inspired by http://www.codeproject.com/Articles/692286/WPF-and-multi-touch
939
        /// </summary>
940
        bool bFirstAccess = true;
941
        double dDistance = 0;
942
        int iZoom;
943
        private void MainMap_StylusDown(object sender, StylusDownEventArgs e)
944
        {
945
            var id = e.StylusDevice.Id;
946
            e.StylusDevice.Capture(MainMap);
947
            if (iFirstStylusID == -1)
948
            {
949
                iFirstStylusID = id;
950
            }
951
            else
952
            {
953
 
954
                MainMap.CanDragMap = false;
955
            }
956
        }
957
        private void MainMap_StylusUp(object sender, StylusEventArgs e)
958
        {
959
            MainMap.ReleaseStylusCapture();
960
            iFirstStylusID = -1;
961
            bFirstAccess = true;
962
            MainMap.CanDragMap = true;
963
            iZoom = 0;
964
        }
965
        private void MainMap_StylusMove(object sender, StylusEventArgs e)
966
        {
967
            var id = e.StylusDevice.Id;
968
            var tp = e.GetPosition(MainMap);
969
 
970
            // This is the first Stylus point; just record its position. 
971
            if (id == iFirstStylusID)
972
            {
973
                pTouch1.X = tp.X;
974
                pTouch1.Y = tp.Y;
975
            }
976
            else
977
            if (iFirstStylusID > -1)
978
            {
979
                pTouch2.X = tp.X;
980
                pTouch2.Y = tp.Y;
981
                double distance = Point.Subtract(pTouch1, pTouch2).Length;
982
                if (!bFirstAccess)
983
                {
984
                    if (distance > dDistance)
985
                        iZoom++;
986
                    else
987
                        if (distance < dDistance)
988
                        iZoom--;
989
                }
990
                if (iZoom > 30)
991
                {
992
                    iZoom = 0;
993
                    Dispatcher.Invoke(() => sliderMapZoom.Value += 1);
994
                }
995
                if (iZoom < -30)
996
                {
997
                    iZoom = 0;
998
                    Dispatcher.Invoke(() => sliderMapZoom.Value -= 1);
999
                }
1000
                dDistance = distance;
1001
                bFirstAccess = false;
1002
            }
1003
        }
1004
        #endregion Touch zooming hackattack ;)
1005
 
1006
        #endregion GMap
1007
 
1008
        #region settings
1009
        private void cBoxTimingsDebug_DropDownClosed(object sender, EventArgs e)
1010
        {
1011
            if(! _bCBInit && cBoxTimingsDebug.SelectedIndex > -1)
1012
                debugInterval = (byte)(Convert.ToInt16(cBoxTimingsDebug.SelectedItem) / 10);
1013
        }
1014
        private void cBoxTimingsNav_DropDownClosed(object sender, EventArgs e)
1015
        {
1016
            if(! _bCBInit && cBoxTimingsNav.SelectedIndex > -1)
1017
                navctrlInterval = (byte)(Convert.ToInt16(cBoxTimingsNav.SelectedItem) / 10);
1018
        }
1019
        private void cBoxTimingsBl_DropDownClosed(object sender, EventArgs e)
1020
        {
1021
            if (!_bCBInit && cBoxTimingsBl.SelectedIndex > -1)
1022
                blctrlInterval = (byte)(Convert.ToInt16(cBoxTimingsBl.SelectedItem) / 10);
1023
        }
1024
        private void cBoxTimingsOSD_DropDownClosed(object sender, EventArgs e)
1025
        {
1026
            if (!_bCBInit && cBoxTimingsOSD.SelectedIndex > -1)
1027
                OSDInterval = (byte)(Convert.ToInt16(cBoxTimingsOSD.SelectedItem) / 10);
1028
        }
1029
        private void chkbAutoDbg_Click(object sender, RoutedEventArgs e)
1030
        {
1031
            if (!_init) _debugDataAutorefresh = (bool)chkbAutoDbg.IsChecked;
1032
        }
1033
        private void chkbAutoNav_Click(object sender, RoutedEventArgs e)
1034
        {
1035
            if (!_init) _navCtrlDataAutorefresh = (bool)chkbAutoNav.IsChecked;
1036
        }
1037
        private void chkbAutoBL_Click(object sender, RoutedEventArgs e)
1038
        {
1039
            if (!_init) _blctrlDataAutorefresh = (bool)chkbAutoBL.IsChecked;
1040
        }
1041
        private void chkbAutoOSD_Click(object sender, RoutedEventArgs e)
1042
        {
1043
            if (!_init) _OSDAutorefresh = (bool)chkbAutoOSD.IsChecked;
1044
        }
1045
 
1046
        private void cBoxLiPoCells_DropDownClosed(object sender, EventArgs e)
1047
        {
1048
            if (cBoxLiPoCells.SelectedIndex > -1)
1049
            {
1050
                _LipoCells = cBoxLiPoCells.SelectedIndex + 3;
1051
                _LipoMinMax();
1052
            }
1053
        }
1054
        void _LipoMinMax()
1055
        {
1056
            _dLipoVMax = (double)(_LipoCells) * 4.22;
1057
            _dLipoVMin = (double)_LipoCells * 3;
1058
            pbTopVoltage.Maximum = _dLipoVMax;
1059
            pbTopVoltage.Minimum = _dLipoVMin;
1060
            sliderThresholdVoltageWarn.Maximum = _dLipoVMax;
1061
            sliderThresholdVoltageWarn.Minimum = _dLipoVMin;
1062
        }
1063
        private void cBoxMotors_DropDownClosed(object sender, EventArgs e)
1064
        {
1065
            if (cBoxMotors.SelectedIndex > -1)
1066
            {
1067
                _iMotors = cBoxMotors.SelectedIndex + 3;
1068
                Dispatcher.Invoke(() =>
1069
                {
1070
                    dgvMotors1.Height = (272 / 12.6) * (_iMotors + 1);  //272 / 12.6 --> Workaround, cause the headerheight = NaN...?
1071
                    GridMotors.Height = dgvMotors1.Height + 10;
1072
                });
1073
            }
1074
        }
1075
        void _setMotorGridSize()
1076
        {
1077
            if (dgvMotors1.Columns.Count > 2)
1078
            {
1079
                dgvMotors1.Columns[0].Width = 24;
1080
                dgvMotors1.Columns[1].Width = 50;
1081
                dgvMotors1.Columns[2].Width = 50;
1082
                dgvMotors1.Height = (272 / 12.6) * (_iMotors + 1);
1083
                GridMotors.Height = dgvMotors1.Height + 10;
1084
            }
1085
 
1086
        }
1087
        #endregion settings
1088
 
1089
        #region functions  
1090
 
1091
        #region logging      
1092
        /// <summary> Log data to the terminal window. </summary>
1093
        /// <param name="msgtype"> The type of message to be written. </param>
1094
        /// <param name="msg"> The string containing the message to be shown. </param>
1095
        private void Log(LogMsgType msgtype, string msg)
1096
        {
1097
            Dispatcher.Invoke(() =>
1098
            {
1099
               // rtfTerminal.CaretPosition = rtfTerminal.CaretPosition.DocumentEnd;
1100
               // rtfTerminal.Foreground = new SolidColorBrush(LogMsgTypeColor[(int)msgtype]);
1101
//                rtfTerminal.AppendText(msg + "\r");
1102
                TextRange tr = new TextRange(rtfTerminal.Document.ContentEnd,rtfTerminal.Document.ContentEnd);
1103
                tr.Text = msg;
1104
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(LogMsgTypeColor[(int)msgtype]));
1105
                rtfTerminal.AppendText("\r");
1106
                rtfTerminal.ScrollToEnd();
1107
            });
1108
        }
1109
        private void ErrorLog(LogMsgType msgtype, string msg)
1110
        {
1111
            Dispatcher.Invoke(() =>
1112
            {
1113
                TextRange tr = new TextRange(rtfError.Document.ContentEnd, rtfError.Document.ContentEnd);
1114
                tr.Text = msg;
1115
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(LogMsgTypeColor[(int)msgtype]));
1116
                rtfError.AppendText("\r");
1117
                rtfError.ScrollToEnd();
1118
 
1119
                _bErrorLog = true;
1120
            });
1121
        }
1122
        /// <summary>
1123
        /// Clear the line in the  errorlog window 
1124
        /// containing the error string when error has ceased
1125
        /// </summary>
1126
        /// <param name="s">substring of errrormessage</param>
1127
        void _clearErrorLog(string s)
1128
        {
1129
            Dispatcher.Invoke((Action)(() =>
1130
            {
1131
                TextRange searchRange = new TextRange(rtfError.Document.ContentStart, rtfError.Document.ContentEnd);
1132
                TextRange foundRange = FindTextInRange(searchRange, s);
1133
 
1134
                int iStart = searchRange.Text.IndexOf(s, StringComparison.OrdinalIgnoreCase);
1135
 
1136
 
1137
                if (iStart > -1)
1138
                {
1139
                    int iLength = 0;
1140
                    int iEnd = searchRange.Text.IndexOf('\r', iStart);
1141
                    if (iEnd > 0)
1142
                    {
1143
                        iLength = iEnd + 1;
1144
                        int iHttp = searchRange.Text.IndexOf("http", iEnd);
1145
                        if (iHttp == iLength)
1146
                        {
1147
                            int iEnd2 = searchRange.Text.IndexOf('\r', iLength);
1148
                            if (iEnd2 > iLength)
1149
                            {
1150
                                iLength = iEnd2 + 1;
1151
                              //  TextRange result = new TextRange(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), GetTextPositionAtOffset(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), iLength));
1152
 
1153
                                rtfError.Selection.Select(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), GetTextPositionAtOffset(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), iLength));
1154
                                rtfError.Selection.Text = string.Empty;
1155
                                if (rtfError.Document.ContentEnd.GetTextRunLength(LogicalDirection.Backward) < 2) _bErrorLog = false;
1156
                            }
1157
 
1158
                        }
1159
                        else
1160
                        {
1161
                            rtfError.Selection.Select(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), GetTextPositionAtOffset(rtfError.Document.ContentStart.GetPositionAtOffset(iStart), iLength));
1162
                            rtfError.Selection.Text = string.Empty;
1163
                            if (rtfError.Document.ContentEnd.GetTextRunLength(LogicalDirection.Backward) < 2) _bErrorLog = false;
1164
                        }
1165
                    }
1166
                }
1167
            }));
1168
 
1169
        }
1170
        public TextRange FindTextInRange(TextRange searchRange, string searchText)
1171
        {
1172
            int offset = searchRange.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
1173
            if (offset < 0)
1174
                return null;  // Not found
1175
 
1176
            var start = GetTextPositionAtOffset(searchRange.Start, offset);
1177
            TextRange result = new TextRange(start, GetTextPositionAtOffset(start, searchText.Length));
1178
 
1179
            return result;
1180
        }
1181
        TextPointer GetTextPositionAtOffset(TextPointer position, int characterCount)
1182
        {
1183
            while (position != null)
1184
            {
1185
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
1186
                {
1187
                    int count = position.GetTextRunLength(LogicalDirection.Forward);
1188
                    if (characterCount <= count)
1189
                    {
1190
                        return position.GetPositionAtOffset(characterCount);
1191
                    }
1192
 
1193
                    characterCount -= count;
1194
                }
1195
 
1196
                TextPointer nextContextPosition = position.GetNextContextPosition(LogicalDirection.Forward);
1197
                if (nextContextPosition == null)
1198
                    return position;
1199
 
1200
                position = nextContextPosition;
1201
            }
1202
 
1203
            return position;
1204
        }
1205
        #endregion logging
1206
 
1207
        #region processing received data
1208
 
1209
        private void processMessage(byte[] message)
1210
        {
1211
            if (message.Length > 0)
1212
            {
1213
                _iLifeCounter++;
1214
                //Log(LogMsgType.Incoming, BitConverter.ToString(message));
1215
                //Log(LogMsgType.Incoming, message.Length.ToString());
1216
                string s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, message.Length));
1217
                char cmdID;
1218
                byte adr;
1219
                byte[] data;
1220
                byte[] tmp = null;
1221
                if (message[0] != '#')
1222
                {
1223
                    int iFound = -1;
1224
                    for (int i = 0; i < message.Length; i++)   //Sometimes the FC/NC sends strings without termination (like WP messages)
1225
                    {                                   //so this is a workaround to not spam the log box
1226
                        if (message[i] == 35)
1227
                        {
1228
                            iFound = i;
1229
                            break;
1230
                        }
1231
                    }
1232
                    if (iFound > 0)
1233
                    {
1234
                        s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, iFound));
1235
                        tmp = new byte[message.Length - iFound];
1236
                        Buffer.BlockCopy(message, iFound, tmp, 0, message.Length - iFound);
1237
                    }
1238
                    s = s.Trim('\0', '\n', '\r');
1239
                    if (s.Length > 0)
1240
                        Log(LogMsgType.Normal, s);
1241
                    if (tmp != null)
1242
                    {
1243
                        s = new string(ASCIIEncoding.ASCII.GetChars(tmp, 0, tmp.Length));
1244
                        processMessage(tmp);
1245
                    }
1246
                }
1247
                //Debug.Print(s);
1248
                else
1249
                {
1250
                    FlightControllerMessage.ParseMessage(message, out cmdID, out adr, out data);
1251
 
1252
                    if (adr == 255) { crcError++; }
1253
                    else crcError = 0;
1254
                    Dispatcher.Invoke(() => tbCrc.Text = crcError.ToString());
1255
                    //display the active controller (FC / NC) 
1256
                    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...???
1257
                    {
1258
                        _iCtrlAct = adr;
1259
                        switch (adr)
1260
                        {
1261
                            case 1:
1262
                                Dispatcher.Invoke(() => tbCtrl.Text = "FC");
2298 - 1263
                                Dispatcher.Invoke(() => buttonSwitchNC.Visibility = Visibility.Visible);
2287 - 1264
                                //Dispatcher.Invoke(() => labelSwitchToNavi.Visibility = Visibility.Visible);
1265
                              //  _setFieldsNA(); //display fields NA for FC 
1266
                                break;
1267
                            case 2:
1268
                                Dispatcher.Invoke(() => tbCtrl.Text = "NC");
1269
                                //Dispatcher.Invoke(() => buttonSwitchNC.Visibility = Visibility.Hidden);
1270
                                //Dispatcher.Invoke(() => labelSwitchToNavi.Visibility = Visibility.Hidden);
1271
                                break;
1272
                            //case 3:
1273
                            //    lblCtrl.Invoke((Action)(() => lblCtrl.Text = "MK3MAG"));
1274
                            //    break;
1275
                            //case 4:
1276
                            //    lblCtrl.Invoke((Action)(() => lblCtrl.Text = "BL-CTRL"));
1277
                            //    break;
1278
                            default:
1279
                                Dispatcher.Invoke(() => tbCtrl.Text = "NA");
1280
                                break;
1281
                        }
1282
                       // _loadLabelNames();
1283
                    }
1284
                    // else
1285
                    //     Debug.Print("Address == 0?");
1286
 
1287
                    if (data != null && data.Length > 0)
1288
                    {
1289
                        s = new string(ASCIIEncoding.ASCII.GetChars(data, 1, data.Length - 1));
1290
                        s = s.Trim('\0', '\n');
1291
 
1292
                        switch (cmdID)
1293
                        {
1294
                            //case 'A': //Label names
1295
                            //    _processLabelNames(s);
1296
                            //    break;
1297
 
1298
                            case 'D': //Debug data
1299
                                _processDebugVals(adr, data);
1300
                                break;
1301
 
1302
                            case 'V': //Version
1303
                                _processVersion(adr, data);
1304
                                break;
1305
 
1306
                            case 'K'://BL-CTRL data
1307
                                _processBLCtrl(data);
1308
                                break;
1309
 
1310
                            case 'O': //NC Data
1311
                                _processNCData(data);
1312
                                break;
1313
 
1314
                            case 'E': //NC error-string
1315
                                ErrorLog(LogMsgType.Error, "NC Error: " + s);
1316
                                break;
1317
 
1318
                            case 'L': //OSD Menue (called by pagenumber)
1319
                                _processOSDSingle(data);
1320
                                break;
1321
 
1322
                            case 'H': //OSD Menue (with autoupdate - called by Key)
1323
                                _processOSDAuto(data);
1324
                                break;
1325
 
1326
                            case 'X': //Waypoint data
1327
                                _processWPData(data);
1328
                                break;
1329
 
2313 - 1330
                            case 'W': //return new Waypoint items count after sending waypoint to copter
1331
                                _iWPCount = data[0];
1332
                                break;
2287 - 1333
                                //default:
1334
                                //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
1335
                                //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
1336
                                //    break;
1337
                        }
1338
                    }
1339
                    //else
1340
                    //{
1341
                    //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
1342
                    //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
1343
                    //}
1344
                }
1345
            }
1346
        }
1347
        /// <summary>
1348
        /// Analog label names 'A'
1349
        /// each label name is returned as a single string 
1350
        /// and added to string array sAnalogLabel[]
1351
        /// and the datatable dtAnalog
1352
        /// </summary>
1353
        /// <param name="s">the label name</param>
1354
        void _processLabelNames(string s)
1355
        {
1356
            //if (iLableIndex < 32)
1357
            //{
1358
            //    sAnalogLabel[iLableIndex] = s;
1359
            //    if (dtAnalog.Rows.Count < 32)
1360
            //        dtAnalog.Rows.Add(s, "");
1361
            //    else
1362
            //        dtAnalog.Rows[iLableIndex].SetField(0, s);
1363
 
1364
            //  //  _getAnalogLabels(iLableIndex + 1);
1365
            //}
1366
            //Debug.Print(s);
1367
        }
1368
        /// <summary>
1369
        /// Debug values 'D'
1370
        /// </summary>
1371
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
1372
        /// <param name="data">the received byte array to process</param>
1373
        void _processDebugVals(byte adr, byte[] data)
1374
        {
1375
            if (data.Length == 66)
1376
            {
2324 - 1377
 
2287 - 1378
                double v;
1379
                int index = 0;
1380
                Int16 i16 = 0;
1381
                double dTemp = 0;
1382
                for (int i = 2; i < 66; i += 2)
1383
                {
1384
                    i16 = data[i + 1];
1385
                    i16 = (Int16)(i16 << 8);
1386
                    iAnalogData[index] = data[i] + i16;
1387
                    sAnalogData[index] = (data[i] + i16).ToString();
1388
                   // dtAnalog.Rows[index].SetField(1, sAnalogData[index]);
1389
 
1390
                    if (adr == 2) //NC
1391
                    {
1392
                        switch (index)
1393
                        {
1394
                            case 0: //pitch (German: nick)
1395
                                Dispatcher.Invoke(() => ArtHor.Pitch = ((double)iAnalogData[index] / (double)10));
1396
                                Dispatcher.Invoke((Action)(() => tbPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
1397
                                break;
1398
                            case 1: //roll
1399
                                Dispatcher.Invoke(() => ArtHor.Roll = ((double)iAnalogData[index] / (double)10));
1400
                                Dispatcher.Invoke((Action)(() => tbRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
1401
                                break;
1402
                            case 4: //altitude
1403
                                Dispatcher.Invoke(() => tbAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m"));
1404
                                Dispatcher.Invoke(() => tbTopHeight.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m"));
2324 - 1405
                                Dispatcher.Invoke(() => { drGPX[3] = (double)iAnalogData[index] / (double)10; });
2287 - 1406
                                break;
1407
                            case 7: //Voltage
1408
                                v = (double)iAnalogData[index] / (double)10;
1409
                                Dispatcher.Invoke(() => tbVolt.Text = v.ToString("0.0 V"));
1410
                                Dispatcher.Invoke(() => tbTopVoltage.Text = v.ToString("0.0 V"));
1411
                                Dispatcher.Invoke(() => pbTopVoltage.Value = v);
1412
                                if (v - _dLipoVMin < 1 | v < _dThresholdVoltageWarn)
1413
                                {
1414
                                    if (v == _dVoltLast)
1415
                                        if(_iVoltJitter < 20) _iVoltJitter++;
1416
                                    else
1417
                                    {
1418
                                        _iVoltJitter = 0;
1419
                                        _dVoltLast = v;
1420
                                    }
1421
                                    if (_iVoltJitter == 20)
1422
                                    {
1423
                                        Dispatcher.Invoke(() => pbTopVoltage.Foreground = Brushes.Orange);
1424
 
1425
                                        if (v - _dLipoVMin < 1 | v < _dThresholdVoltageCrit)
1426
                                        {
1427
                                            Dispatcher.Invoke(() => pbTopVoltage.Foreground = Brushes.Red);
1428
                                            if (stbVoltageCritAnim != null && !_bCritAnimVoltActive)
1429
                                            {
1430
                                                Dispatcher.Invoke(() => stbVoltageCritAnim.Begin());
1431
                                                _bCritAnimVoltActive = true;
1432
                                            }
1433
                                            if (_bVoiceVoltPlay && !_bCritVoiceVoltActive)
1434
                                            {
2295 - 1435
                                                Thread t = new Thread(() => _mediaPlayer("Voice\\CriticalBattery.mp3"));
1436
                                                t.Start();
2287 - 1437
                                                _bCritVoiceVoltActive = true;
1438
                                            }
1439
                                        }
1440
                                        else
1441
                                        {
1442
                                            if (stbVoltageCritAnim != null && _bCritAnimVoltActive)
1443
                                            {
1444
                                                Dispatcher.Invoke(() => stbVoltageCritAnim.Stop());
1445
                                                _bCritAnimVoltActive = false;
1446
                                            }
1447
                                            _bCritVoiceVoltActive = false;
1448
 
2291 - 1449
                                            if (_bVoiceVoltPlay && !_bWarnVoiceVoltActive)
2287 - 1450
                                            {
2295 - 1451
                                                Thread t = new Thread(() => _mediaPlayer("Voice\\LowBattery.mp3"));
1452
                                                t.Start();
2291 - 1453
                                                _bWarnVoiceVoltActive = true;
2287 - 1454
                                            }
1455
                                        }
1456
                                    }
1457
                                }
1458
                                else
1459
                                {
1460
                                    Dispatcher.Invoke(() => pbTopVoltage.Foreground = new SolidColorBrush(Color.FromArgb(255, 107, 195, 123)));
1461
                                    if (stbVoltageCritAnim != null && _bCritAnimVoltActive)
1462
                                    {
1463
                                        Dispatcher.Invoke(() => stbVoltageCritAnim.Stop());
1464
                                        _bCritAnimVoltActive = false;
1465
                                    }
1466
                                    _bCritVoiceVoltActive = false;
2291 - 1467
                                    _bWarnVoiceVoltActive = false;
2287 - 1468
                                    _iVoltJitter = 0;
1469
                                }
1470
                                break;
1471
                            case 8: // Current
1472
                                Dispatcher.Invoke(() => tbCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A"));
1473
                                Dispatcher.Invoke(() => tbTopCurrent.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A"));
1474
                                break;
1475
                            case 10: //heading
2291 - 1476
                                Dispatcher.Invoke((Action)(() => tbHeading.Text = sAnalogData[index] + "°"));
2287 - 1477
                                Dispatcher.Invoke(() => ArtHor.rotate = iAnalogData[index]);
1478
                                break;
1479
                            case 12: // SPI error
2291 - 1480
                                Dispatcher.Invoke((Action)(() => tbSPI.Text = sAnalogData[index]));
2287 - 1481
                                break;
1482
                            case 14: //i2c error
2291 - 1483
                                Dispatcher.Invoke((Action)(() => tbI2C.Text = sAnalogData[index]));
2287 - 1484
                                break;
1485
                            case 20: //Earthmagnet field
2291 - 1486
                                Dispatcher.Invoke((Action)(() => tbMagF.Text = sAnalogData[index] + "%"));
1487
                                Dispatcher.Invoke((Action)(() => tbTopEarthMag.Text = sAnalogData[index] + "%"));
1488
 
1489
                                if (Math.Abs(100 - iAnalogData[index]) < _iThresholdMagField)
1490
                                {
1491
                                    Dispatcher.Invoke(() => imageEarthMag.Source = new BitmapImage(new Uri("Images/EarthMag.png", UriKind.Relative)));
1492
                                    _iMagneticFieldJitter = 0; _bVoiceMagneticFieldActive = false;
1493
                                    if (stbMagneticFieldAnim != null && _bAnimMagneticFieldActive)
1494
                                    {
1495
                                        Dispatcher.Invoke(() => stbMagneticFieldAnim.Stop());
1496
                                        _bAnimMagneticFieldActive = false;
1497
                                    }
1498
                                }
1499
                                else
1500
                                {
1501
                                    Dispatcher.Invoke(() => imageEarthMag.Source = new BitmapImage(new Uri("Images/EarthMag_R.png", UriKind.Relative)));
1502
                                    if(_iMagneticFieldLast >= Math.Abs(100 - iAnalogData[index]))
1503
                                    {
1504
                                        if (_iMagneticFieldJitter < 20)
1505
                                            _iMagneticFieldJitter++;
1506
                                    }
1507
                                    else
1508
                                    {
1509
                                        _iMagneticFieldJitter = 0;
1510
                                        _iMagneticFieldLast = Math.Abs(100 - iAnalogData[index]);
1511
                                    }
1512
                                    if(_iMagneticFieldJitter == 20)
1513
                                    {
1514
                                        if (stbMagneticFieldAnim != null && !_bAnimMagneticFieldActive)
1515
                                        {
1516
                                            Dispatcher.Invoke(() => stbMagneticFieldAnim.Begin());
1517
                                            _bAnimMagneticFieldActive = true;
1518
                                        }
1519
                                        if (_bVoiceMagneticFieldPlay && !_bVoiceMagneticFieldActive)
1520
                                        {
2295 - 1521
                                            Thread t = new Thread(() => _mediaPlayer("Voice\\MagneticField.mp3"));
1522
                                            t.Start();
2291 - 1523
                                            _bVoiceMagneticFieldActive = true;
1524
                                        }
1525
                                    }
1526
                                }
2287 - 1527
                                break;
1528
                            case 21: //GroundSpeed
1529
                                     Dispatcher.Invoke((Action)(() => tbSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
1530
                                     Dispatcher.Invoke((Action)(() => tbTopSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
1531
                                break;
2291 - 1532
 
1533
                            ///**********   needs testing --> not sure what position this is  ***************
2287 - 1534
                            case 28: //Distance East from saved home position -> calculate distance with distance N + height
1535
                                    dTemp = Math.Pow((double)iAnalogData[index], 2) + Math.Pow((double)iAnalogData[index - 1], 2);
1536
                                    dTemp = Math.Sqrt(dTemp) / (double)10; //'flat' distance from HP with N/E
1537
                                                                           //  lblNCDist.Invoke((Action)(() => lblNCDist.Text = dTemp.ToString("0.00")));
1538
                                    dTemp = Math.Pow(dTemp, 2) + Math.Pow(((double)iAnalogData[4] / (double)10), 2); //adding 'height' into calculation
1539
                                    dTemp = Math.Sqrt(dTemp) / (double)10;
1540
                               //     Dispatcher.Invoke((Action)(() => tbTopDistanceHP.Text = dTemp.ToString("0.0 m")));
1541
                                    Dispatcher.Invoke((Action)(() => tbHP1.Text = dTemp.ToString("0.0 m")));
1542
                                break;
2291 - 1543
 
2287 - 1544
                            case 31: //Sats used
1545
                                     Dispatcher.Invoke((Action)(() => tbSats.Text = sAnalogData[index]));
1546
                                    // Dispatcher.Invoke((Action)(() => tbTopSats.Text = sAnalogData[index]));                                   
1547
                                break;
1548
                        }
1549
                    }
1550
                    index++;
1551
                }
1552
            }
1553
            else
1554
                Debug.Print("wrong data-length (66): " + data.Length.ToString());
1555
        }
1556
        /// <summary>
1557
        /// Version string 'V'
1558
        /// </summary>
1559
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
1560
        /// <param name="data">the received byte array to process</param>
1561
        void _processVersion(byte adr, byte[] data)
1562
        {
1563
            if (data.Length == 12)
1564
            {
1565
                if (!check_HWError)
1566
                {
1567
                    string[] sVersionStruct = new string[10] { "SWMajor: ", "SWMinor: ", "ProtoMajor: ", "LabelTextCRC: ", "SWPatch: ", "HardwareError 1: ", "HardwareError 2: ", "HWMajor: ", "BL_Firmware: ", "Flags: " };
1568
                    string sVersion = "";
1569
                    //sbyte[] signed = Array.ConvertAll(data, b => unchecked((sbyte)b));
1570
                    Log(LogMsgType.Warning, (adr == 1 ? "FC-" : "NC-") + "Version: ");
1571
                    sVersion = "HW V" + (data[7] / 10).ToString() + "." + (data[7] % 10).ToString();
1572
                    Log(LogMsgType.Incoming, sVersion);
1573
                    sVersion = "SW V" + (data[0]).ToString() + "." + (data[1]).ToString() + ((char)(data[4] + 'a')).ToString();
1574
                    Log(LogMsgType.Incoming, sVersion);
1575
                    Log(LogMsgType.Incoming, "BL-Firmware: V" + (data[8] / 100).ToString() + "." + (data[8] % 100).ToString());
1576
                }
1577
                if (data[5] > 0) //error0 
1578
                {
1579
                    if (adr == 1)
1580
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[5].ToString() + ": " + ((FC_HWError0)data[5]).ToString());
1581
                    if (adr == 2)
1582
                        ErrorLog(LogMsgType.Error, "NC - HW-Error " + data[5].ToString() + ": " + ((NC_HWError0)data[5]).ToString());
1583
                }
1584
                if (data[6] > 0) //error1 
1585
                {
1586
                    if (adr == 1)
1587
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[6].ToString() + ": " + ((FC_HWError1)data[6]).ToString());
1588
                    if (adr == 2)
1589
                        ErrorLog(LogMsgType.Error, "NC - Unknown HW-ERROR: " + data[6].ToString()); //@moment NC has only one error field
1590
                }
1591
                if ((data[5] + data[6] == 0) && _bErrorLog)
1592
                    _clearErrorLog(adr == 1 ? "FC - HW-Error" : "NC - HW-Error");
1593
 
1594
            }
1595
            check_HWError = false;
1596
        }
1597
        /// <summary>
1598
        /// BL-Ctrl data 'K'
1599
        /// for FC you have to use a customized firmware
1600
        /// </summary>
1601
        /// <param name="data">the received byte array to process</param>
1602
        void _processBLCtrl(byte[] data)
1603
        {
1604
            if (data.Length % 6 == 0) //data.Length up to 96 (16 motors x 6 byte data) --> new datastruct in FC -> not standard!
1605
            {
1606
                bool bAvailable = false;
1607
                for (int i = 0; i < data.Length && data[i] < _iMotors; i += 6) // data[i] < _iMotors -- only show set number of motors (12 max @ moment)
1608
                {
1609
 
1610
                    if ((data[i + 4] & 128) == 128) //Status bit at pos 7 = 128 dec -- if true, motor is available
1611
                        bAvailable = true;
1612
                    else
1613
                        bAvailable = false;
1614
 
1615
                    if (data[i] < _iMotors)
1616
                    {
1617
                        if (bAvailable)
1618
                        {
2315 - 1619
                            dtMotors.Rows[data[i]].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
1620
                            dtMotors.Rows[data[i]].SetField(2, data[i + 2].ToString("0 °C"));
2287 - 1621
                        }
1622
                        else
1623
                        {
2315 - 1624
                            dtMotors.Rows[data[i]].SetField(1, "NA");
1625
                            dtMotors.Rows[data[i]].SetField(2, "NA");
2287 - 1626
                        }
1627
                    }
1628
                    //if (data[i] > 3 && data[i] < 8)
1629
                    //{
1630
                    //    if (bAvailable)
1631
                    //    {
1632
                    //        dtMotors2.Rows[data[i] - 4].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
1633
                    //        dtMotors2.Rows[data[i] - 4].SetField(2, data[i + 2].ToString("0 °C"));
1634
                    //    }
1635
                    //    else
1636
                    //    {
1637
                    //        dtMotors2.Rows[data[i] - 4].SetField(1, "NA");
1638
                    //        dtMotors2.Rows[data[i] - 4].SetField(2, "NA");
1639
                    //    }
1640
                    //}
1641
                }
1642
            }
1643
        }
1644
        /// <summary>
1645
        /// Navi-Ctrl data 'O'
1646
        /// GPS-Position, capacatiy, flying time...
1647
        /// </summary>
1648
        /// <param name="data">the received byte array to process</param>
1649
        void _processNCData(byte[] data)
1650
        {
1651
            int i_32, i_16, iVal;
1652
            double d;
1653
            i_32 = data[4];
1654
            iVal = i_32 << 24;
1655
            i_32 = data[3];
1656
            iVal += i_32 << 16;
1657
            i_32 = data[2];
1658
            iVal += i_32 << 8;
1659
            iVal += data[1];
1660
            d = (double)iVal / Math.Pow(10, 7);
2324 - 1661
            Dispatcher.Invoke(() => { drGPX[2] = d; });
1662
 
2287 - 1663
            PointLatLng p = new PointLatLng();
1664
 
1665
            p.Lng = d;
1666
          //  lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = d.ToString("0.######°"))); //GPS-Position: Longitude in decimal degree
1667
            //lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = _convertDegree(d))); //GPS-Position: Longitude in minutes, seconds
1668
 
1669
            i_32 = data[8];
1670
            iVal = i_32 << 24;
1671
            i_32 = data[7];
1672
            iVal += i_32 << 16;
1673
            i_32 = data[6];
1674
            iVal += i_32 << 8;
1675
            iVal += data[5];
1676
            d = (double)iVal / Math.Pow(10, 7);
2324 - 1677
            Dispatcher.Invoke(() => { drGPX[1] = d; });
1678
            Dispatcher.Invoke(() => { drGPX[4] = DateTime.UtcNow.ToString("u", System.Globalization.CultureInfo.InvariantCulture); }); //2011-01-14T01:59:01Z });
2287 - 1679
            p.Lat = d;
2291 - 1680
            if (data[50] > 4)//if more than 4 sats in use . otherwise the map would jump and scroll insane at beginning
1681
            {
1682
                _bSatFix = true; _iSatsJitter = 0; _bVoiceSatFixActive = false;
2295 - 1683
                if(_bAutoHome && !_bFirstSatFix)
1684
                {
1685
                    if (_iFirstSatFix < 3)
1686
                        _iFirstSatFix++;
1687
                    else
1688
                    {
1689
                        _bFirstSatFix = true;
2347 - 1690
                        Dispatcher.Invoke(() => _setHomePos());
2295 - 1691
                    }
1692
                }
2291 - 1693
                if (stbSatFixLostAnim != null && _bAnimSatFixActive)
1694
                {
1695
                    Dispatcher.Invoke(() => stbSatFixLostAnim.Stop());
1696
                    _bAnimSatFixActive = false;
1697
                }
1698
                if (!_bFollowCopter)
1699
                {
1700
                    _setCopterData(p);
1701
                    if (!MainMap.ViewArea.Contains(p))
1702
                        Dispatcher.Invoke(() => MainMap.Position = p);
2287 - 1703
 
2291 - 1704
                }
1705
                else
2287 - 1706
                    Dispatcher.Invoke(() => MainMap.Position = p);
1707
            }
1708
            else
2291 - 1709
            {
1710
                if(_bSatFix)
1711
                {
1712
                    if (data[50] == _iSatsLast)
1713
                    {
1714
                        if (_iSatsJitter < 20) _iSatsJitter++;
1715
                    }
1716
                    else
1717
                    {
1718
                        _iSatsJitter = 0;
1719
                        _iSatsLast = data[50];
1720
                    }
2287 - 1721
 
2291 - 1722
                    if (_iSatsJitter == 20)
1723
                    {
1724
                        if (stbSatFixLostAnim != null && !_bAnimSatFixActive)
1725
                        {
1726
                            Dispatcher.Invoke(() => stbSatFixLostAnim.Begin());
1727
                            _bAnimSatFixActive = true;
1728
                        }
1729
                        if (_bVoiceSatFixPlay && !_bVoiceSatFixActive)
1730
                        {
2335 - 1731
                            Thread th = new Thread(() => _mediaPlayer("Voice\\SatFixLost.mp3"));
2295 - 1732
                            th.Start();
2291 - 1733
                            _bVoiceSatFixActive = true;
1734
                        }
1735
 
1736
                        _bSatFix = false;
1737
                    }
1738
                }
1739
            }
1740
 
2287 - 1741
            i_16 = data[28];
1742
            i_16 = (Int16)(i_16 << 8);
1743
            iVal = data[27] + i_16;
1744
            Dispatcher.Invoke((Action)(() => tbWP.Text = ((double)iVal / (double)10).ToString("0.0 m"))); //Distance to next WP
1745
 
1746
            i_16 = data[45];
1747
            i_16 = (Int16)(i_16 << 8);
1748
            iVal = data[44] + i_16;
1749
        //    Dispatcher.Invoke((Action)(() => tbTopDistanceHP.Text = ((double)iVal / (double)10).ToString("0.0 m"))); //Distance to HP set by GPS on
1750
            Dispatcher.Invoke((Action)(() => tbHP.Text = ((double)iVal / (double)10).ToString("0.0 m"))); //Distance to HP set by GPS on
1751
 
1752
            Dispatcher.Invoke((Action)(() => tbWPIndex.Text = data[48].ToString())); //Waypoint index
2355 - 1753
            Dispatcher.Invoke((Action)(() => lblWPIndexNC.Content = data[48].ToString()));
2347 - 1754
            if(data[48] > 0 && _wpIndex != data[48] -1 && wpList.Count > 0)
2342 - 1755
            {
2347 - 1756
                _setActiveWP(data[48]-1);
2355 - 1757
                if((data[67] & 2) == 2)
1758
                    Dispatcher.Invoke(() => {
1759
                        DataGridRow row;
1760
                        if (_wpIndex > -1)
1761
                        {
1762
                            row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpIndex);
1763
                            row.Background = new SolidColorBrush(Colors.Transparent);
1764
                            row.BorderBrush = new SolidColorBrush(Colors.Transparent);
1765
                            row.BorderThickness = new Thickness(0);
1766
                        }
1767
                        _wpIndex = data[48] - 1;
1768
                        row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpIndex);
2366 - 1769
                        row.Background = new SolidColorBrush(Color.FromArgb(80, 0, 255, 100));
1770
                        row.BorderBrush = new SolidColorBrush(Colors.SpringGreen);
2355 - 1771
                        row.BorderThickness = new Thickness(2);
1772
                        dgvWP.UpdateLayout();
1773
                    });
2347 - 1774
                _wpIndex = data[48]-1;
2342 - 1775
            }
2347 - 1776
            else
1777
            {
1778
                if ((data[48] == 0 || wpList.Count == 0) & MainMap.Markers.Contains(wpActiveMarker))
2355 - 1779
                {
2347 - 1780
                    Dispatcher.Invoke(() => MainMap.Markers.Remove(wpActiveMarker));
2355 - 1781
                    Dispatcher.Invoke(() =>
1782
                    {
1783
                        DataGridRow row;
2368 - 1784
                        if (_wpIndex > -1 && data[48] == 0 && wpList.Count > _wpIndex)
2355 - 1785
                        {
1786
                            row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpIndex);
1787
                            row.Background = new SolidColorBrush(Colors.Transparent);
1788
                            row.BorderBrush = new SolidColorBrush(Colors.Transparent);
1789
                            row.BorderThickness = new Thickness(0);
1790
                            _wpIndex = -1;
1791
                        }
1792
                    });
1793
 
1794
                }
2347 - 1795
            }
2342 - 1796
 
2287 - 1797
            Dispatcher.Invoke((Action)(() => tbWPCount.Text = data[49].ToString())); //Waypoints count
2355 - 1798
            Dispatcher.Invoke((Action)(() => lblWPCountNC.Content = data[49].ToString())); //Waypoints count
2340 - 1799
            _wpCount = data[49];
2287 - 1800
            Dispatcher.Invoke((Action)(() => tbTopSats.Text = data[50].ToString())); //Satellites
1801
 
1802
            //--------------- Capacity used ------------------------
1803
            i_16 = data[81];
1804
            i_16 = (Int16)(i_16 << 8);
1805
            iVal = data[80] + i_16;
1806
            Dispatcher.Invoke((Action)(() => tbCapacity.Text = iVal.ToString() + " mAh"));
1807
            Dispatcher.Invoke((Action)(() => tbTopCapacity.Text = iVal.ToString() + " mAh"));
1808
 
1809
            //--------------- Flying time ------------------------
1810
            i_16 = data[56];
1811
            i_16 = (Int16)(i_16 << 8);
1812
            iVal = data[55] + i_16;
1813
            TimeSpan t = TimeSpan.FromSeconds(iVal);
1814
            string Text = t.Hours.ToString("D2") + ":" + t.Minutes.ToString("D2") + ":" + t.Seconds.ToString("D2");
1815
            Dispatcher.Invoke((Action)(() => tbFTime.Text = Text.ToString()));
1816
            Dispatcher.Invoke((Action)(() => tbTopFTime.Text = Text.ToString()));
1817
 
1818
            //--------------- RC quality ------------------------
1819
            Dispatcher.Invoke((Action)(() => tbRCQ.Text = data[66].ToString()));
1820
            Dispatcher.Invoke((Action)(() => tbTopRC.Text = data[66].ToString()));
1821
 
2291 - 1822
            if(data[66] > _iThresholdRC)
1823
            {
1824
                _iRCLevelJitter = 0; _bVoiceRCLevelActive = false;
1825
                if (stbRCLevelAnim != null && _bAnimRCLevelActive)
1826
                {
1827
                    Dispatcher.Invoke(() => stbRCLevelAnim.Stop());
1828
                    _bAnimRCLevelActive = false;
1829
                }
1830
            }
1831
            else
1832
            {
1833
                if (_iRCLevelJitter < 20) _iRCLevelJitter++;
1834
                if (_iRCLevelJitter == 20)
1835
                {
1836
                    if (stbRCLevelAnim != null && !_bAnimRCLevelActive)
1837
                    {
1838
                        Dispatcher.Invoke(() => stbRCLevelAnim.Begin());
1839
                        _bAnimRCLevelActive = true;
1840
                    }
1841
                    if (_bVoiceRCLevelPlay && !_bVoiceRCLevelActive)
1842
                    {
2295 - 1843
                        Thread th = new Thread(() => _mediaPlayer("Voice\\RCLevel.mp3"));
1844
                        th.Start();
2291 - 1845
                        _bVoiceRCLevelActive = true;
1846
                    }
1847
                        _iRCLevelJitter++;
1848
                }
1849
            }
1850
 
2287 - 1851
            //--------------- NC Error ------------------------
1852
            Dispatcher.Invoke((Action)(() => tbNCErr.Text = data[69].ToString()));  //NC Errornumber
1853
            if (data[69] > 0)
1854
                _readNCError();
1855
            if (data[69] > 0 & data[69] < 44)
1856
                ErrorLog(LogMsgType.Error, "NC Error [" + data[69].ToString() + "]: " + NC_Error[data[69]]);
1857
            else
1858
                if (_bErrorLog) _clearErrorLog("NC Error");
1859
 
2298 - 1860
            //-------------FC / NC Status Flags
1861
            Dispatcher.Invoke((Action)(() => FC1_1.Background = ((data[67] & 1) ==1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_MOTOR_RUN                             0x01
1862
            Dispatcher.Invoke((Action)(() => FC1_2.Background = ((data[67] & 2) ==2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_FLY                                   0x02
1863
            Dispatcher.Invoke((Action)(() => FC1_3.Background = ((data[67] & 4) ==4) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_CALIBRATE                             0x04
1864
            Dispatcher.Invoke((Action)(() => FC1_4.Background = ((data[67] & 8) ==8) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_START                                 0x08
1865
            Dispatcher.Invoke((Action)(() => FC1_5.Background = ((data[67] & 16) ==16) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_EMERGENCY_LANDING                      0x10
1866
            Dispatcher.Invoke((Action)(() => FC1_6.Background = ((data[67] & 32) ==32) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_LOWBAT                         0x20
1867
 
1868
            Dispatcher.Invoke((Action)(() => FC2_1.Background = ((data[74] & 1) ==1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_CAREFREE                             0x01
1869
            Dispatcher.Invoke((Action)(() => FC2_2.Background = ((data[74] & 2) ==2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_ALTITUDE_CONTROL                     0x02
1870
            Dispatcher.Invoke((Action)(() => FC2_3.Background = ((data[74] & 4) ==4) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_RC_FAILSAVE_ACTIVE                      0x04
1871
            Dispatcher.Invoke((Action)(() => FC2_4.Background = ((data[74] & 8) ==8) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_OUT1_ACTIVE                          0x08
1872
            Dispatcher.Invoke((Action)(() => FC2_5.Background = ((data[74] & 16) ==16) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_OUT2_ACTIVE                        0x10
1873
            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
1874
            Dispatcher.Invoke((Action)(() => FC2_7.Background = ((data[74] & 64) ==64) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_AUTO_STARTING                              0x40
1875
            Dispatcher.Invoke((Action)(() => FC2_8.Background = ((data[74] & 128) ==128) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_AUTO_LANDING                             0x80
1876
 
1877
            Dispatcher.Invoke((Action)(() => NC1_2.Background = ((data[68] & 2) == 2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_PH                                     0x02
1878
            Dispatcher.Invoke((Action)(() => NC1_3.Background = ((data[68] & 4) == 4) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_CH                                     0x04
1879
            Dispatcher.Invoke((Action)(() => NC1_4.Background = ((data[68] & 8) == 8) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_RANGE_LIMIT                               0x08
1880
            Dispatcher.Invoke((Action)(() => NC1_5.Background = ((data[68] & 16) == 16) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_NOSERIALLINK                            0x10
1881
            Dispatcher.Invoke((Action)(() => NC1_6.Background = ((data[68] & 32) == 32) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_TARGET_REACHED                               0x20
1882
            Dispatcher.Invoke((Action)(() => NC1_7.Background = ((data[68] & 64) == 64) ? new SolidColorBrush(Colors.DodgerBlue) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_MANUAL_CONTROL                          0x40
1883
            Dispatcher.Invoke((Action)(() => NC1_8.Background = ((data[68] & 128) == 128) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// NC_FLAG_GPS_OK                                     0x80
2299 - 1884
 
1885
            //Sidebar StatusSymbols
1886
            Dispatcher.Invoke((Action)(() => tbSideBarStatusMotors.Background = ((data[67] & 1) ==1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_MOTOR_RUN                             0x01
1887
            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
1888
            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
1889
 
1890
            Dispatcher.Invoke((Action)(() => tbSideBarStatusCF.Background = ((data[74] & 1) == 1) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_CAREFREE                                0x01
1891
            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
1892
            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
1893
 
1894
            Dispatcher.Invoke((Action)(() => tbSideBarStatusEmergencyLanding.Background = ((data[67] & 16) == 16) ? new SolidColorBrush(Colors.LightCoral) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS_EMERGENCY_LANDING                   0x10
2304 - 1895
            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
1896
            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 - 1897
 
1898
            Dispatcher.Invoke((Action)(() => tbSideBarStatusAC.Background = ((data[74] & 2) ==2) ? new SolidColorBrush(Colors.LightSeaGreen) : new SolidColorBrush(Colors.Transparent)));// FC_STATUS2_ALTITUDE_CONTROL                         0x02
1899
            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
1900
            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
1901
 
1902
            Dispatcher.Invoke((Action)(() => tbSideBarStatusPH.Text = ((data[68] & 4) == 4) ? "CH" : "PH"));// NC_FLAG_PH 0x02 / NC_FLAG_CH 0x04
2304 - 1903
            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
1904
            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
1905
            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 - 1906
 
2324 - 1907
            _bAirborne = (data[67] & 2) == 2 ? true : false;
2287 - 1908
        }
1909
        /// <summary>
1910
        /// Navi-Ctrl WP data struct 'X'
1911
        /// called by index
1912
        /// </summary>
1913
        /// <param name="data">the received byte array to process</param>
1914
        void _processWPData(byte[] data)
1915
        {
2313 - 1916
            _iWPCount = data[0];
2287 - 1917
            _bGetWPCount = false;
1918
            if (data.Length >= 28)
1919
            {
1920
                Dispatcher.Invoke(() => lblWPIndex.Content = data[1].ToString());
1921
                Dispatcher.Invoke(() => lblWPCount.Content = data[0].ToString());
1922
                if (_bGetWP)
1923
                {
1924
                    if (data[1] == 1)
2315 - 1925
                    {
2333 - 1926
                        Dispatcher.Invoke(() =>
1927
                        {
2356 - 1928
                            wpList.Clear();
1929
                            _clearMapMarkers(typeof(CustomMarkerWP));
1930
                            if (mRouteWP != null)
1931
                                MainMap.Markers.Remove(mRouteWP);
1932
                            if (wpActiveMarker != null)
1933
                                MainMap.Markers.Remove(wpActiveMarker);
1934
                            lblWPRouteDistance.Content = "0 m";
1935
                            dtWaypoints.Rows.Clear();
2368 - 1936
                            _wpEdit = -1;_wpIndex = -1;
2318 - 1937
                        });
2315 - 1938
                    }
2287 - 1939
                    DataRow dr = dtWaypoints.NewRow();
1940
                    dr = Waypoints.toDataRow(data, dr);
2313 - 1941
                    dtWaypoints.Rows.Add(dr);
2363 - 1942
                    _createWP(new PointLatLng((double)dr[3], (double)dr[4]), (string)dr[2], (int)dr[1]);
2313 - 1943
                    Dispatcher.Invoke(() => dgvWP.Items.Refresh());
1944
                    Dispatcher.Invoke(() => _iWPIndex = data[1]);
2287 - 1945
                    if (data[1] == data[0])
1946
                    {
1947
                        _bGetWP = false;
2368 - 1948
                        _routeUpdate();
2287 - 1949
                    }
1950
 
1951
                }
1952
            }
1953
            else
1954
            {
1955
                Dispatcher.Invoke(() => lblWPIndex.Content = 0);
1956
                Dispatcher.Invoke(() => lblWPCount.Content = 0);
1957
            }
1958
        }
1959
        /// <summary>
1960
        /// OSD Menue 'L'
1961
        /// single page called by pagenumber
1962
        /// no autoupdate
1963
        /// </summary>
1964
        /// <param name="data">the received byte array to process</param>
1965
        void _processOSDSingle(byte[] data)
1966
        {
1967
            if (data.Length == 84)
1968
            {
1969
                string sMessage = "";
1970
                iOSDPage = data[0];
1971
                iOSDMax = data[1];
1972
                if (cbOSD.Items.Count != iOSDMax) _initOSDCB();
1973
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 2, data.Length - 4));
1974
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20)+ "\r", true);
1975
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20)+ "\r", false);
1976
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20)+ "\r", false);
1977
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20), false);
1978
                Dispatcher.Invoke(() => { cbOSD.SelectedValue = iOSDPage; });
1979
              //  lblOSDPageNr.Invoke((Action)(() => lblOSDPageNr.Text = iOSDPage.ToString("[0]")));
1980
 
1981
            }
1982
            //else
1983
            //    OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 84)");
1984
 
1985
        }
1986
        /// <summary>
1987
        /// OSD Menue 'H'
1988
        /// called by keys (0x01,0x02,0x03,0x04)
1989
        /// autoupdate
1990
        /// </summary>
1991
        /// <param name="data">the received byte array to process</param>
1992
        void _processOSDAuto(byte[] data)
1993
        {
1994
            if (data.Length == 81)
1995
            {
1996
                string sMessage = "";
1997
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length - 1));
1998
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20)+ "\r", true);
1999
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20)+ "\r", false);
2000
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20)+ "\r", false);
2001
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20), false);
2002
 
2003
            }
2004
            //else
2005
            //    OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 81)");
2006
        }
2007
 
2008
        #endregion processing received data
2009
 
2010
        #region controller messages
2011
        /// <summary> send message to controller to request data
2012
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
2013
        /// </summary>
2014
        /// <param name="CMDID"> the command ID </param>
2015
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
2016
        private void _sendControllerMessage(char CMDID, byte address)
2017
        {
2018
            if (serialPortCtrl.Port.IsOpen)
2019
            {
2020
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2021
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address);
2022
                serialStream.Write(bytes, 0, bytes.Length);
2023
 
2024
            }
2025
            else
2026
                Log(LogMsgType.Error, "NOT CONNECTED!");
2027
        }
2028
        /// <summary> send message to controller to request data
2029
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
2030
        /// </summary>
2031
        /// <param name="CMDID"> the command ID </param>
2032
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
2033
        /// <param name="data"> additional data for the request</param>
2034
        private void _sendControllerMessage(char CMDID, byte address, byte[] data)
2035
        {
2036
            if (serialPortCtrl.Port.IsOpen)
2037
            {
2038
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2039
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address, data);
2040
                serialStream.Write(bytes, 0, bytes.Length);
2041
 
2042
            }
2043
            else
2044
                Log(LogMsgType.Error, "NOT CONNECTED!");
2045
        }
2046
 
2047
        /// <summary>
2048
        /// start/stop continous polling of controller values
2049
        /// </summary>
2050
        /// <param name="b">start/stop switch</param>
2051
        void _readCont(bool b)
2052
        {
2053
            bReadContinously = b;
2054
            if (bReadContinously)
2055
            {
2056
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
2057
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
2058
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
2059
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); Thread.Sleep(10); }
2060
                // Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.LightGreen));
2061
                Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_G.png", UriKind.Relative)));
2062
            }
2063
            else
2064
            {
2065
                // Dispatcher.Invoke((Action)(() => rctConnection.Fill = Brushes.LightGray));
2066
                Dispatcher.Invoke(() => imageConn.Source = new BitmapImage(new Uri("Images/Data_W.png", UriKind.Relative)));
2067
                _bConnErr = false;
2068
            }
2069
            _iLifeCounter = 0;
2070
        }
2071
 
2072
        private void _getVersion()
2073
        {
2074
            _sendControllerMessage('v', 0);
2075
        }
2076
        /// <summary>
2077
        /// get FC version struct via NC
2078
        /// by sending '1' as data (not documented in wiki...)
2079
        /// returns HW error 255 (comment in uart1.c : tells the KopterTool that it is the FC-version)
2080
        /// </summary>
2081
        /// <param name="ctrl">controller number 1=FC</param> 
2082
        private void _getVersion(byte ctrl)
2083
        {
2084
            _sendControllerMessage('v', 0, new byte[1] { ctrl });
2085
        }
2086
        /// <summary>
2087
        /// Switch back to NC by sending the 'Magic Packet' 0x1B,0x1B,0x55,0xAA,0x00
2088
        /// </summary>
2089
        private void _switchToNC()
2090
        {
2091
            if (serialPortCtrl.Port.IsOpen)
2092
            {
2093
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2094
                byte[] bytes = new byte[5] { 0x1B, 0x1B, 0x55, 0xAA, 0x00 };
2095
                serialStream.Write(bytes, 0, bytes.Length);
2096
 
2097
                Thread.Sleep(100);
2098
                _getVersion();
2099
                Thread.Sleep(100);
2100
               // _OSDMenue(0);
2101
            }
2102
            else
2103
                Log(LogMsgType.Error, "NOT CONNECTED!");
2104
        }
2105
        /// <summary>
2106
        /// switch to FC
2107
        /// </summary>
2108
        private void _switchToFC()
2109
        {
2110
            _sendControllerMessage('u', 2, new byte[1] { (byte)0 });
2111
            Thread.Sleep(100);
2112
            _getVersion();
2113
            Thread.Sleep(100);
2114
          //  _OSDMenue(0);
2115
        }
2116
        /// <summary>
2117
        /// send RESET signal to FC
2118
        /// </summary>
2119
        private void _resetCtrl()
2120
        {
2121
            _sendControllerMessage('R', 1);
2122
        }
2123
        /// <summary>
2124
        /// poll the debug data (4sec subscription)
2125
        /// </summary>
2126
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
2127
        private void _readDebugData(bool auto)
2128
        {
2129
            byte interval = auto ? debugInterval : (byte)0;
2130
            _sendControllerMessage('d', 0, new byte[1] { debugInterval });
2131
        }
2132
        /// <summary>
2133
        /// poll the BL-CTRL status via NC (4sec subscription)
2134
        /// </summary>
2135
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
2136
        private void _readBLCtrl(bool auto)
2137
        {
2138
            byte interval = auto ? blctrlInterval : (byte)0;
2139
            _sendControllerMessage('k', 0, new byte[1] { interval });
2140
        }
2141
        /// <summary>
2142
        /// poll the NC data struct (4sec subscription)
2143
        /// </summary>
2144
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
2145
        private void _readNavData(bool auto)
2146
        {
2147
            byte interval = auto ? navctrlInterval : (byte)0;
2148
            _sendControllerMessage('o', 2, new byte[1] { interval });
2149
        }
2150
        /// <summary>
2151
        /// get the errortext for pending NC error
2152
        /// </summary>
2153
        private void _readNCError()
2154
        {
2155
            _sendControllerMessage('e', 2);
2156
        }
2157
        /// <summary>
2158
        /// request the Waypoint at index
2159
        /// </summary>
2160
        /// <param name="index"></param>
2161
        void _getpWP(int index)
2162
        {
2163
            if (serialPortCtrl.Port.IsOpen)
2164
            {
2165
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2166
                byte[] bytes = FlightControllerMessage.CreateMessage('x', 2, new byte[1] { (byte)index });
2167
                serialStream.Write(bytes, 0, bytes.Length);
2168
            }
2169
            else
2170
                Log(LogMsgType.Error, "NOT CONNECTED!");
2171
 
2172
        }
2173
        void _getWP()
2174
        {
2335 - 2175
            int iTimeout = 0;
2287 - 2176
            _bGetWPCount = true;
2315 - 2177
            _getpWP(1); //get the itemscount of wp
2335 - 2178
            while (_bGetWPCount & iTimeout < _iWPTimeout * 5)
2179
            {
2180
                Thread.Sleep(10);
2181
                iTimeout++;
2182
            }
2183
            if (_iWPCount > 0 & !_bGetWPCount)
2287 - 2184
                _getWPList();
2185
        }
2186
        void _getWPList()
2187
        {
2188
            _bGetWP = true;
2313 - 2189
            int iTimeout=0;
2190
            for (int j = 0; j < _iWPCount; j++)
2287 - 2191
            {
2192
                _getpWP(j + 1);
2313 - 2193
                iTimeout = 0;
2194
                while (_iWPIndex != j + 1 & iTimeout < _iWPTimeout * 5)
2195
                {
2196
                    Thread.Sleep(1);
2197
                    iTimeout++;
2198
                }
2287 - 2199
            }
2200
        }
2363 - 2201
        /// <summary>
2202
        /// Wrapper for _clearCopterWPList()
2203
        /// necessary, cause it is called by threadnew which does not like return values...
2204
        /// </summary>
2340 - 2205
        void clearCopterWPList()
2313 - 2206
        {
2340 - 2207
            _clearCopterWPList();
2208
        }
2363 - 2209
        /// <summary>
2210
        /// clear the WP list of the copter
2211
        /// by sending 'invalid' and index '0'
2212
        /// </summary>
2213
        /// <returns></returns>
2340 - 2214
        bool _clearCopterWPList()
2215
        {
2335 - 2216
            int iTimeout = 0;
2313 - 2217
            if (serialPortCtrl.Port.IsOpen)
2218
            {
2219
                byte[] bData = new byte[30];
2220
                for (int i = 0; i < 30; i++)
2221
                    bData[i] = 0;
2222
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2223
                byte[] bytes = FlightControllerMessage.CreateMessage('w', 2, bData); //delete all WP on Copter by sending 'invalid'(==0) at index 0
2224
                serialStream.Write(bytes, 0, bytes.Length);
2287 - 2225
 
2313 - 2226
                _iWPCount = -1;
2340 - 2227
                while (_iWPCount == -1 & iTimeout < _iWPTimeout)
2335 - 2228
                {
2313 - 2229
                    Thread.Sleep(10);
2335 - 2230
                    iTimeout++;
2231
                }
2313 - 2232
                Dispatcher.Invoke(() => lblWPCount.Content = _iWPCount.ToString());
2335 - 2233
                if (_iWPCount > -1)
2340 - 2234
                    return true;
2235
                else
2236
                    Log(LogMsgType.Error, "Timeout while sending list!");
2237
            }
2238
            else
2239
                Log(LogMsgType.Error, "NOT CONNECTED!");
2240
 
2241
            return false;
2242
}
2243
        void _sendWPList()
2244
        {
2362 - 2245
            _sendWPList(0);
2246
        }
2247
        void _sendWPList(int iStart)
2248
        {
2340 - 2249
            int iTimeout = 0;
2250
            if (serialPortCtrl.Port.IsOpen)
2251
            {
2252
                if (_clearCopterWPList())
2313 - 2253
                {
2362 - 2254
                    int k = 1;
2255
                    for (int i = iStart; i < dtWaypoints.Rows.Count; i++)
2335 - 2256
                    {
2362 - 2257
                        k = iStart > 0 ? k : -1;
2376 - 2258
                        _sendWayPoint(dtWaypoints.Rows[i], k, 'w',false);
2313 - 2259
 
2335 - 2260
                        _iWPCount = -1;
2261
                        iTimeout = 0;
2262
                        while (_iWPCount == -1 & iTimeout < _iWPTimeout * 5)
2263
                        {
2264
                            Thread.Sleep(10);
2265
                            iTimeout++;
2266
                        }
2267
                        if (_iWPCount == -1)
2268
                        {
2269
                            Log(LogMsgType.Error, "Timeout while sending list!");
2270
                            break;
2271
                        }
2272
                        Dispatcher.Invoke(() => lblWPCount.Content = _iWPCount.ToString());
2362 - 2273
                        k++;
2335 - 2274
                    }
2313 - 2275
                }
2276
            }
2277
            else
2278
                Log(LogMsgType.Error, "NOT CONNECTED!");
2279
 
2280
        }
2376 - 2281
        bool _sendWayPoint(DataRow dr, int index, char command,bool bSim)
2340 - 2282
        {
2313 - 2283
 
2340 - 2284
            if (serialPortCtrl.Port.IsOpen)
2285
            {
2286
                byte[] bData = new byte[30];
2287
                for (int i = 0; i < 30; i++)
2288
                    bData[i] = 0;
2289
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2290
                byte[] bytes;
2291
                int iVal;
2292
                double dVal;
2293
                NumberFormatInfo nfi = new NumberFormatInfo();
2294
                nfi.NumberDecimalSeparator = ",";
2295
 
2296
                //longitude
2297
                dVal = Convert.ToDouble(dr[4], nfi);
2298
                iVal = (int)(dVal * Math.Pow(10, 7));
2299
                bData[0] = (byte)(iVal & 0xff);
2300
                bData[1] = (byte)((iVal >> 8) & 0xff);
2301
                bData[2] = (byte)((iVal >> 16) & 0xff);
2302
                bData[3] = (byte)(iVal >> 24);
2303
                //latitude
2304
                dVal = Convert.ToDouble(dr[3], nfi);
2305
                iVal = (int)(dVal * Math.Pow(10, 7));
2306
                bData[4] = (byte)(iVal & 0xff);
2307
                bData[5] = (byte)((iVal >> 8) & 0xff);
2308
                bData[6] = (byte)((iVal >> 16) & 0xff);
2309
                bData[7] = (byte)(iVal >> 24);
2310
                //altitude
2311
                dVal = Convert.ToDouble(dr[5], nfi);
2312
                iVal = (int)(dVal * 10);
2313
                bData[8] = (byte)(iVal & 0xff);
2314
                bData[9] = (byte)((iVal >> 8) & 0xff);
2315
                bData[10] = (byte)((iVal >> 16) & 0xff);
2316
                bData[11] = (byte)(iVal >> 24);
2376 - 2317
                if(bSim)
2318
                    bData[12] = 3; //Status 'SIMULATE'
2340 - 2319
                //Status 'NEWDATA'
2376 - 2320
                else
2321
                    bData[12] = 1;
2340 - 2322
                //heading
2323
                iVal = Convert.ToInt16(dr[6]);
2324
                bData[13] = (byte)(iVal & 0xff);
2325
                bData[14] = (byte)((iVal >> 8) & 0xff);
2326
                //ToleranceRadius
2327
                bData[15] = Convert.ToByte(dr[9]);
2328
                //HoldTime
2329
                bData[16] = Convert.ToByte(dr[10]);
2330
                //Event_Flag
2331
                bData[17] = Convert.ToByte(dr[13]);
2332
                //Index
2333
                bData[18] = index > 0 ? (byte)index : Convert.ToByte((int)dr[0]);
2334
                //Type
2335
                bData[19] = Convert.ToByte(dr[1]);
2336
                //WP_EventChannelValue
2337
                bData[20] = Convert.ToByte(dr[14]);
2338
                //AltitudeRate
2339
                bData[21] = Convert.ToByte(dr[8]);
2340
                //Speed
2341
                bData[22] = Convert.ToByte(dr[7]);
2342
                //CamAngle
2343
                bData[23] = (byte)Convert.ToInt16(dr[12]);
2344
                //Name
2362 - 2345
                string s = index > 0 ? ((string)dr[2]).Substring(0, 1) + index.ToString() : (string)dr[2];
2346
                byte[] name = ASCIIEncoding.ASCII.GetBytes(s);
2340 - 2347
                bData[24] = name.Length > 0 ? name[0] : (byte)0;
2348
                bData[25] = name.Length > 1 ? name[1] : (byte)0;
2349
                bData[26] = name.Length > 2 ? name[2] : (byte)0;
2350
                bData[27] = name.Length > 3 ? name[3] : (byte)0;
2351
                //Autotrigger
2352
                bData[28] = Convert.ToByte(dr[11]);
2353
 
2356 - 2354
                bytes = FlightControllerMessage.CreateMessage(command, 2, bData);
2340 - 2355
                serialStream.Write(bytes, 0, bytes.Length);
2356
 
2357
                return true;
2358
            }
2359
 
2360
            return false;
2361
        }
2287 - 2362
        #region OSD-Menue
2363
 
2364
        /// <summary>
2365
        /// one time query of the OSD Menue with pagenumber
2366
        /// </summary>
2367
        /// <param name="iMenue">Menue page</param>
2368
        void _OSDMenue(int iMenue)
2369
        {
2370
            if (serialPortCtrl.Port.IsOpen)
2371
            {
2372
                if (iMenue > iOSDMax)
2373
                    iMenue = 0;
2374
                Stream serialStream = serialPortCtrl.Port.BaseStream;
2375
                byte[] bytes = FlightControllerMessage.CreateMessage('l', 0, new byte[1] { (byte)iMenue });
2376
                serialStream.Write(bytes, 0, bytes.Length);
2377
            }
2378
            else
2379
                Log(LogMsgType.Error, "NOT CONNECTED!");
2380
 
2381
        }
2382
        /// <summary>
2383
        /// call the OSDMenue and start autorefresh
2384
        ///  usually by sending a menuekey
2385
        /// 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)
2386
        /// therefore the value has to be negative (inverted) in order to distinguish from old (2 line) menuestyle
2387
        /// and must not have any bits of the menue keys 0x1 0x2 0x4 0x8 (0x10?) --> 0x20 = -33
2388
        /// </summary>
2389
        void _OSDMenueAutoRefresh()
2390
        {
2391
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)(-33)), OSDInterval });
2392
        }
2393
        void _OSDMenueAutoRefresh(byte key)
2394
        {
2395
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)~key), OSDInterval });
2396
        }
2397
        /// <summary>
2398
        /// initialize the OSD menue combobox
2399
        /// combox is filled by numbers from 0 to max pagenumber
2400
        /// </summary>
2401
        void _initOSDCB()
2402
        {
2403
            _bCBInit = true;
2404
            if (iOSDMax == 0)
2405
            {
2406
                _OSDMenue(0);
2407
                Thread.Sleep(10);
2408
            }
2409
            Dispatcher.Invoke((Action)(() => cbOSD.Items.Clear()));
2410
            for (int i = 0; i <= iOSDMax; i++)
2411
            {
2412
                Dispatcher.Invoke((Action)(() => cbOSD.Items.Add(i)));
2413
            }
2414
            Dispatcher.Invoke((Action)(() => cbOSD.SelectedItem = iOSDPage));
2415
            _bCBInit = false;
2416
        }
2417
        private void btnOSDForward_Click(object sender, RoutedEventArgs e)
2418
        {
2419
            iOSDPage++;
2420
            if (iOSDPage > iOSDMax)
2421
                iOSDPage = 0;
2422
 
2423
            _OSDMenue(iOSDPage);
2424
        }
2425
        private void btnOSDBackward_Click(object sender, RoutedEventArgs e)
2426
        {
2427
            iOSDPage--;
2428
            if (iOSDPage < 0)
2429
                iOSDPage = iOSDMax;
2430
 
2431
            _OSDMenue(iOSDPage);
2432
        }
2433
        private void btnOSDLeave_Click(object sender, RoutedEventArgs e)
2434
        {
2435
            _OSDMenueAutoRefresh(8);
2436
        }
2437
        private void btnOSDEnter_Click(object sender, RoutedEventArgs e)
2438
        {
2439
            _OSDMenueAutoRefresh(4);
2440
        }
2441
        private void cbOSD_DropDownClosing(object sender, EventArgs e)
2442
        {
2443
            if (!_bCBInit && cbOSD.SelectedIndex > -1)
2444
                _OSDMenue(cbOSD.SelectedIndex);
2445
        }
2446
        private void OSD(LogMsgType msgtype, string msg, bool bNew)
2447
        {
2448
            Dispatcher.Invoke(() =>
2449
            {
2450
                TextRange tr;
2451
                if (bNew)
2452
                {
2453
                    rtfOSD.SelectAll();
2454
                    rtfOSD.Selection.Text = string.Empty;
2455
                }
2456
                tr = new TextRange(rtfOSD.Document.ContentEnd, rtfOSD.Document.ContentEnd);
2457
                tr.Text = msg;
2458
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(LogMsgTypeColor[(int)msgtype]));
2459
                //     rtfOSD.AppendText("\r");
2460
                rtfOSD.ScrollToEnd();
2461
 
2462
            });
2463
        }
2464
 
2465
        #endregion OSD-Menue
2466
 
2467
        #endregion controller messages
2468
 
2295 - 2469
        void _mediaPlayer(string file)
2470
        {
2471
            if (File.Exists(file))
2472
            {
2473
                MediaPlayer.MediaPlayer mp = new MediaPlayer.MediaPlayer();
2474
                mp.Open(file);
2475
                mp.Play();
2476
            }
2477
        }
2310 - 2478
 
2362 - 2479
        #region ui
2310 - 2480
        /// <summary>
2481
        /// Switch between fullscreen and normal window mode
2482
        /// save & restore scaling settings
2483
        /// </summary>
2484
        /// <param name="sender"></param>
2485
        /// <param name="e"></param>
2287 - 2486
        private void imageFullscreen_MouseDown(object sender, MouseButtonEventArgs e)
2487
        {
2488
            if (winState.isMaximized)
2489
            {
2490
                winState.Restore(this);
2491
                imageFullscreen.Source = new BitmapImage(new Uri("Images/Fullscreen.png", UriKind.Relative));
2492
                if(_bSaveWinStateFull)
2493
                    _saveScaleSliders(true);
2494
                if(_bSaveWinStateNormal)
2495
                    _setScaleSliders(false);
2496
            }
2497
            else
2498
            {
2499
                winState.Maximize(this);
2500
                imageFullscreen.Source = new BitmapImage(new Uri("Images/RestoreScreen.png", UriKind.Relative));
2501
                if(_bSaveWinStateNormal)
2502
                    _saveScaleSliders(false);
2503
                if(_bSaveWinStateFull)
2504
                    _setScaleSliders(true);
2505
            }
2506
        }
2507
 
2508
        /// <summary>
2509
        /// reset the scaling of all UI elements to default
2510
        /// </summary>
2511
        /// <param name="sender"></param>
2512
        /// <param name="e"></param>
2513
        private void buttonUIScaleReset_Click(object sender, RoutedEventArgs e)
2514
        {
2515
            UIScaleHorizonSlider.Value =
2516
                UIScaleLOGSlider.Value =
2517
                UIScaleMotorsSlider.Value =
2518
                UIScaleOSDSlider.Value =
2519
                UIScaleSlider.Value =
2520
                UIScaleTopSlider.Value = 1;
2521
        }
2522
        /// <summary>
2523
        /// adjust the top postion of UI elements below the top bar to fit the bottom position of the bar when scaling the top bar
2524
        /// </summary>
2525
        /// <param name="sender"></param>
2526
        /// <param name="e"></param>
2527
        private void UIScaleTopSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
2528
        {
2529
            GridSettings.Margin = new Thickness(GridSettings.Margin.Left, 36 * UIScaleTopSlider.Value, GridSettings.Margin.Right, GridSettings.Margin.Bottom);
2530
            if (GridMotors != null)
2531
                GridMotors.Margin = new Thickness(GridMotors.Margin.Left, 36 * UIScaleTopSlider.Value, GridMotors.Margin.Right, GridMotors.Margin.Bottom);
2532
            if (GridSideBar != null)
2533
                GridSideBar.Margin = new Thickness(GridSideBar.Margin.Left, 36 * UIScaleTopSlider.Value, GridSideBar.Margin.Right, GridSideBar.Margin.Bottom);
2534
            if (GridOSD != null)
2535
                GridOSD.Margin = new Thickness(GridOSD.Margin.Left, 36 * UIScaleTopSlider.Value, GridOSD.Margin.Right, GridOSD.Margin.Bottom);
2536
            if (GridData != null)
2537
                GridData.Margin = new Thickness(GridData.Margin.Left, 36 * UIScaleTopSlider.Value, GridData.Margin.Right, GridData.Margin.Bottom);
2538
            if (GridWP != null)
2539
                GridWP.Margin = new Thickness(GridWP.Margin.Left, 36 * UIScaleTopSlider.Value, GridWP.Margin.Right, GridWP.Margin.Bottom);
2540
        }
2310 - 2541
        /// <summary>
2542
        /// restore the saved scalings for the fullscreen/normal window mode
2543
        /// </summary>
2544
        /// <param name="bFull">the mode the window is set to</param>
2287 - 2545
        void _setScaleSliders(bool bFull)
2546
        {
2547
            if(bFull)
2548
            {
2549
                UIScaleSlider.Value = scaleFullAll;
2550
                UIScaleTopSlider.Value = scaleFullTopBar;
2551
                UIScaleMotorsSlider.Value = scaleFullMotors;
2552
                UIScaleOSDSlider.Value = scaleFullOSD;
2553
                UIScaleLOGSlider.Value = scaleFullLOG;
2554
                UIScaleHorizonSlider.Value = scaleFullHorizon;
2555
            }
2556
            else
2557
            {
2558
                UIScaleSlider.Value = scaleNormalAll;
2559
                UIScaleTopSlider.Value = scaleNormalTopBar;
2560
                UIScaleMotorsSlider.Value = scaleNormalMotors;
2561
                UIScaleOSDSlider.Value = scaleNormalOSD;
2562
                UIScaleLOGSlider.Value = scaleNormalLOG;
2563
                UIScaleHorizonSlider.Value = scaleNormalHorizon;
2564
            }
2565
        }
2566
 
2310 - 2567
        /// <summary>
2568
        /// save the scalings for the actual window mode
2569
        /// </summary>
2570
        /// <param name="bFull">the actual window mode</param>
2287 - 2571
        void _saveScaleSliders(bool bFull)
2572
        {
2573
 
2574
            if (bFull)
2575
            {
2576
                scaleFullAll = UIScaleSlider.Value;
2577
                scaleFullTopBar = UIScaleTopSlider.Value;
2578
                scaleFullMotors = UIScaleMotorsSlider.Value;
2579
                scaleFullOSD = UIScaleOSDSlider.Value;
2580
                scaleFullLOG = UIScaleLOGSlider.Value;
2581
                scaleFullHorizon = UIScaleHorizonSlider.Value;
2582
            }
2583
            else
2584
            {
2585
                scaleNormalAll = UIScaleSlider.Value;
2586
                scaleNormalTopBar = UIScaleTopSlider.Value;
2587
                scaleNormalMotors = UIScaleMotorsSlider.Value;
2588
                scaleNormalOSD = UIScaleOSDSlider.Value;
2589
                scaleNormalLOG = UIScaleLOGSlider.Value;
2590
                scaleNormalHorizon = UIScaleHorizonSlider.Value;
2591
            }
2592
        }
2362 - 2593
        #endregion ui
2287 - 2594
 
2595
        /// <summary>
2596
        /// read settings from ini-file
2597
        /// </summary>
2598
        void _readIni()
2599
        {
2600
            if (!File.Exists(filePath + "\\MKLiveViewSettings.ini"))
2601
                _writeIni();
2602
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
2603
            ini.path = filePath + "\\MKLiveViewSettings.ini";
2312 - 2604
            try
2605
            {
2287 - 2606
 
2312 - 2607
                string sVal = ini.IniReadValue("timings", "AutorefreshDebugData");
2608
                if (sVal != "") _debugDataAutorefresh = Convert.ToBoolean(sVal);
2609
                sVal = ini.IniReadValue("timings", "AutorefreshNavCtrlData");
2610
                if (sVal != "") _navCtrlDataAutorefresh = Convert.ToBoolean(sVal);
2611
                sVal = ini.IniReadValue("timings", "AutorefreshBLCtrlData");
2612
                if (sVal != "") _blctrlDataAutorefresh = Convert.ToBoolean(sVal);
2613
                sVal = ini.IniReadValue("timings", "AutorefreshOSDData");
2614
                if (sVal != "") _OSDAutorefresh = Convert.ToBoolean(sVal);
2287 - 2615
 
2312 - 2616
                sVal = ini.IniReadValue("timings", "IntervalDebugData");
2617
                if (sVal != "") debugInterval = (byte)Convert.ToInt16(sVal);
2618
                sVal = ini.IniReadValue("timings", "IntervalNavCtrlData");
2619
                if (sVal != "") navctrlInterval = (byte)Convert.ToInt16(sVal);
2620
                sVal = ini.IniReadValue("timings", "IntervalBLCtrlData");
2621
                if (sVal != "") blctrlInterval = (byte)Convert.ToInt16(sVal);
2622
                sVal = ini.IniReadValue("timings", "IntervalOSDData");
2623
                if (sVal != "") OSDInterval = (byte)Convert.ToInt16(sVal);
2287 - 2624
 
2312 - 2625
                sVal = ini.IniReadValue("topBar", "voltage");
2626
                if (sVal != "") chkBoxTopBarShowVoltage.IsChecked = Convert.ToBoolean(sVal);
2627
                sVal = ini.IniReadValue("topBar", "capacity");
2628
                if (sVal != "") chkBoxTopBarShowCapacity.IsChecked = Convert.ToBoolean(sVal);
2629
                sVal = ini.IniReadValue("topBar", "current");
2630
                if (sVal != "") chkBoxTopBarShowCurrent.IsChecked = Convert.ToBoolean(sVal);
2631
                sVal = ini.IniReadValue("topBar", "flightTime");
2632
                if (sVal != "") chkBoxTopBarShowFlightTime.IsChecked = Convert.ToBoolean(sVal);
2633
                sVal = ini.IniReadValue("topBar", "distanceHP");
2634
                if (sVal != "") chkBoxTopBarShowDistanceHP.IsChecked = Convert.ToBoolean(sVal);
2635
                sVal = ini.IniReadValue("topBar", "height");
2636
                if (sVal != "") chkBoxTopBarShowHeight.IsChecked = Convert.ToBoolean(sVal);
2637
                sVal = ini.IniReadValue("topBar", "speed");
2638
                if (sVal != "") chkBoxTopBarShowSpeed.IsChecked = Convert.ToBoolean(sVal);
2639
                sVal = ini.IniReadValue("topBar", "magneticField");
2640
                if (sVal != "") chkBoxTopBarShowMF.IsChecked = Convert.ToBoolean(sVal);
2641
                sVal = ini.IniReadValue("topBar", "satellites");
2642
                if (sVal != "") chkBoxTopBarShowSatellites.IsChecked = Convert.ToBoolean(sVal);
2643
                sVal = ini.IniReadValue("topBar", "rc");
2644
                if (sVal != "") chkBoxTopBarShowRC.IsChecked = Convert.ToBoolean(sVal);
2287 - 2645
 
2312 - 2646
                sVal = ini.IniReadValue("style", "saveFullScreen");
2647
                if (sVal != "") chkBoxSaveFullScreenState.IsChecked = Convert.ToBoolean(sVal);
2648
                sVal = ini.IniReadValue("style", "saveNormalState");
2649
                if (sVal != "") chkBoxSaveNormalState.IsChecked = Convert.ToBoolean(sVal);
2287 - 2650
 
2312 - 2651
                sVal = ini.IniReadValue("style", "scaleNormalAll");
2652
                if (sVal != "") scaleNormalAll = Convert.ToDouble(sVal);
2653
                sVal = ini.IniReadValue("style", "scaleNormalTopBar");
2654
                if (sVal != "") scaleNormalTopBar = Convert.ToDouble(sVal);
2655
                sVal = ini.IniReadValue("style", "scaleNormalMotors");
2656
                if (sVal != "") scaleNormalMotors = Convert.ToDouble(sVal);
2657
                sVal = ini.IniReadValue("style", "scaleNormalOSD");
2658
                if (sVal != "") scaleNormalOSD = Convert.ToDouble(sVal);
2659
                sVal = ini.IniReadValue("style", "scaleNormalLOG");
2660
                if (sVal != "") scaleNormalLOG = Convert.ToDouble(sVal);
2661
                sVal = ini.IniReadValue("style", "scaleNormalHorizon");
2662
                if (sVal != "") scaleNormalHorizon = Convert.ToDouble(sVal);
2287 - 2663
 
2312 - 2664
                sVal = ini.IniReadValue("style", "scaleFullAll");
2665
                if (sVal != "") scaleFullAll = Convert.ToDouble(sVal);
2666
                sVal = ini.IniReadValue("style", "scaleFullTopBar");
2667
                if (sVal != "") scaleFullTopBar = Convert.ToDouble(sVal);
2668
                sVal = ini.IniReadValue("style", "scaleFullMotors");
2669
                if (sVal != "") scaleFullMotors = Convert.ToDouble(sVal);
2670
                sVal = ini.IniReadValue("style", "scaleFullOSD");
2671
                if (sVal != "") scaleFullOSD = Convert.ToDouble(sVal);
2672
                sVal = ini.IniReadValue("style", "scaleFullLOG");
2673
                if (sVal != "") scaleFullLOG = Convert.ToDouble(sVal);
2674
                sVal = ini.IniReadValue("style", "scaleFullHorizon");
2675
                if (sVal != "") scaleFullHorizon = Convert.ToDouble(sVal);
2287 - 2676
 
2312 - 2677
                sVal = ini.IniReadValue("general", "LiPoCells");
2678
                _LipoCells = Convert.ToInt16(sVal);
2679
                sVal = ini.IniReadValue("general", "Motors");
2680
                if (sVal != "") _iMotors = Convert.ToInt16(sVal);
2287 - 2681
 
2312 - 2682
                sVal = ini.IniReadValue("map", "followMe");
2683
                if (sVal != "") _bFollowCopter = Convert.ToBoolean(sVal);
2684
                sVal = ini.IniReadValue("map", "AutoSetHome");
2685
                if (sVal != "") _bAutoHome = Convert.ToBoolean(sVal);
2324 - 2686
                sVal = ini.IniReadValue("map", "GPXLog");
2687
                if (sVal != "") _bGPXLog = Convert.ToBoolean(sVal);
2287 - 2688
 
2312 - 2689
                sVal = ini.IniReadValue("threshold", "VoltageWarning");
2690
                if(sVal != "") _dThresholdVoltageWarn = Convert.ToDouble(sVal);
2691
                sVal = ini.IniReadValue("threshold", "VoltageCritical");
2692
                if(sVal != "") _dThresholdVoltageCrit = Convert.ToDouble(sVal);
2693
                sVal = ini.IniReadValue("threshold", "VoiceVoltageEnable");
2694
                if(sVal != "") _bVoiceVoltPlay = Convert.ToBoolean(sVal);
2695
                sVal = ini.IniReadValue("threshold", "VoiceSatFixEnable");
2696
                if(sVal != "") _bVoiceSatFixPlay = Convert.ToBoolean(sVal);
2697
                sVal = ini.IniReadValue("threshold", "VoiceMagFieldEnable");
2698
                if(sVal != "") _bVoiceMagneticFieldPlay = Convert.ToBoolean(sVal);
2699
                sVal = ini.IniReadValue("threshold", "DistanceWarning");
2700
                if(sVal != "") _dThresholdDistanceWarn = Convert.ToDouble(sVal);
2701
                sVal = ini.IniReadValue("threshold", "VoiceDistanceWarnEnable");
2702
                if(sVal != "") _bVoiceDistancePlay = Convert.ToBoolean(sVal);
2703
                sVal = ini.IniReadValue("threshold", "VoiceRCLevelWarnEnable");
2704
                if(sVal != "") _bVoiceRCLevelPlay = Convert.ToBoolean(sVal);
2705
                sVal = ini.IniReadValue("threshold", "MaxDistance");
2706
                if(sVal != "") _dThresholdDistanceMax = Convert.ToDouble(sVal);
2707
                sVal = ini.IniReadValue("threshold", "RCThreshold");
2708
                if(sVal != "") _iThresholdRC = Convert.ToInt32(sVal);
2709
                sVal = ini.IniReadValue("threshold", "MagFieldThreshold");
2710
                if(sVal != "") _iThresholdMagField = Convert.ToInt32(sVal);
2321 - 2711
 
2712
                sVal = ini.IniReadValue("waypoints", "wpcolor");
2713
                if(sVal != "") comboBoxWPColor.SelectedIndex = Convert.ToInt32(sVal);
2714
                sVal = ini.IniReadValue("waypoints", "poicolor");
2715
                if(sVal != "") comboBoxPOIColor.SelectedIndex = Convert.ToInt32(sVal);
2716
                sVal = ini.IniReadValue("waypoints", "fscolor");
2717
                if(sVal != "") comboBoxFSColor.SelectedIndex = Convert.ToInt32(sVal);
2718
                sVal = ini.IniReadValue("waypoints", "coptercolor");
2719
                if(sVal != "") comboBoxCopterColor.SelectedIndex = Convert.ToInt32(sVal);
2328 - 2720
                sVal = ini.IniReadValue("waypoints", "routecolor");
2721
                if(sVal != "") comboBoxRouteColor.SelectedIndex = Convert.ToInt32(sVal);
2722
                sVal = ini.IniReadValue("waypoints", "showWPRoute");
2723
                if(sVal != "") _bShowWPRoute = Convert.ToBoolean(sVal);
2349 - 2724
 
2725
                for (int i = 0; i < 12; i++)
2726
                {
2727
                    sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "Val");
2728
                    if (sVal != "")
2729
                        serChan[i] = Convert.ToInt16(sVal);
2730
                    sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "Title");
2731
                    if (sVal != "")
2732
                        serChanTitle[i] = sVal;
2733
                    for (int y = 0; i < 4 && y < 3; y++)
2734
                    {
2735
                        sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "ValSub" + y.ToString());
2736
                        if (sVal != "")
2737
                            serChan_sub[(i * 3) + y] = Convert.ToInt16(sVal);
2738
                    }
2739
                }
2740
 
2312 - 2741
            }
2742
            catch (Exception e)
2743
            {
2287 - 2744
 
2312 - 2745
                MessageBox.Show("Error parsing ini-file!" + Environment.NewLine + e.Message,"Read ini-file" ,MessageBoxButton.OK,MessageBoxImage.Error);
2746
            }
2747
 
2287 - 2748
        }
2749
 
2750
        /// <summary>
2751
        /// save settings to ini-file
2752
        /// </summary>
2753
        void _writeIni()
2754
        {
2755
 
2756
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
2757
            ini.path = filePath + "\\MKLiveViewSettings.ini";
2758
 
2312 - 2759
            try
2760
            {
2287 - 2761
 
2312 - 2762
                ini.IniWriteValue("timings", "AutorefreshDebugData", _debugDataAutorefresh ? "true" : "false");
2763
                ini.IniWriteValue("timings", "AutorefreshNavCtrlData", _navCtrlDataAutorefresh ? "true" : "false");
2764
                ini.IniWriteValue("timings", "AutorefreshBLCtrlData", _blctrlDataAutorefresh ? "true" : "false");
2765
                ini.IniWriteValue("timings", "AutorefreshOSDData", _OSDAutorefresh ? "true" : "false");
2287 - 2766
 
2312 - 2767
                ini.IniWriteValue("timings", "IntervalDebugData", debugInterval.ToString());
2768
                ini.IniWriteValue("timings", "IntervalNavCtrlData", navctrlInterval.ToString());
2769
                ini.IniWriteValue("timings", "IntervalBLCtrlData", blctrlInterval.ToString());
2770
                ini.IniWriteValue("timings", "IntervalOSDData", OSDInterval.ToString());
2287 - 2771
 
2312 - 2772
                ini.IniWriteValue("general", "LiPoCells", _LipoCells.ToString());
2773
                ini.IniWriteValue("general", "Motors", _iMotors.ToString());
2287 - 2774
 
2312 - 2775
                ini.IniWriteValue("map", "followMe", _bFollowCopter.ToString());
2776
                ini.IniWriteValue("map", "AutoSetHome", _bAutoHome.ToString());
2324 - 2777
                ini.IniWriteValue("map", "GPXLog", _bGPXLog.ToString());
2287 - 2778
 
2312 - 2779
                ini.IniWriteValue("topBar", "voltage", chkBoxTopBarShowVoltage.IsChecked.ToString());
2780
                ini.IniWriteValue("topBar", "capacity", chkBoxTopBarShowCapacity.IsChecked.ToString());
2781
                ini.IniWriteValue("topBar", "current", chkBoxTopBarShowCurrent.IsChecked.ToString());
2782
                ini.IniWriteValue("topBar", "flightTime", chkBoxTopBarShowFlightTime.IsChecked.ToString());
2783
                ini.IniWriteValue("topBar", "distanceHP", chkBoxTopBarShowDistanceHP.IsChecked.ToString());
2784
                ini.IniWriteValue("topBar", "height", chkBoxTopBarShowHeight.IsChecked.ToString());
2785
                ini.IniWriteValue("topBar", "speed", chkBoxTopBarShowSpeed.IsChecked.ToString());
2786
                ini.IniWriteValue("topBar", "magneticField", chkBoxTopBarShowMF.IsChecked.ToString());
2787
                ini.IniWriteValue("topBar", "satellites", chkBoxTopBarShowSatellites.IsChecked.ToString());
2788
                ini.IniWriteValue("topBar", "rc", chkBoxTopBarShowRC.IsChecked.ToString());
2287 - 2789
 
2312 - 2790
                ini.IniWriteValue("style", "saveFullScreen", chkBoxSaveFullScreenState.IsChecked.ToString());
2791
                ini.IniWriteValue("style", "saveNormalState", chkBoxSaveNormalState.IsChecked.ToString());
2287 - 2792
 
2312 - 2793
                ini.IniWriteValue("style", "scaleNormalAll", scaleNormalAll.ToString());
2794
                ini.IniWriteValue("style", "scaleNormalTopBar", scaleNormalTopBar.ToString());
2795
                ini.IniWriteValue("style", "scaleNormalMotors", scaleNormalMotors.ToString());
2796
                ini.IniWriteValue("style", "scaleNormalOSD", scaleNormalOSD.ToString());
2797
                ini.IniWriteValue("style", "scaleNormalLOG", scaleNormalLOG.ToString());
2798
                ini.IniWriteValue("style", "scaleNormalHorizon", scaleNormalHorizon.ToString());
2287 - 2799
 
2312 - 2800
                ini.IniWriteValue("style", "scaleFullAll", scaleFullAll.ToString());
2801
                ini.IniWriteValue("style", "scaleFullTopBar", scaleFullTopBar.ToString());
2802
                ini.IniWriteValue("style", "scaleFullMotors", scaleFullMotors.ToString());
2803
                ini.IniWriteValue("style", "scaleFullOSD", scaleFullOSD.ToString());
2804
                ini.IniWriteValue("style", "scaleFullLOG", scaleFullLOG.ToString());
2805
                ini.IniWriteValue("style", "scaleFullHorizon", scaleFullHorizon.ToString());
2287 - 2806
 
2312 - 2807
                ini.IniWriteValue("style", "horizon", chkBoxShowHorizon.IsChecked.ToString());
2808
 
2809
                ini.IniWriteValue("threshold", "VoltageWarning", _dThresholdVoltageWarn.ToString());
2810
                ini.IniWriteValue("threshold", "VoltageCritical", _dThresholdVoltageCrit.ToString());
2811
                ini.IniWriteValue("threshold", "VoiceVoltageEnable", _bVoiceVoltPlay.ToString());
2812
                ini.IniWriteValue("threshold", "VoiceSatFixEnable", _bVoiceSatFixPlay.ToString());
2813
                ini.IniWriteValue("threshold", "VoiceMagFieldEnable", _bVoiceMagneticFieldPlay.ToString());
2814
                ini.IniWriteValue("threshold", "VoiceDistanceWarnEnable", _bVoiceDistancePlay.ToString());
2815
                ini.IniWriteValue("threshold", "VoiceRCLevelWarnEnable", _bVoiceRCLevelPlay.ToString());
2816
                ini.IniWriteValue("threshold", "DistanceWarning", _dThresholdDistanceWarn.ToString());
2817
                ini.IniWriteValue("threshold", "MaxDistance", _dThresholdDistanceMax.ToString());
2818
                ini.IniWriteValue("threshold", "RCThreshold", _iThresholdRC.ToString());
2819
                ini.IniWriteValue("threshold", "MagFieldThreshold", _iThresholdMagField.ToString());
2321 - 2820
 
2821
                ini.IniWriteValue("waypoints", "wpcolor", comboBoxWPColor.SelectedIndex.ToString());
2822
                ini.IniWriteValue("waypoints", "poicolor", comboBoxPOIColor.SelectedIndex.ToString());
2823
                ini.IniWriteValue("waypoints", "fscolor", comboBoxFSColor.SelectedIndex.ToString());
2824
                ini.IniWriteValue("waypoints", "coptercolor", comboBoxCopterColor.SelectedIndex.ToString());
2328 - 2825
                ini.IniWriteValue("waypoints", "routecolor", comboBoxRouteColor.SelectedIndex.ToString());
2826
                ini.IniWriteValue("waypoints", "showWPRoute", _bShowWPRoute.ToString());
2349 - 2827
 
2828
                for (int i = 0; i < 12; i++)
2829
                {
2830
                    ini.IniWriteValue("serial", "ch" + i.ToString() + "Val", serChan[i].ToString());
2831
                    ini.IniWriteValue("serial", "ch" + i.ToString() + "Title", serChanTitle[i]);
2832
                    for (int y = 0; i < 4 && y < 3; y++)
2833
                    {
2834
                        ini.IniWriteValue("serial", "ch" + i.ToString() + "ValSub" + y.ToString(), serChan_sub[(i * 3) + y].ToString());
2835
                    }
2836
                }
2837
 
2312 - 2838
            }
2839
            catch (Exception e)
2840
            {
2841
 
2842
                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);
2843
            }
2287 - 2844
        }
2350 - 2845
 
2349 - 2846
        #region serial channels
2847
        /// <summary>
2848
        /// Sending the serial channel values
2849
        /// </summary>
2850
        void _sendSerialData()
2851
        {
2852
            byte[] serData = new byte[12];
2853
            for (int i = 0; i < 12; i++)
2854
            {
2855
                serData[i] = unchecked((byte)(serChan[i] - 127));
2856
            }
2857
            _sendControllerMessage('y', 1, serData);
2858
        }
2859
        /// <summary>
2860
        /// init the controls for displaying
2861
        /// and setting serial control channels
2862
        /// </summary>
2863
        void _initSerialCtrl()
2864
        {
2865
            SerChan1ScaleSlider.Value = serChan[0];
2866
            textBoxSerial1.Text = serChanTitle[0];
2867
            SerChan2ScaleSlider.Value = serChan[1];
2868
            textBoxSerial2.Text = serChanTitle[1];
2350 - 2869
            SerChan3ScaleSlider.Value = serChan[2];
2870
            textBoxSerial3.Text = serChanTitle[2];
2349 - 2871
            //SerChan4ScaleSlider.Value = serChan[3];
2872
            //textBoxSerial4.Text = serChanTitle[3];
2873
            //trckbarSerial5.Value = serChan[4];
2874
            //textBoxSerial5.Text = serChanTitle[4];
2875
            //trckbarSerial6.Value = serChan[5];
2876
            //textBoxSerial6.Text = serChanTitle[5];
2877
            //trckbarSerial7.Value = serChan[6];
2878
            //textBoxSerial7.Text = serChanTitle[6];
2879
            //trckbarSerial8.Value = serChan[7];
2880
            //textBoxSerial8.Text = serChanTitle[7];
2312 - 2881
 
2349 - 2882
            textBoxSerial1_val1.Text = serChan_sub[0].ToString();
2883
            textBoxSerial1_val2.Text = serChan_sub[1].ToString();
2884
            textBoxSerial1_val3.Text = serChan_sub[2].ToString();
2885
            textBoxSerial2_val1.Text = serChan_sub[3].ToString();
2886
            textBoxSerial2_val2.Text = serChan_sub[4].ToString();
2887
            textBoxSerial2_val3.Text = serChan_sub[5].ToString();
2350 - 2888
            textBoxSerial3_val1.Text = serChan_sub[6].ToString();
2889
            textBoxSerial3_val2.Text = serChan_sub[7].ToString();
2890
            textBoxSerial3_val3.Text = serChan_sub[8].ToString();
2349 - 2891
            //textBoxSerial4_val1.Text = serChan_sub[9].ToString();
2892
            //textBoxSerial4_val2.Text = serChan_sub[10].ToString();
2893
            //textBoxSerial4_val3.Text = serChan_sub[11].ToString();
2894
        }
2895
        private void SerChan1ScaleSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
2896
        {
2897
            if (!_init)
2898
            {
2899
                serChan[0] = (int)SerChan1ScaleSlider.Value;
2900
                _sendSerialData();
2901
            }
2902
        }
2903
        private void textBoxSerial1_TextChanged(object sender, TextChangedEventArgs e)
2904
        {
2905
            if (!_init)
2906
            {
2907
                serChanTitle[0] = textBoxSerial1.Text;
2908
            }
2909
        }
2910
        private void textBoxSerial1_val1_TextChanged(object sender, TextChangedEventArgs e)
2911
        {
2912
            if (textBoxSerial1_val1.Text.Length > 0 & !_init)
2913
            {
2914
                serChan_sub[0] = Convert.ToInt16(textBoxSerial1_val1.Text);
2915
            }
2916
        }
2917
        private void textBoxSerial1_val2_TextChanged(object sender, TextChangedEventArgs e)
2918
        {
2919
            if (textBoxSerial1_val2.Text.Length > 0 & !_init)
2920
            {
2921
                serChan_sub[1] = Convert.ToInt16(textBoxSerial1_val2.Text);
2922
            }
2923
        }
2924
        private void textBoxSerial1_val3_TextChanged(object sender, TextChangedEventArgs e)
2925
        {
2926
            if (textBoxSerial1_val3.Text.Length > 0 & !_init)
2927
            {
2928
                serChan_sub[2] = Convert.ToInt16(textBoxSerial1_val3.Text);
2929
            }
2930
        }
2931
        private void btnSer1_val1_Click(object sender, RoutedEventArgs e)
2932
        {
2933
            if (textBoxSerial1_val1.Text.Length > 0)
2934
            {
2935
                SerChan1ScaleSlider.Value = Convert.ToInt16(textBoxSerial1_val1.Text);
2936
            }
2937
        }
2938
        private void btnSer1_0_Click(object sender, RoutedEventArgs e)
2939
        {
2940
            SerChan1ScaleSlider.Value = 0;
2941
        }
2942
        private void btnSer1_127_Click(object sender, RoutedEventArgs e)
2943
        {
2944
            SerChan1ScaleSlider.Value = 127;
2945
        }
2946
        private void btnSer1_254_Click(object sender, RoutedEventArgs e)
2947
        {
2948
            SerChan1ScaleSlider.Value = 254;
2949
        }
2950
        private void btnSer1_val2_Click(object sender, RoutedEventArgs e)
2951
        {
2952
            if (textBoxSerial1_val2.Text.Length > 0)
2953
            {
2954
                SerChan1ScaleSlider.Value = Convert.ToInt16(textBoxSerial1_val2.Text);
2955
            }
2956
        }
2957
        private void btnSer1_val3_Click(object sender, RoutedEventArgs e)
2958
        {
2959
            if (textBoxSerial1_val3.Text.Length > 0)
2960
            {
2961
                SerChan1ScaleSlider.Value = Convert.ToInt16(textBoxSerial1_val3.Text);
2962
            }
2963
        }
2964
 
2965
        private void SerChan2ScaleSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
2966
        {
2967
            if (!_init)
2968
            {
2969
                serChan[1] = (int)SerChan2ScaleSlider.Value;
2970
                _sendSerialData();
2971
            }
2972
        }
2973
        private void textBoxSerial2_TextChanged(object sender, TextChangedEventArgs e)
2974
        {
2975
            if (!_init)
2976
            {
2977
                serChanTitle[1] = textBoxSerial2.Text;
2978
            }
2979
        }
2980
        private void textBoxSerial2_val1_TextChanged(object sender, TextChangedEventArgs e)
2981
        {
2982
            if (textBoxSerial2_val1.Text.Length > 0 & !_init)
2983
            {
2984
                serChan_sub[3] = Convert.ToInt16(textBoxSerial2_val1.Text);
2985
            }
2986
        }
2987
        private void textBoxSerial2_val2_TextChanged(object sender, TextChangedEventArgs e)
2988
        {
2989
            if (textBoxSerial2_val2.Text.Length > 0 & !_init)
2990
            {
2991
                serChan_sub[4] = Convert.ToInt16(textBoxSerial2_val2.Text);
2992
            }
2993
        }
2994
        private void textBoxSerial2_val3_TextChanged(object sender, TextChangedEventArgs e)
2995
        {
2996
            if (textBoxSerial2_val3.Text.Length > 0 & !_init)
2997
            {
2998
                serChan_sub[5] = Convert.ToInt16(textBoxSerial2_val3.Text);
2999
            }
3000
        }
3001
        private void btnSer2_0_Click(object sender, RoutedEventArgs e)
3002
        {
3003
            SerChan2ScaleSlider.Value = 0;
3004
        }
3005
        private void btnSer2_127_Click(object sender, RoutedEventArgs e)
3006
        {
3007
            SerChan2ScaleSlider.Value = 127;
3008
        }
3009
        private void btnSer2_254_Click(object sender, RoutedEventArgs e)
3010
        {
3011
            SerChan2ScaleSlider.Value = 254;
3012
        }
3013
        private void btnSer2_val1_Click(object sender, RoutedEventArgs e)
3014
        {
3015
            if (textBoxSerial2_val1.Text.Length > 0)
3016
            {
3017
                SerChan2ScaleSlider.Value = Convert.ToInt16(textBoxSerial2_val1.Text);
3018
            }
3019
        }
3020
        private void btnSer2_val2_Click(object sender, RoutedEventArgs e)
3021
        {
3022
            if (textBoxSerial2_val2.Text.Length > 0)
3023
            {
3024
                SerChan2ScaleSlider.Value = Convert.ToInt16(textBoxSerial2_val2.Text);
3025
            }
3026
        }
3027
        private void btnSer2_val3_Click(object sender, RoutedEventArgs e)
3028
        {
3029
            if (textBoxSerial2_val3.Text.Length > 0)
3030
            {
3031
                SerChan2ScaleSlider.Value = Convert.ToInt16(textBoxSerial2_val3.Text);
3032
            }
3033
        }
2350 - 3034
 
3035
        private void SerChan3ScaleSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
3036
        {
3037
            if (!_init)
3038
            {
3039
                serChan[2] = (int)SerChan3ScaleSlider.Value;
3040
                _sendSerialData();
3041
            }
3042
        }
3043
        private void textBoxSerial3_TextChanged(object sender, TextChangedEventArgs e)
3044
        {
3045
            if (!_init)
3046
            {
3047
                serChanTitle[2] = textBoxSerial3.Text;
3048
            }
3049
        }
3050
        private void textBoxSerial3_val1_TextChanged(object sender, TextChangedEventArgs e)
3051
        {
3052
            if (textBoxSerial3_val1.Text.Length > 0 & !_init)
3053
            {
3054
                serChan_sub[6] = Convert.ToInt16(textBoxSerial3_val1.Text);
3055
            }
3056
        }
3057
        private void textBoxSerial3_val2_TextChanged(object sender, TextChangedEventArgs e)
3058
        {
3059
            if (textBoxSerial3_val2.Text.Length > 0 & !_init)
3060
            {
3061
                serChan_sub[7] = Convert.ToInt16(textBoxSerial3_val2.Text);
3062
            }
3063
        }
3064
        private void textBoxSerial3_val3_TextChanged(object sender, TextChangedEventArgs e)
3065
        {
3066
            if (textBoxSerial3_val3.Text.Length > 0 & !_init)
3067
            {
3068
                serChan_sub[8] = Convert.ToInt16(textBoxSerial3_val3.Text);
3069
            }
3070
        }
3071
        private void btnSer3_0_Click(object sender, RoutedEventArgs e)
3072
        {
3073
            SerChan3ScaleSlider.Value = 0;
3074
        }
3075
        private void btnSer3_127_Click(object sender, RoutedEventArgs e)
3076
        {
3077
            SerChan3ScaleSlider.Value = 127;
3078
        }
3079
        private void btnSer3_254_Click(object sender, RoutedEventArgs e)
3080
        {
3081
            SerChan3ScaleSlider.Value = 254;
3082
        }
3083
        private void btnSer3_val1_Click(object sender, RoutedEventArgs e)
3084
        {
3085
            if (textBoxSerial3_val1.Text.Length > 0)
3086
            {
3087
                SerChan3ScaleSlider.Value = Convert.ToInt16(textBoxSerial3_val1.Text);
3088
            }
3089
        }
3090
        private void btnSer3_val2_Click(object sender, RoutedEventArgs e)
3091
        {
3092
            if (textBoxSerial3_val2.Text.Length > 0)
3093
            {
3094
                SerChan3ScaleSlider.Value = Convert.ToInt16(textBoxSerial3_val2.Text);
3095
            }
3096
        }
3097
        private void btnSer3_val3_Click(object sender, RoutedEventArgs e)
3098
        {
3099
            if (textBoxSerial3_val3.Text.Length > 0)
3100
            {
3101
                SerChan3ScaleSlider.Value = Convert.ToInt16(textBoxSerial3_val3.Text);
3102
            }
3103
        }
2349 - 3104
        /// <summary>
3105
        /// checks the input of a textbox
3106
        /// for valid data
3107
        /// in this case values 0-254
3108
        /// </summary>
3109
        /// <param name="sender"></param>
3110
        /// <param name="e"></param>
3111
        private void textBox_serial_KeyPress(object sender, KeyEventArgs e)
3112
        {
3113
            if ("1234567890,\b".IndexOf(e.Key.ToString()) < 0) //general check for valid chars(0-9) and backspace (\b)
3114
                e.Handled = true;
3115
            else
3116
            if ("\b".IndexOf(e.Key.ToString()) < 0)
3117
                if (Convert.ToInt16(((TextBox)sender).Text + e.Key) > 254) //if valid and not backspace, check for upper limit of the resulting number
3118
                    e.Handled = true;
3119
                else
3120
                {
3121
                    int i = -1;
3122
                    switch (((TextBox)sender).Name)
3123
                    {
3124
                        case "textBoxSerial1_val1":
3125
                            i = 0;
3126
                            break;
3127
                        case "textBoxSerial1_val2":
3128
                            i = 1;
3129
                            break;
3130
                        case "textBoxSerial1_val3":
3131
                            i = 2;
3132
                            break;
3133
                        case "textBoxSerial2_val1":
3134
                            i = 3;
3135
                            break;
3136
                        case "textBoxSerial2_val2":
3137
                            i = 4;
3138
                            break;
3139
                        case "textBoxSerial2_val3":
3140
                            i = 5;
3141
                            break;
3142
                        case "textBoxSerial3_val1":
3143
                            i = 6;
3144
                            break;
3145
                        case "textBoxSerial3_val2":
3146
                            i = 7;
3147
                            break;
3148
                        case "textBoxSerial3_val3":
3149
                            i = 8;
3150
                            break;
3151
                        case "textBoxSerial4_val1":
3152
                            i = 9;
3153
                            break;
3154
                        case "textBoxSerial4_val2":
3155
                            i = 10;
3156
                            break;
3157
                        case "textBoxSerial4_val3":
3158
                            i = 11;
3159
                            break;
3160
                    }
3161
                    if (i > -1)
3162
                        serChan_sub[i] = Convert.ToInt16(((TextBox)sender).Text + e.Key.ToString());
3163
                }
3164
        }
3165
 
3166
        #endregion serial channels
2315 - 3167
        #region WP
2312 - 3168
        void _readWPLFile()
3169
        {
3170
            Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
3171
            fd.Filter = "Waypointlists | *.wpl";
3172
            fd.Multiselect = false;
3173
            if (fd.ShowDialog().Value)
3174
            {
3175
                string file = fd.SafeFileName;
3176
                IniFile ini = new IniFile(fd.SafeFileName);
3177
                ini.path = fd.FileName;
3178
 
3179
                try
3180
                {
3181
                    string sVal = ini.IniReadValue("General", "FileVersion");
3182
                    if (sVal == "")
3183
                        MessageBox.Show("The file has no version declared - can't go on...", "", MessageBoxButton.OK, MessageBoxImage.Information);
3184
                    else
3185
                    {
3186
                        if (Convert.ToInt16(sVal) < 3)
3187
                            MessageBox.Show("The file version is not supported - can't go on...", "", MessageBoxButton.OK, MessageBoxImage.Information);
3188
                        else
3189
                        {
3190
                            sVal = ini.IniReadValue("General", "NumberOfWaypoints");
3191
                            if (sVal == "")
3192
                                MessageBox.Show("The file has no number of waypoints declared - can't go on...", "", MessageBoxButton.OK, MessageBoxImage.Information);
3193
                            else
3194
                            {
3195
                                int wpnum = Convert.ToInt16(sVal);
3196
                                string wp;
3197
                                int i;
2313 - 3198
                                NumberFormatInfo nfi = new NumberFormatInfo();
3199
                                nfi.NumberDecimalSeparator = ".";
2312 - 3200
                                dtWaypoints.Rows.Clear();
2368 - 3201
                                _wpEdit = -1;_wpIndex = -1;
2327 - 3202
                                _clearMapMarkers(typeof(CustomMarkerWP));
2363 - 3203
                                _clearMapMarkers(typeof(CustomMarkerWPActive));
2328 - 3204
                                wpList.Clear();
3205
                                if (mRouteWP != null)
3206
                                    MainMap.Markers.Remove(mRouteWP);
2363 - 3207
                                //if (wpActiveMarker != null)
3208
                                //    MainMap.Markers.Remove(wpActiveMarker);
2328 - 3209
                                Dispatcher.Invoke(() => lblWPRouteDistance.Content = "0 m");
3210
 
2312 - 3211
                                for (int k = 1; k <= wpnum; k++)
3212
                                {
3213
                                    DataRow dr = dtWaypoints.NewRow();
3214
                                    dr.ItemArray = new object[16];
3215
                                    object[] o = new object[16];
3216
                                    i = 0;
3217
                                    wp = "Point" + k.ToString();
3218
                                    o[i] = k;
3219
                                    i++;
3220
                                    sVal = ini.IniReadValue(wp, "Type");
3221
                                    if (sVal != "")
2315 - 3222
                                        o[i] = Convert.ToInt16(sVal) - 1;
2312 - 3223
                                    i++;
3224
                                    sVal = ini.IniReadValue(wp, "Prefix");
3225
                                    if (sVal != "")
2350 - 3226
                                        o[i] = sVal + k.ToString();
3227
                                   //     o[i] = sVal == "0" ? "!" + k.ToString() : sVal + k.ToString();
2312 - 3228
                                    i++;
2313 - 3229
                                    sVal = ini.IniReadValue(wp, "Latitude");
2312 - 3230
                                    if (sVal != "")
2313 - 3231
                                        o[i] = Convert.ToDouble(sVal, nfi);
2312 - 3232
                                    i++;
2313 - 3233
                                    sVal = ini.IniReadValue(wp, "Longitude");
2312 - 3234
                                    if (sVal != "")
2313 - 3235
                                        o[i] = Convert.ToDouble(sVal, nfi);
2312 - 3236
                                    i++;
3237
                                    sVal = ini.IniReadValue(wp, "Altitude");
3238
                                    if (sVal != "")
2313 - 3239
                                        o[i] = Convert.ToDouble(sVal, nfi);
2312 - 3240
                                    i++;
3241
                                    sVal = ini.IniReadValue(wp, "Heading");
3242
                                    if (sVal != "")
3243
                                        o[i] = Convert.ToInt16(sVal);
3244
                                    i++;
3245
                                    sVal = ini.IniReadValue(wp, "Speed");
3246
                                    if (sVal != "")
2315 - 3247
                                        o[i] = Convert.ToInt16(sVal);
2312 - 3248
                                    i++;
3249
                                    sVal = ini.IniReadValue(wp, "ClimbRate");
3250
                                    if (sVal != "")
3251
                                        o[i] = Convert.ToInt16(sVal);
3252
                                    i++;
3253
                                    sVal = ini.IniReadValue(wp, "Radius");
3254
                                    if (sVal != "")
3255
                                        o[i] = Convert.ToInt16(sVal);
3256
                                    i++;
3257
                                    sVal = ini.IniReadValue(wp, "DelayTime");
3258
                                    if (sVal != "")
3259
                                        o[i] = Convert.ToInt16(sVal);
3260
                                    i++;
3261
                                    sVal = ini.IniReadValue(wp, "AutoTrigger");
3262
                                    if (sVal != "")
3263
                                        o[i] = Convert.ToInt16(sVal); ;
3264
                                    i++;
3265
                                    sVal = ini.IniReadValue(wp, "CAM-Nick");
3266
                                    if (sVal != "")
2313 - 3267
                                        o[i] = Convert.ToInt16(sVal);
2312 - 3268
                                    i++;
3269
                                    o[i] = 0;
3270
                                    i++;
3271
                                    sVal = ini.IniReadValue(wp, "WP_Event_Channel_Value");
3272
                                    if (sVal != "")
3273
                                        o[i] = Convert.ToInt16(sVal);
3274
                                    i++;
3275
                                    o[i] = "New";
3276
 
3277
                                    dr.ItemArray = o;
3278
                                    dtWaypoints.Rows.Add(dr);
2363 - 3279
                                    _createWP(new PointLatLng((double)o[3], (double)o[4]), (string)dr[2], (int)o[1]);
2315 - 3280
 
2312 - 3281
                                    Dispatcher.Invoke(() => lblWPIndex.Content = k.ToString());
3282
                                    Dispatcher.Invoke(() => lblWPCount.Content = k.ToString());
3283
                                    Dispatcher.Invoke(() => dgvWP.Items.Refresh());
3284
                                    Thread.Sleep(10);
3285
                                }
2359 - 3286
                                _routeUpdate();
2312 - 3287
                            }
3288
                        }
3289
                    }
3290
 
3291
                }
3292
                catch (Exception e)
3293
                {
3294
 
3295
                    MessageBox.Show("Error parsing wpl-file!" + Environment.NewLine + e.Message, "Read wpl-file", MessageBoxButton.OK, MessageBoxImage.Error);
3296
                }
3297
 
3298
            }
3299
        }
2350 - 3300
        void _saveWPLFile()
3301
        {
3302
            if (dtWaypoints.Rows.Count > 0)
3303
            {
3304
                Microsoft.Win32.SaveFileDialog fd = new Microsoft.Win32.SaveFileDialog();
3305
                fd.Filter = "Waypointlists | *.wpl";
3306
                fd.AddExtension = true;
3307
                if (fd.ShowDialog().Value)
3308
                {
3309
                    string file = fd.SafeFileName;
3310
                    IniFile ini = new IniFile(fd.SafeFileName);
3311
                    ini.path = fd.FileName;
3312
                    NumberFormatInfo nfi = new NumberFormatInfo();
3313
                    nfi.NumberDecimalSeparator = ".";
3314
 
3315
                    try
3316
                    {
3317
                        ini.IniWriteValue("General", "FileVersion", "3");
3318
                        ini.IniWriteValue("General", "NumberOfWaypoints", dtWaypoints.Rows.Count.ToString());
3319
                        ini.IniWriteValue("General", "Mapfile", "");
3320
                        for(int i = 1; i<=dtWaypoints.Rows.Count; i++)
3321
                        {
3322
                            ini.IniWriteValue("Point" + i.ToString(), "Latitude", ((double)(dtWaypoints.Rows[i-1][3])).ToString(nfi));
3323
                            ini.IniWriteValue("Point" + i.ToString(), "Longitude", ((double)(dtWaypoints.Rows[i - 1][4])).ToString(nfi));
3324
                            ini.IniWriteValue("Point" + i.ToString(), "Radius", dtWaypoints.Rows[i - 1][9].ToString());
3325
                            ini.IniWriteValue("Point" + i.ToString(), "Altitude", dtWaypoints.Rows[i - 1][5].ToString());
3326
                            ini.IniWriteValue("Point" + i.ToString(), "ClimbRate", dtWaypoints.Rows[i - 1][8].ToString());
3327
                            ini.IniWriteValue("Point" + i.ToString(), "DelayTime", dtWaypoints.Rows[i - 1][10].ToString());
3328
                            ini.IniWriteValue("Point" + i.ToString(), "WP_Event_Channel_Value", dtWaypoints.Rows[i - 1][14].ToString());
3329
                            ini.IniWriteValue("Point" + i.ToString(), "Heading", dtWaypoints.Rows[i - 1][6].ToString());
3330
                            ini.IniWriteValue("Point" + i.ToString(), "Speed", dtWaypoints.Rows[i - 1][7].ToString());
3331
                            ini.IniWriteValue("Point" + i.ToString(), "CAM-Nick", dtWaypoints.Rows[i - 1][12].ToString());
3332
                            ini.IniWriteValue("Point" + i.ToString(), "Type", ((int)dtWaypoints.Rows[i - 1][1]+1).ToString());
3333
                            ini.IniWriteValue("Point" + i.ToString(), "Prefix", dtWaypoints.Rows[i - 1][2].ToString().Substring(0, 1)); // == "!" ? "0" : dtWaypoints.Rows[i - 1][2].ToString().Substring(0, 1));
3334
                            ini.IniWriteValue("Point" + i.ToString(), "AutoTrigger", dtWaypoints.Rows[i - 1][11].ToString());
3335
                        }
3336
                        MessageBox.Show(dtWaypoints.Rows.Count.ToString() + " points saved to " + file, "Waypointlist saved", MessageBoxButton.OK, MessageBoxImage.Information);
3337
                    }
3338
                    catch { }
3339
                }
3340
            }
3341
            else
3342
                MessageBox.Show("Nothing to save...");
3343
        }
3344
        private void btnSaveWPLFile_Click(object sender, RoutedEventArgs e)
3345
        {
3346
            _saveWPLFile();
3347
        }
3348
        /// <summary>
3349
        /// set the selected color for the route
3350
        /// </summary>
3351
        /// <param name="color"></param>
3352
        /// <returns></returns>
2328 - 3353
        Brush _getBrush(string color)
3354
        {
3355
            switch (color)
3356
            {
3357
                case "red":
3358
                    return Brushes.Red;
3359
                case "green":
3360
                    return Brushes.Lime;
3361
                case "blue":
3362
                    return Brushes.Aqua;
3363
                case "pink":
3364
                    return Brushes.Magenta;
3365
                case "yellow":
3366
                    return Brushes.Yellow;
3367
                default:
3368
                    return Brushes.Magenta;
3369
            }
3370
        }
2359 - 3371
        void _routeUpdate()
3372
        {
3373
            Dispatcher.Invoke(() =>
3374
            {
3375
                if (comboBoxRouteColor.SelectionBoxItem != null)
3376
                {
3377
                    string s = comboBoxRouteColor.SelectionBoxItem.ToString();
3378
                    mRouteWP = new GMapRoute(wpList, _getBrush(s));
3379
                }
3380
                else
3381
                    mRouteWP = new GMapRoute(wpList, null);
3382
 
3383
                if (_bShowWPRoute)
2368 - 3384
                    MainMap.Markers.Add(mRouteWP);
2359 - 3385
            });
3386
 
3387
            MapRoute mr = new MapRoute(wpList, "WPList");
3388
            Dispatcher.Invoke(() => lblWPRouteDistance.Content = (mr.Distance * 1000).ToString("0 m"));
3389
        }
2363 - 3390
        GMapMarker _createWP(PointLatLng p, string name, int type)
3391
        {
3392
            GMapMarker wpMarker = new GMapMarker(p);
3393
            wpMarker.Shape = new CustomMarkerWP(this, wpMarker, name, type);
3394
            wpMarker.Offset = new System.Windows.Point(-11.5, -11.5);
3395
            wpMarker.ZIndex = 100;
3396
            _setMarkerColor(wpMarker, type);
3397
            Dispatcher.Invoke(() => MainMap.Markers.Add(wpMarker));
2372 - 3398
            if (type == 0 || type == 3)
2363 - 3399
                wpList.Add(p);
3400
            return wpMarker;
3401
        }
2315 - 3402
        void _setMarkerColor(GMapMarker wpMarker,int iType)
3403
        {
2369 - 3404
            if(wpMarker != null)
2315 - 3405
            Dispatcher.Invoke(() =>
3406
            {
3407
                switch (iType)
3408
                {
3409
                    case 0:
3410
                        if (comboBoxWPColor.SelectionBoxItem != null)
3411
                        {
3412
                            string s = comboBoxWPColor.SelectionBoxItem.ToString();
3413
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
3414
                        }
3415
                        else
2372 - 3416
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("green");
2315 - 3417
                        break;
3418
                    case 1:
3419
                        if (comboBoxPOIColor.SelectionBoxItem != null)
3420
                        {
3421
                            string s = comboBoxPOIColor.SelectionBoxItem.ToString();
3422
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
3423
                        }
3424
                        else
2372 - 3425
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("pink");
2315 - 3426
                        break;
3427
                    case 2:
3428
                        if (comboBoxFSColor.SelectionBoxItem != null)
3429
                        {
3430
                            string s = comboBoxFSColor.SelectionBoxItem.ToString();
3431
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
3432
                        }
3433
                        else
3434
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("red");
3435
                        break;
2372 - 3436
                    case 3:
3437
                        if (comboBoxLandingColor.SelectionBoxItem != null)
3438
                        {
3439
                            string s = comboBoxLandingColor.SelectionBoxItem.ToString();
3440
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor(s);
3441
                        }
3442
                        else
3443
                            ((CustomMarkerWP)(wpMarker.Shape)).setColor("blue");
3444
                        break;
2315 - 3445
                    default:
3446
                        ((CustomMarkerWP)(wpMarker.Shape)).setColor("red");
3447
                        break;
3448
                }
3449
            });
2312 - 3450
 
2315 - 3451
        }
2372 - 3452
        void _MarkerColorSelection(object sender,int type)
3453
        {
2315 - 3454
            Dispatcher.Invoke(() =>
3455
            {
2372 - 3456
                if (((ComboBox)sender).SelectionBoxItem != null)
2315 - 3457
                {
3458
                    for (int k = 0; k < MainMap.Markers.Count; k++)
3459
                    {
3460
                        GMapMarker p = MainMap.Markers[k];
2372 - 3461
                        if (p.Shape != null && p.Shape.GetType() == typeof(CustomMarkerWP))
2315 - 3462
                        {
2372 - 3463
                            if (((CustomMarkerWP)p.Shape).WPType == type)
2315 - 3464
                            {
2372 - 3465
                                string s = ((ComboBox)sender).SelectionBoxItem.ToString();
2315 - 3466
                                ((CustomMarkerWP)(p.Shape)).setColor(s);
3467
                            }
3468
                        }
3469
                    }
3470
                }
3471
            });
2287 - 3472
        }
2376 - 3473
       private void comboBoxWPColor_DropDownClosed(object sender, EventArgs e)
2318 - 3474
        {
2376 - 3475
            _MarkerColorSelection(sender, 0);
3476
        }
3477
        private void comboBoxPOIColor_DropDownClosed(object sender, EventArgs e)
3478
        {
3479
            _MarkerColorSelection(sender, 1);
3480
        }
3481
        private void comboBoxFSColor_DropDownClosed(object sender, EventArgs e)
3482
        {
3483
            _MarkerColorSelection(sender, 2);
3484
        }
3485
        private void comboBoxLandingColor_DropDownClosed(object sender, EventArgs e)
3486
        {
3487
            _MarkerColorSelection(sender,3);
3488
        }
3489
         private void comboBoxCopterColor_DropDownClosed(object sender, EventArgs e)
3490
        {
2318 - 3491
            Dispatcher.Invoke(() => {
3492
                if (comboBoxCopterColor.SelectionBoxItem != null)
3493
                {
3494
                    string s = comboBoxCopterColor.SelectionBoxItem.ToString();
3495
                    ((CustomMarkerCopter)(copter.Shape)).setColor(s);
3496
                }
3497
                else
3498
                    ((CustomMarkerCopter)(copter.Shape)).setColor("red");
3499
            });
3500
        }
2328 - 3501
        private void comboBoxRouteColor_DropDownClosed(object sender, EventArgs e)
3502
        {
3503
            Dispatcher.Invoke(() =>
3504
            {
3505
                if (comboBoxRouteColor.SelectionBoxItem != null)
3506
                {
3507
                    string s = comboBoxRouteColor.SelectionBoxItem.ToString();
3508
                    MainMap.Markers.Remove(mRouteWP);
3509
                    mRouteWP = new GMapRoute(wpList, _getBrush(s));
3510
                    if (_bShowWPRoute)
3511
                        MainMap.Markers.Add(mRouteWP);
3512
                }
3513
            });
3514
        }
3515
        private void checkBoxShowWPRoute_Click(object sender, RoutedEventArgs e)
3516
        {
3517
            _bShowWPRoute = (bool)checkBoxShowWPRoute.IsChecked;
3518
            if (_bShowWPRoute)
3519
            {
3520
                if (mRouteWP != null)
3521
                    MainMap.Markers.Add(mRouteWP);
3522
            }
3523
            else
3524
            {
3525
                if (mRouteWP != null)
3526
                    MainMap.Markers.Remove(mRouteWP);
3527
            }
3528
        }
2315 - 3529
        private void btnLoadWPLFile_Click(object sender, RoutedEventArgs e)
2287 - 3530
        {
2315 - 3531
            _readWPLFile();
2287 - 3532
        }
2335 - 3533
        private void btnClearWPList_Click(object sender, RoutedEventArgs e)
3534
        {
3535
            _clearMapMarkers(typeof(CustomMarkerWP));
2347 - 3536
            _clearMapMarkers(typeof(CustomMarkerWPActive));
2335 - 3537
            wpList.Clear();
3538
            if (mRouteWP != null)
3539
                MainMap.Markers.Remove(mRouteWP);
2347 - 3540
            //if (wpActiveMarker != null)
3541
            //    MainMap.Markers.Remove(wpActiveMarker);
2335 - 3542
            dtWaypoints.Rows.Clear();
2356 - 3543
            _wpEdit = -1;
2368 - 3544
            _wpIndex = -1;
2335 - 3545
            Dispatcher.Invoke(() => dgvWP.Items.Refresh());
3546
            Dispatcher.Invoke(() => lblWPIndex.Content = 0);
3547
            Dispatcher.Invoke(() => lblWPCount.Content = 0);
3548
            Dispatcher.Invoke(() => lblWPRouteDistance.Content = "0 m");
3549
        }
2340 - 3550
        private void btnClearCopterList_Click(object sender, RoutedEventArgs e)
3551
        {
3552
            Thread t = new Thread(new ThreadStart(clearCopterWPList));
3553
            t.Start();
3554
        }
2355 - 3555
        private void btnSendActiveWP_Click(object sender, RoutedEventArgs e)
2340 - 3556
        {
3557
            if (dgvWP.SelectedIndex > -1 && dgvWP.SelectedIndex < dtWaypoints.Rows.Count)
3558
            {
2372 - 3559
                if (_wpCount > 0)
2376 - 3560
                    _sendWayPoint(dtWaypoints.Rows[dgvWP.SelectedIndex], -1, 's',false);
2372 - 3561
                else
2376 - 3562
                    _sendWayPoint(dtWaypoints.Rows[dgvWP.SelectedIndex], 1, 's',false);
2363 - 3563
 
2372 - 3564
                //int index = dgvWP.SelectedIndex;
3565
                //Thread t = new Thread(() => _sendWPList(index));
3566
                //t.Start();
2354 - 3567
 
3568
                Dispatcher.Invoke(() => {
3569
                    DataGridRow row;
2368 - 3570
                    if (_wpEdit > -1 && _wpEdit < dgvWP.ItemContainerGenerator.Items.Count)
2354 - 3571
                    {
2368 - 3572
                        row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpEdit);
2354 - 3573
                        row.Background = new SolidColorBrush(Colors.Transparent);
3574
                        row.BorderBrush = new SolidColorBrush(Colors.Transparent);
3575
                        row.BorderThickness = new Thickness(0);
2376 - 3576
                        dgvWP.UpdateLayout();
2354 - 3577
                    }
2376 - 3578
                    //_wpEdit = dgvWP.SelectedIndex;
3579
                    //row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpEdit);
3580
                    //row.Background = new SolidColorBrush(Color.FromArgb(80, 0, 255, 100));
3581
                    //row.BorderBrush = new SolidColorBrush(Colors.SpringGreen);
3582
                    //row.BorderThickness = new Thickness(2);
2354 - 3583
                });
2340 - 3584
            }
3585
        }
2376 - 3586
        private void btnWPSimulateStart_Click(object sender, RoutedEventArgs e)
3587
        {
3588
            _Simulate = !_Simulate;
3589
            if (dtWaypoints.Rows.Count > 0)
3590
            {
3591
                DataRow dr = dtWaypoints.Rows[0];
3592
                dr[13] = _Simulate ? 3 : 0;
3593
                _sendWayPoint(dr, 1, 's', true);
3594
                rectSimulate.Visibility = _Simulate ? Visibility.Visible : Visibility.Hidden;
3595
            }
3596
        }
2355 - 3597
        private void dgvWP_MouseUp(object sender, MouseButtonEventArgs e)
3598
        {
2359 - 3599
            _dgvWPselectEditRow();
3600
        }
3601
        private void dgvWP_MouseDoubleClick(object sender, MouseButtonEventArgs e)
3602
        {
3603
        }
3604
        void _dgvWPselectEditRow()
3605
        {
2355 - 3606
            if (dgvWP.SelectedIndex > -1 && dgvWP.SelectedIndex < dtWaypoints.Rows.Count)
3607
            {
2368 - 3608
               Dispatcher.Invoke(() => {
2355 - 3609
                    DataGridRow row;
2368 - 3610
                    if (_wpEdit > -1 && _wpEdit < dgvWP.ItemContainerGenerator.Items.Count)
2355 - 3611
                    {
3612
                        row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpEdit);
3613
                        row.Background = new SolidColorBrush(Colors.Transparent);
3614
                        row.BorderBrush = new SolidColorBrush(Colors.Transparent);
3615
                        row.BorderThickness = new Thickness(0);
3616
                    }
3617
                    _wpEdit = dgvWP.SelectedIndex;
3618
                    row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpEdit);
3619
                    row.Background = new SolidColorBrush(Color.FromArgb(80, 0, 100, 255));
3620
                    row.BorderBrush = new SolidColorBrush(Colors.Aqua);
3621
                    row.BorderThickness = new Thickness(2);
3622
                    dgvWP.UpdateLayout();
2340 - 3623
 
2355 - 3624
                    _setWPEditFields(_wpEdit);
3625
                });
3626
            }
3627
        }
3628
        void _setWPEditFields(int index)
3629
        {
3630
            int iVal;
3631
            cbWPEditType.SelectedIndex = (int)dtWaypoints.Rows[index][1];
3632
            tbWPEditPrefix.Text = dtWaypoints.Rows[index][2].ToString().Substring(0,1);
3633
            tbWPEditLat.Text = dtWaypoints.Rows[index][3].ToString();
3634
            tbWPEditLon.Text = dtWaypoints.Rows[index][4].ToString();
3635
            tbWPEditAlt.Text = dtWaypoints.Rows[index][5].ToString();
3636
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][6]);
3637
            if (iVal == 0)
3638
            {
3639
                cbWPEditHeading.SelectedIndex = 0;
3640
                tbWPEditHeading.Text = " - - -";
3641
                tbWPEditHeading.IsReadOnly = true;
3642
            }
3643
            if (iVal > 0 && iVal < 360)
3644
            {
3645
                cbWPEditHeading.SelectedIndex = 2;
3646
                tbWPEditHeading.Text = iVal.ToString();
3647
                tbWPEditHeading.IsReadOnly = false;
3648
            }
3649
            if (iVal < 0)
3650
            {
3651
                cbWPEditHeading.SelectedIndex = 1;
3652
                tbWPEditHeading.Text = (Math.Abs(iVal).ToString());
3653
                tbWPEditHeading.IsReadOnly = false;
3654
            }
3655
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][7]);
3656
            if (iVal == 0)
3657
            {
3658
                cbWPEditSpeed.SelectedIndex = 0;
3659
                tbWPEditSpeed.Text = "MAX";
3660
                tbWPEditSpeed.IsReadOnly = true;
3661
            }
3662
            if (iVal > 0 && iVal < 248)
3663
            {
3664
                cbWPEditSpeed.SelectedIndex = 1;
3665
                tbWPEditSpeed.Text = ((double)iVal * 0.1).ToString();
3666
                tbWPEditSpeed.IsReadOnly = false;
3667
            }
3668
            if (iVal > 247)
3669
            {
3670
                cbWPEditSpeed.SelectedIndex = 256 - iVal + 1;
3671
                tbWPEditSpeed.Text = "";
3672
                tbWPEditSpeed.IsReadOnly = true;
3673
            }
3674
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][8]);
3675
            if (iVal == 255)
3676
            {
3677
                cbWPEditClimbrate.SelectedIndex = 0;
3678
                tbWPEditClimbrate.Text = "AUTO";
3679
                tbWPEditClimbrate.IsReadOnly = true;
3680
            }
3681
            else
3682
            {
3683
                cbWPEditClimbrate.SelectedIndex = 1;
3684
                tbWPEditClimbrate.Text = (System.Convert.ToDouble(iVal) / 10).ToString("0.0");
3685
                tbWPEditClimbrate.IsReadOnly = false;
3686
            }
3687
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][9]);
3688
            tbWPEditRadius.Text = iVal.ToString();
3689
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][10]);
3690
            tbWPEditHoldtime.Text = iVal.ToString();
3691
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][11]);
3692
            tbWPEditAutoTrigger.Text = iVal.ToString();
3693
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][12]);
3694
            if (iVal == 0)
3695
            {
3696
                cbWPEditCamAngle.SelectedIndex = 0;
3697
                tbWPEditCamAngle.Text = " - - - ";
3698
                tbWPEditCamAngle.IsReadOnly = true;
3699
            }
3700
            if (iVal < 0 | iVal == 255)
3701
            {
3702
                cbWPEditCamAngle.SelectedIndex = 1;
3703
                tbWPEditCamAngle.Text = "AUTO";
3704
                tbWPEditCamAngle.IsReadOnly = true;
3705
            }
3706
            if (iVal > 0 & iVal < 255)
3707
            {
3708
                cbWPEditCamAngle.SelectedIndex = 2;
3709
                tbWPEditCamAngle.Text = iVal.ToString();
3710
                tbWPEditCamAngle.IsReadOnly = false;
3711
            }
3712
            iVal = Convert.ToInt16(dtWaypoints.Rows[index][14]);
3713
            tbWPEditOut1.Text = iVal.ToString();
3714
 
3715
        }
3716
 
2361 - 3717
        private void btnEditWPSave_Click(object sender, RoutedEventArgs e)
3718
        {
2363 - 3719
            if(dgvWP.SelectedIndex > -1 && dgvWP.SelectedIndex < dtWaypoints.Rows.Count)
3720
            {
2369 - 3721
                string oldName = (string)dtWaypoints.Rows[dgvWP.SelectedIndex][2];
2372 - 3722
                int oldType = (int)dtWaypoints.Rows[dgvWP.SelectedIndex][1];
3723
                PointLatLng pOld = new PointLatLng((double)dtWaypoints.Rows[dgvWP.SelectedIndex][3], (double)dtWaypoints.Rows[dgvWP.SelectedIndex][4]);
3724
                int i = wpList.IndexOf(pOld);
2363 - 3725
                dtWaypoints.Rows[dgvWP.SelectedIndex][1] = cbWPEditType.SelectedIndex;
3726
                dtWaypoints.Rows[dgvWP.SelectedIndex][2] = tbWPEditPrefix.Text + (dgvWP.SelectedIndex + 1).ToString();
3727
                dtWaypoints.Rows[dgvWP.SelectedIndex][3] = Convert.ToDouble(tbWPEditLat.Text.Replace('.', ','));
3728
                dtWaypoints.Rows[dgvWP.SelectedIndex][4] = Convert.ToDouble(tbWPEditLon.Text.Replace('.', ','));
2372 - 3729
                if (i > -1)
3730
                {
3731
                    if((int)dtWaypoints.Rows[dgvWP.SelectedIndex][1] == 0 || (int)dtWaypoints.Rows[dgvWP.SelectedIndex][1] == 3)
3732
                        wpList[i] = (new PointLatLng((double)dtWaypoints.Rows[dgvWP.SelectedIndex][3], (double)dtWaypoints.Rows[dgvWP.SelectedIndex][4]));
3733
                    else
3734
                        wpList.Remove(pOld);
3735
                }
3736
                else
3737
                {
3738
                    if ((int)dtWaypoints.Rows[dgvWP.SelectedIndex][1] == 0 || (int)dtWaypoints.Rows[dgvWP.SelectedIndex][1] == 3)
3739
                    {
3740
                        int found = 0;
3741
                        for (int k = 0; k < dgvWP.SelectedIndex; k++)
3742
                            if ((int)dtWaypoints.Rows[k][1] == 0)
3743
                                found++;
3744
                        wpList.Insert(found, new PointLatLng((double)dtWaypoints.Rows[dgvWP.SelectedIndex][3], (double)dtWaypoints.Rows[dgvWP.SelectedIndex][4]));
3745
                    }
3746
                }
2363 - 3747
                dtWaypoints.Rows[dgvWP.SelectedIndex][5] = tbWPEditAlt.Text;
3748
                switch (cbWPEditHeading.SelectedIndex)
3749
                {
3750
                    case 0:
3751
                        dtWaypoints.Rows[dgvWP.SelectedIndex][6] = "0";
3752
                        break;
3753
                    case 1:
3754
                        dtWaypoints.Rows[dgvWP.SelectedIndex][6] = "-" + tbWPEditHeading.Text;
3755
                        break;
3756
                    case 2:
3757
                        dtWaypoints.Rows[dgvWP.SelectedIndex][6] = tbWPEditHeading.Text;
3758
                        break;
3759
                }
3760
                switch (cbWPEditSpeed.SelectedIndex)
3761
                {
3762
                    case 0:
3763
                        dtWaypoints.Rows[dgvWP.SelectedIndex][7] = "0";
3764
                        break;
3765
                    case 1:
3766
                        dtWaypoints.Rows[dgvWP.SelectedIndex][7] = (System.Convert.ToDouble(tbWPEditSpeed.Text.Replace('.', ',')) * 10).ToString("0");
3767
                        break;
3768
                    case 2:
3769
                        dtWaypoints.Rows[dgvWP.SelectedIndex][7] = (256 - Convert.ToInt16(tbWPEditSpeed.Text)).ToString();
3770
                        break;
3771
                }
3772
                switch (cbWPEditClimbrate.SelectedIndex)
3773
                {
3774
                    case 0:
3775
                        dtWaypoints.Rows[dgvWP.SelectedIndex][8] = "255";
3776
                        break;
3777
                    case 1:
3778
                        dtWaypoints.Rows[dgvWP.SelectedIndex][8] = (System.Convert.ToDouble(tbWPEditClimbrate.Text.Replace('.',',')) * 10).ToString("0");
3779
                        break;
3780
                }
3781
                dtWaypoints.Rows[dgvWP.SelectedIndex][9] = tbWPEditRadius.Text;
3782
                dtWaypoints.Rows[dgvWP.SelectedIndex][10] = tbWPEditHoldtime.Text;
3783
                dtWaypoints.Rows[dgvWP.SelectedIndex][11] = tbWPEditAutoTrigger.Text;
3784
                switch (cbWPEditCamAngle.SelectedIndex)
3785
                {
3786
                    case 0:
3787
                        dtWaypoints.Rows[dgvWP.SelectedIndex][12] = "0";
3788
                        break;
3789
                    case 1:
3790
                        dtWaypoints.Rows[dgvWP.SelectedIndex][12] = "255";
3791
                        break;
3792
                    case 2:
3793
                        dtWaypoints.Rows[dgvWP.SelectedIndex][12] = tbWPEditCamAngle.Text;
3794
                        break;
3795
                }
3796
                dtWaypoints.Rows[dgvWP.SelectedIndex][14] = tbWPEditOut1.Text;
2361 - 3797
 
2369 - 3798
                // _clearMapMarkers(typeof(CustomMarkerWP));
3799
                _repositionWPMarker(new PointLatLng((double)dtWaypoints.Rows[dgvWP.SelectedIndex][3], (double)dtWaypoints.Rows[dgvWP.SelectedIndex][4]),oldName);
3800
                _renameWPMarker(oldName, (string)dtWaypoints.Rows[dgvWP.SelectedIndex][2]);
2363 - 3801
                _clearMapMarkers(typeof(CustomMarkerWPActive));
2369 - 3802
                _setMarkerColor(_findWPMarker((string)dtWaypoints.Rows[dgvWP.SelectedIndex][2]), (int)dtWaypoints.Rows[dgvWP.SelectedIndex][1]);
2372 - 3803
                _WPMarkerSetType((string)dtWaypoints.Rows[dgvWP.SelectedIndex][2], (int)dtWaypoints.Rows[dgvWP.SelectedIndex][1]);
2369 - 3804
               // wpList.Clear();
2363 - 3805
                if (mRouteWP != null)
3806
                    MainMap.Markers.Remove(mRouteWP);
3807
 
2369 - 3808
                //for (int k = 0; k < dtWaypoints.Rows.Count; k++)
3809
                //{
3810
                //    _createWP(new PointLatLng((double)dtWaypoints.Rows[k][3], (double)dtWaypoints.Rows[k][4]), (string)dtWaypoints.Rows[k][2], (int)dtWaypoints.Rows[k][1]);
3811
                //}
2363 - 3812
                _routeUpdate();
3813
                dgvWP.Items.Refresh();
3814
 
3815
            }
3816
 
2361 - 3817
        }
3818
        private void btnEditWPDel_Click(object sender, RoutedEventArgs e)
3819
        {
2368 - 3820
            if (dgvWP.SelectedIndex > -1 && dgvWP.SelectedIndex < dtWaypoints.Rows.Count)
3821
            {
3822
                int index = dgvWP.SelectedIndex;
3823
                Dispatcher.Invoke(() => {
3824
                    DataGridRow row;
3825
                    if (_wpEdit > -1 && _wpEdit < dgvWP.ItemContainerGenerator.Items.Count)
3826
                    {
3827
                        row = (DataGridRow)dgvWP.ItemContainerGenerator.ContainerFromIndex(_wpEdit);
3828
                        row.Background = new SolidColorBrush(Colors.Transparent);
3829
                        row.BorderBrush = new SolidColorBrush(Colors.Transparent);
3830
                        row.BorderThickness = new Thickness(0);
3831
                    }
2372 - 3832
                    if ((int)dtWaypoints.Rows[index][1] == 0 || (int)dtWaypoints.Rows[index][1] == 3)
2368 - 3833
                        wpList.Remove(new PointLatLng((double)dtWaypoints.Rows[index][3], (double)dtWaypoints.Rows[index][4]));
3834
                    _clearWPMarker((string)dtWaypoints.Rows[index][2]);
2369 - 3835
                    if (wpActiveMarker != null)
3836
                        MainMap.Markers.Remove(wpActiveMarker);
2368 - 3837
                    dtWaypoints.Rows[index].Delete();
3838
                    _wpIndex = -1;
3839
                    _wpEdit = -1;
3840
                    for (int i = index; i < dtWaypoints.Rows.Count; i++) //change the index of points behind deleted point + rename to new index
3841
                    {
3842
                        dtWaypoints.Rows[i][0] = i + 1;
3843
                        string s1 = (string)dtWaypoints.Rows[i][2]; //old name of WP (Prefix + index)
3844
                        string s2 = s1.Substring(0, 1) + (i + 1).ToString(); //new name of WP
3845
                        _renameWPMarker(s1, s2);
3846
                        dtWaypoints.Rows[i][2] = s2;
3847
                    }
3848
                    lblWPCount.Content = dtWaypoints.Rows.Count;
3849
                    if (mRouteWP != null)
3850
                        MainMap.Markers.Remove(mRouteWP);
3851
                    _routeUpdate();
2361 - 3852
 
2368 - 3853
                    dgvWP.UpdateLayout();
3854
                });
3855
            }
2361 - 3856
        }
2366 - 3857
        private void tbWPEdit_TouchDown(object sender, TouchEventArgs e)
3858
        {
3859
            _wpWEdit(sender);
3860
        }
2361 - 3861
        private void tbWPEdit_KeyDown(object sender, KeyEventArgs e)
3862
        {
2366 - 3863
            _wpWEdit(sender);
3864
        }
2369 - 3865
        private void tbWPEdit_MouseDown(object sender, MouseButtonEventArgs e)
3866
        {
3867
            _wpWEdit(sender);
3868
        }
2366 - 3869
        void _wpWEdit(object sender)
3870
        {
2369 - 3871
           // if (!((TextBox)sender).IsReadOnly)
2361 - 3872
            {
3873
                KeyPad.Keypad k = new KeyPad.Keypad(this);
3874
 
2363 - 3875
                switch (((TextBox)sender).Name)
3876
                {
3877
                    case "tbWPEditLat":
3878
                        k.Title = "Latitude";
3879
                        k.LENGTH = 17;
3880
                        k.MAX = 359.9;
3881
                        break;
3882
                    case "tbWPEditLon":
3883
                        k.Title = "Longitude";
3884
                        k.LENGTH = 17;
3885
                        k.MAX = 359.9;
3886
                        break;
3887
                    case "tbWPEditAlt":
3888
                        k.Title = "Altitude";
3889
                        k.LENGTH = 3;
3890
                        k.MAX = 254;
3891
                        k.disableDecimal();
3892
                        break;
3893
                    case "tbWPEditHeading":
3894
                        k.Title = "Heading";
3895
                        k.LENGTH = 3;
3896
                        k.MAX = 359;
3897
                        k.MIN = 1;
3898
                        k.disableDecimal();
3899
                        break;
3900
                    case "tbWPEditSpeed":
3901
                        k.Title = "Speed";
3902
                        k.LENGTH = 4;
3903
                        k.MAX = 24.7;
3904
                        k.MIN = 0.1;
3905
                        break;
3906
                    case "tbWPEditClimbrate":
3907
                        k.Title = "Climbrate";
3908
                        k.LENGTH = 4;
3909
                        k.MAX = 25.4;
3910
                        k.MIN = 0.1;
3911
                        break;
3912
                    case "tbWPEditRadius":
3913
                        k.Title = "Radius";
3914
                        k.LENGTH = 3;
3915
                        k.MAX = 254;
3916
                        k.disableDecimal();
3917
                        break;
3918
                    case "tbWPEditHoldtime":
3919
                        k.Title = "Holdtime";
3920
                        k.LENGTH = 3;
3921
                        k.MAX = 254;
3922
                        break;
3923
                    case "tbWPEditAutoTrigger":
3924
                        k.Title = "Autotrigger";
3925
                        k.LENGTH = 3;
3926
                        k.MAX = 254;
3927
                        k.disableDecimal();
3928
                        break;
3929
                    case "tbWPEditCamAngle":
3930
                        k.Title = "Camera angle";
3931
                        k.LENGTH = 3;
3932
                        k.MAX = 254;
3933
                        k.MIN = 1;
3934
                        k.disableDecimal();
3935
                        break;
3936
                    case "tbWPEditOut1":
3937
                        k.Title = "OUT1 timer interval";
3938
                        k.LENGTH = 3;
3939
                        k.MAX = 254;
3940
                        k.disableDecimal();
3941
                        break;
3942
                }
3943
                k.Result = ((TextBox)sender).Text;
2366 - 3944
                if (k.ShowDialog() == true && k.Result.Length > 0)
2363 - 3945
                    ((TextBox)sender).Text = k.Result;
2361 - 3946
            }
2366 - 3947
 
2361 - 3948
        }
2356 - 3949
        private void tbWPEditHeading_KeyDown(object sender, KeyEventArgs e)
3950
        {
3951
           if(!tbWPEditHeading.IsReadOnly)
3952
            {
3953
                //var x = KeyInterop.VirtualKeyFromKey(e.Key);
3954
                KeyConverter x = new KeyConverter();
3955
                string s = x.ConvertToString(e.Key);
3956
 
3957
                if ("1234567890,\b".IndexOf(s) < 0) //general check for valid chars(0-9) and backspace (\b)
3958
                    e.Handled = true;
3959
                else
3960
                    if ("\b".IndexOf(s) < 0)
3961
                        if (Convert.ToInt16(((TextBox)sender).Text + s) > 360) //if valid and not backspace, check for upper limit of the resulting number
3962
                            e.Handled = true;
3963
 
3964
            }
3965
        }
2361 - 3966
        private void btnWPAddCurrentPos_Click(object sender, RoutedEventArgs e)
2356 - 3967
        {
2359 - 3968
            object[] o = new object[16];
2356 - 3969
 
2359 - 3970
            o[0] = dgvWP.ItemContainerGenerator.Items.Count+1;
3971
            o[1] = 0;
3972
           //     cbWPEditType.SelectedIndex = 0;
3973
          //  tbWPEditPrefix.Text = "P";
3974
            o[2] = "P" + o[0].ToString();
3975
         //   tbWPEditLat.Text = copter.Position.Lat.ToString();
3976
            o[3] = copter.Position.Lat;
3977
          //  tbWPEditLon.Text = copter.Position.Lng.ToString();
3978
            o[4] = copter.Position.Lng;            
3979
         //   tbWPEditAlt.Text = ((double)iAnalogData[4] / (double)10).ToString();
3980
            o[5] = iAnalogData[4].ToString();
2356 - 3981
 
2359 - 3982
        //    cbWPEditHeading.SelectedIndex = 2;
3983
            o[6] = tbWPEditHeading.Text = iAnalogData[10].ToString();
3984
        //    tbWPEditHeading.IsReadOnly = false;
2356 - 3985
 
2359 - 3986
       //     cbWPEditSpeed.SelectedIndex = 1;
3987
       //     tbWPEditSpeed.Text = "5.0";
3988
       //     tbWPEditSpeed.IsReadOnly = false;
2372 - 3989
            o[7] = "10";
2356 - 3990
 
2359 - 3991
      //      cbWPEditClimbrate.SelectedIndex = 1;
3992
     //       tbWPEditClimbrate.Text = "5.0";
3993
     //       tbWPEditClimbrate.IsReadOnly = false;
2372 - 3994
            o[8] = "10";
2356 - 3995
 
2359 - 3996
     //       tbWPEditRadius.Text = "10";
2372 - 3997
            o[9] = "5";
2359 - 3998
     //       tbWPEditHoldtime.Text = "5";
3999
            o[10] = "5";
4000
      //      tbWPEditAutoTrigger.Text = "0";
4001
            o[11] = "0";
4002
     //       cbWPEditCamAngle.SelectedIndex = 1;
4003
     //       tbWPEditCamAngle.Text = "AUTO";
4004
     //       tbWPEditCamAngle.IsReadOnly = true;
4005
            o[12] = "255";
2356 - 4006
 
2359 - 4007
            o[13] = "0";
4008
           //     tbWPEditOut1.Text = "0";
4009
            o[14] = "0";
4010
            o[15] = "0";
4011
 
4012
            dtWaypoints.Rows.Add(o);
2368 - 4013
            _createWP(new PointLatLng((double)o[3], (double)o[4]), (string)o[2], (int)o[1]);
2359 - 4014
            Dispatcher.Invoke(() => lblWPCount.Content = o[0].ToString());
4015
            if (mRouteWP != null)
4016
                MainMap.Markers.Remove(mRouteWP);
4017
            _routeUpdate();
4018
            Dispatcher.Invoke(() => {
4019
                dgvWP.Items.Refresh();
4020
                dgvWP.SelectedIndex = (int)o[0] -1;
4021
                dgvWP.UpdateLayout();
4022
                _dgvWPselectEditRow();
4023
                });
2356 - 4024
        }
4025
 
2315 - 4026
        #endregion WP
2324 - 4027
        #region GPX
4028
        private void checkBoxGPXLog_Click(object sender, RoutedEventArgs e)
4029
        {
4030
            _bGPXLog = (bool)checkBoxGPXLog.IsChecked;
4031
        }
4032
        void _gpxAdd(double lat,double lon, int elevation)
4033
        {
4034
            DataRow dr = dtGPX.NewRow();
4035
            dr[0] = dtGPX.Rows.Count - 1;
4036
            dr[1] = lat;
4037
            dr[2] = lon;
4038
            dr[3] = elevation;
4039
            dr[4] = DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture); //2011-01-14T01:59:01Z
4040
            dtGPX.Rows.Add(dr);
4041
        }
4042
        void _saveGPXLog()
4043
        {
4044
            if (!Directory.Exists("GPXLog"))
4045
                Directory.CreateDirectory("GPXLog");
4046
            string SaveFileName = "GPXLog\\" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".gpx";
4047
            XmlTextWriter myXmlTextWriter = null;
4048
            myXmlTextWriter = new XmlTextWriter(SaveFileName, null);
4049
            NumberFormatInfo nfi = new NumberFormatInfo();
4050
            nfi.NumberDecimalSeparator = ".";
2315 - 4051
 
2324 - 4052
            try
4053
            {
4054
                myXmlTextWriter.Formatting = Formatting.Indented;
4055
 
4056
                myXmlTextWriter.WriteStartDocument();
4057
 
4058
                myXmlTextWriter.WriteStartElement("gpx");
4059
 
4060
                myXmlTextWriter.WriteAttributeString("version", "1.0");
4061
                myXmlTextWriter.WriteAttributeString("creator", "MKLiveView v1.0");
4062
                myXmlTextWriter.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
4063
                myXmlTextWriter.WriteAttributeString("xmlns", "http://www.topografix.com/GPX/1/1");
4064
                myXmlTextWriter.WriteAttributeString("xsi:schemaLocation", "http://www.topografix.com/GPX/1/1/gpx.xsd");
4065
 
4066
                myXmlTextWriter.WriteElementString("time", DateTime.UtcNow.ToString("u", System.Globalization.CultureInfo.InvariantCulture));
4067
 
4068
                myXmlTextWriter.WriteStartElement("trk");
4069
                myXmlTextWriter.WriteStartElement("trkseg");
4070
                for(int i = 0; i< dtGPX.Rows.Count;i++)
4071
                {
4072
                    myXmlTextWriter.WriteStartElement("trkpt");
4073
                    myXmlTextWriter.WriteAttributeString("lat", dtGPX.Rows[i][1].ToString() != "" ? ((double)dtGPX.Rows[i][1]).ToString(nfi) : "");
4074
                    myXmlTextWriter.WriteAttributeString("lon", dtGPX.Rows[i][2].ToString() != "" ? ((double)dtGPX.Rows[i][2]).ToString(nfi) : "");
4075
                    myXmlTextWriter.WriteElementString("ele", dtGPX.Rows[i][3].ToString());
4076
                    myXmlTextWriter.WriteElementString("time", dtGPX.Rows[i][4].ToString());
4077
                    myXmlTextWriter.WriteEndElement();
4078
                }
4079
                myXmlTextWriter.WriteEndElement();
4080
                myXmlTextWriter.WriteEndElement();
4081
                myXmlTextWriter.WriteEndElement();
4082
            }
4083
            catch (Exception e)
4084
            {
4085
                Console.WriteLine("Exception: {0}", e.ToString());
4086
            }
4087
            finally
4088
            {
4089
                if (myXmlTextWriter != null)
4090
                {
4091
                    myXmlTextWriter.Close();
4092
                }
4093
            }
4094
        }
2356 - 4095
 
2376 - 4096
 
2324 - 4097
        private void btnLoadGPXLog_Click(object sender, RoutedEventArgs e)
4098
        {
4099
            _loadGPXLog();
4100
        }
2327 - 4101
        private void btnClearRoute_Click(object sender, RoutedEventArgs e)
4102
        {
4103
            _clearMapMarkers(typeof(GMapRoute));
4104
        }
2324 - 4105
        void _loadGPXLog()
4106
        {
4107
 
4108
            Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
4109
            fd.Filter = "GPX-Logfile | *.gpx";
4110
            fd.Multiselect = false;
4111
            if (fd.ShowDialog().Value)
4112
            {
4113
                string file = fd.FileName;
4114
                try
4115
                {
4116
                    XDocument gpxDoc = XDocument.Load(file);
4117
                    XNamespace gpx = XNamespace.Get("http://www.topografix.com/GPX/1/1");
4118
 
4119
                    NumberFormatInfo nfi = new NumberFormatInfo();
4120
                    nfi.NumberDecimalSeparator = ".";
4121
 
4122
                    var tracks = from track in gpxDoc.Descendants(gpx + "trk")
4123
                                 select new
4124
                                 {
4125
                                     Name = track.Element(gpx + "name") != null ? track.Element(gpx + "name").Value : null,
4126
                                     Segs = (
4127
                                         from trackpoint in track.Descendants(gpx + "trkpt")
4128
                                         select new
4129
                                         {
4130
                                             Latitude = trackpoint.Attribute("lat").Value,
4131
                                             Longitude = trackpoint.Attribute("lon").Value,
4132
                                             Elevation = trackpoint.Element(gpx + "ele") != null ?
4133
                                             trackpoint.Element(gpx + "ele").Value : null,
4134
                                             Time = trackpoint.Element(gpx + "time") != null ?
4135
                                             trackpoint.Element(gpx + "time").Value : null
4136
                                         }
4137
                                     )
4138
                                 };
4139
 
4140
                    List<PointLatLng> wpl = new List<PointLatLng>();
4141
                    foreach(var trk in tracks)
4142
                    {
4143
                        foreach(var trkseg in trk.Segs)
4144
                        {
4145
                            if(trkseg.Latitude != "" && trkseg.Longitude !="")
4146
                            wpl.Add(new PointLatLng(Convert.ToDouble(trkseg.Latitude, nfi), Convert.ToDouble(trkseg.Longitude, nfi)));
4147
                        }
4148
 
4149
                    }
4150
                    if(wpl.Count() > 0)
4151
                    {
2327 - 4152
                        _clearMapMarkers(typeof(GMapRoute));
2324 - 4153
                        MapRoute mr = new MapRoute(wpl, "flying");
2328 - 4154
                        Dispatcher.Invoke(() =>
4155
                        {
4156
                            GMapRoute mRoute;
4157
                            if (comboBoxRouteColor.SelectionBoxItem != null)
4158
                            {
4159
                                string s = comboBoxRouteColor.SelectionBoxItem.ToString();
2366 - 4160
                                mRoute = new GMapRoute(wpl, _getBrush(s));
2328 - 4161
                            }
4162
                            else
2366 - 4163
                                mRoute = new GMapRoute(wpl, null);
2324 - 4164
 
2328 - 4165
                            MainMap.Markers.Add(mRoute);
4166
                        });
2324 - 4167
                    }
4168
 
4169
                }
4170
                catch (Exception e)
4171
                {
4172
                    Console.WriteLine("Exception: {0}", e.ToString());
4173
                }
4174
            }
4175
        }
4176
        #endregion GPX
2315 - 4177
        #endregion functions
2287 - 4178
    }
2315 - 4179
     /// <summary>
4180
    /// formats the wp datatable values for display in datagrid - this is bound in the datagrid as a converter
4181
    /// </summary>
2313 - 4182
    public class waypointsConverter : IValueConverter
4183
    {
4184
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
4185
        {
4186
            if (value != null)
4187
            {
4188
                switch ((string)parameter)
4189
                {
4190
                    case "Latitude":
4191
                        return value.ToString() + " °";
4192
                    case "Longitude":
4193
                        return value.ToString() + " °";
4194
                    case "Radius":
4195
                        return value.ToString() + " m";
4196
                    case "Altitude":
4197
                        return value.ToString() + " m";
4198
                    case "ClimbRate":
4199
                        return value.ToString() == "255" ? "Auto" : (System.Convert.ToDouble(value) / 10).ToString("0.0 m/s");
4200
                    case "DelayTime":
4201
                        return value.ToString() + " s";
4202
                    case "Heading":
4203
                        return Waypoints.Heading(System.Convert.ToInt32(value));
4204
                    case "Speed":
4205
                        return Waypoints.WPSpeed(System.Convert.ToInt16(value));
4206
                    case "CamAngle":
4207
                        return Waypoints.CAMAngle(System.Convert.ToInt16(value));
4208
                    case "Type":
4209
                        return ((Waypoints.pointType)(System.Convert.ToInt16(value))).ToString();
4210
                    case "AutoTrigger":
4211
                        return value.ToString() == "0" ? "- - -" : value.ToString() + " m";
4212
                    case "Status":
2355 - 4213
                        return (Waypoints.status)(System.Convert.ToInt16(value));
2313 - 4214
                }
4215
 
4216
                return value.ToString();
4217
            }
4218
            else return value;
4219
        }
4220
 
4221
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
4222
        {
4223
            throw new NotImplementedException();
4224
        }
4225
    }
4226
 
2287 - 4227
    public class IniFile
4228
    {
4229
        public string path;
4230
 
4231
        [DllImport("kernel32")]
4232
        private static extern long WritePrivateProfileString(string section,
4233
          string key, string val, string filePath);
4234
 
4235
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
4236
        static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
4237
               uint nSize, string lpFileName);
4238
 
4239
        [DllImport("kernel32")]
4240
        private static extern int GetPrivateProfileString(string section,
4241
          string key, string def, StringBuilder retVal,
4242
          int size, string filePath);
4243
 
4244
        public IniFile(string INIPath)
4245
        {
4246
            path = INIPath;
4247
        }
4248
 
4249
        public void IniWriteValue(string Section, string Key, string Value)
4250
        {
4251
            WritePrivateProfileString(Section, Key, Value, this.path);
4252
        }
4253
 
4254
        public string IniReadValue(string Section, string Key)
4255
        {
4256
            StringBuilder temp = new StringBuilder(255);
4257
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
4258
            return temp.ToString();
4259
        }
4260
        //Ini_sections auslesen in String-Array
4261
        public string[] IniSectionNames()
4262
        {
4263
 
4264
            //  uint MAX_BUFFER = 32767;
4265
            uint MAX_BUFFER = 8388608;
4266
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
4267
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, this.path);
4268
            if (bytesReturned == 0)
4269
            {
4270
                Marshal.FreeCoTaskMem(pReturnedString);
4271
                return null;
4272
            }
4273
            string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
4274
            Marshal.FreeCoTaskMem(pReturnedString);
4275
            //use of Substring below removes terminating null for split
4276
            return local.Substring(0, local.Length - 1).Split('\0');
4277
 
4278
 
4279
        }
4280
    }
4281
 
4282
    /// <summary>
4283
    /// Selected Win AI Function Calls
4284
    /// </summary>
4285
    public class WinApi
4286
    {
4287
        [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
4288
        public static extern int GetSystemMetrics(int which);
4289
        [DllImport("user32.dll")]
4290
        public static extern void
4291
                SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
4292
                             int X, int Y, int width, int height, uint flags);
4293
 
4294
        private const int SM_CXSCREEN = 0;
4295
        private const int SM_CYSCREEN = 1;
4296
        private static IntPtr HWND_TOP = IntPtr.Zero;
4297
        private const int SWP_SHOWWINDOW = 64; // 0x0040
4298
 
4299
        public static int ScreenX
4300
        {
4301
            get { return GetSystemMetrics(SM_CXSCREEN); }
4302
        }
4303
 
4304
        public static int ScreenY
4305
        {
4306
            get { return GetSystemMetrics(SM_CYSCREEN); }
4307
        }
4308
 
4309
        public static void SetWinFullScreen(IntPtr hwnd)
4310
        {
4311
            SetWindowPos(hwnd, HWND_TOP, -8, -7, ScreenX+15, ScreenY+14, SWP_SHOWWINDOW);
4312
        }
4313
    }
4314
    /// <summary>
4315
    /// Class used to preserve / restore state of the window
4316
    /// </summary>
4317
    public class WinState
4318
    {
4319
        private WindowState winState;
4320
        private WindowStyle brdStyle;
4321
        private bool topMost;
4322
        private Rect restore;
4323
        private bool IsMaximized = false;
4324
 
4325
        public bool isMaximized
4326
        {
4327
            get { return IsMaximized; }
4328
        }
4329
        public void Maximize(Window targetForm)
4330
        {
4331
            if (!IsMaximized)
4332
            {
4333
                IsMaximized = true;
4334
                Save(targetForm);
4335
                targetForm.WindowState = WindowState.Maximized;
4336
                targetForm.WindowStyle = WindowStyle.None;
4337
                targetForm.Topmost = true;
4338
                WinApi.SetWinFullScreen(new WindowInteropHelper(targetForm).Handle);
4339
            }
4340
        }
4341
 
4342
        public void Save(Window targetForm)
4343
        {
4344
            winState = targetForm.WindowState;
4345
            brdStyle = targetForm.WindowStyle;
4346
            topMost = targetForm.Topmost;
4347
            restore = targetForm.RestoreBounds;
4348
        }
4349
        public void Restore(Window targetForm)
4350
        {
4351
            targetForm.WindowState = winState;
4352
            targetForm.WindowStyle = brdStyle;
4353
            targetForm.Topmost = topMost;
4354
 
4355
            targetForm.Left = restore.Left;
4356
            targetForm.Top = restore.Top;
4357
            targetForm.Height = restore.Height;
4358
            targetForm.Width = restore.Width;
4359
            IsMaximized = false;
4360
        }
4361
    }
4362
 
4363
}