Subversion Repositories Projects

Rev

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