Subversion Repositories Projects

Rev

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

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