Subversion Repositories Projects

Rev

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

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