Subversion Repositories Projects

Rev

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

Rev Author Line No. Line
2233 - 1
///============================================================================
2
/// MKLiveView 
3
/// Copyright © 2016 Steph
4
/// 
5
///This file is part of MKLiveView.
6
///
7
///MKLiveView is free software: you can redistribute it and/or modify
8
///it under the terms of the GNU General Public License as published by
9
///the Free Software Foundation, either version 3 of the License, or
10
///(at your option) any later version.
11
///
12
///MKLiveView is distributed in the hope that it will be useful,
13
///but WITHOUT ANY WARRANTY; without even the implied warranty of
14
///MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
///GNU General Public License for more details.
16
///
17
///You should have received a copy of the GNU General Public License
18
///along with cssRcon.  If not, see <http://www.gnu.org/licenses/>.
19
///
20
///============================================================================
21
///Credits:
22
///Chootair (http://www.codeproject.com/script/Membership/View.aspx?mid=3941737)
23
///for his "C# Avionic Instrument Controls" (http://www.codeproject.com/Articles/27411/C-Avionic-Instrument-Controls)
24
///I used some of his code for displaying the compass 
25
///
26
///Tom Pyke (http://tom.pycke.be)
27
///for his "Artifical horizon" (http://tom.pycke.be/mav/100/artificial-horizon)
28
///Great job!
29
///
30
/// and last but most of all to JOHN C. MACDONALD at Ira A. Fulton College of Engineering and Technology
31
/// for his MIKROKOPTER SERIAL CONTROL TUTORIAL (http://hdl.lib.byu.edu/1877/2747)
2265 - 32
/// and the sourcecode (http://hdl.lib.byu.edu/1877/2748)
2233 - 33
/// By his work I finally managed to get the communication with the Mikrokopter controllers to run
34
/// Some of his code was used in this programm like the SimpelSerialPort class (with some changes)
35
/// and the FilghtControllerMessage class
36
/// 
37
///============================================================================
2259 - 38
/// DISCLAIMER
39
/// ===========
40
/// 
41
/// I created this software with my best knowledge and belief.
42
/// 
43
/// IN NO EVENT, UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, 
44
/// SHALL I, OR ANY PERSON BE LIABLE FOR ANY LOSS, EXPENSE OR DAMAGE, 
45
/// OF ANY TYPE OR NATURE ARISING OUT OF THE USE OF, 
46
/// OR INABILITY TO USE THIS SOFTWARE OR PROGRAM, 
47
/// INCLUDING, BUT NOT LIMITED TO, CLAIMS, SUITS OR CAUSES OF ACTION 
48
/// INVOLVING ALLEGED INFRINGEMENT OF COPYRIGHTS, 
49
/// PATENTS, TRADEMARKS, TRADE SECRETS, OR UNFAIR COMPETITION.
50
/// 
51
/// This means: use it & have fun (but @ Your own risk...)
52
/// ===========================================================================
2233 - 53
 
54
using System;
55
using System.Data;
56
using System.Drawing;
57
using System.Text;
58
using System.Windows.Forms;
59
using System.IO;
60
using System.Threading;
61
using System.Diagnostics;
62
using System.Runtime.InteropServices;
63
 
64
namespace MKLiveView
65
{
66
    public partial class MainForm : Form
67
    {
2250 - 68
        String[] NC_Error = new string[44]
69
        {
70
            "No Error",
71
            "FC not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A1_.22FC_not_compatible_.22",
72
            "MK3Mag not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A2_.22MK3Mag_not_compatible_.22",
73
            "no FC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A3_.22no_FC_communication_.22",
74
            "no compass communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A4_.22no_compass_communication_.22",
75
            "no GPS communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A5_.22no_GPS_communication_.22",
76
            "bad compass value" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A6_.22bad_compass_value.22",
77
            "RC Signal lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A7_.22RC_Signal_lost_.22",
78
            "FC spi rx error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A8_.22FC_spi_rx_error_.22",
79
            "ERR: no NC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A9:_.22ERR:_no_NC_communication.22",
80
            "ERR: FC Nick Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A10_.22ERR:_FC_Nick_Gyro.22",
81
            "ERR: FC Roll Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A11_.22ERR:_FC_Roll_Gyro.22",
82
            "ERR: FC Yaw Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A12_.22ERR:_FC_Yaw_Gyro.22",
83
            "ERR: FC Nick ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A13_.22ERR:_FC_Nick_ACC.22",
84
            "ERR: FC Roll ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A14_.22ERR:_FC_Roll_ACC.22",
85
            "ERR: FC Z-ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A15_.22ERR:_FC_Z-ACC.22",
86
            "ERR: Pressure sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A16_.22ERR:_Pressure_sensor.22",
87
            "ERR: FC I2C" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A17_.22ERR:_FC_I2C.22",
88
            "ERR: Bl Missing" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A18_.22ERR:_Bl_Missing.22",
89
            "Mixer Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A19_.22Mixer_Error.22",
90
            "FC: Carefree Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A20_.22FC:_Carefree_Error.22",
91
            "ERR: GPS lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A21_.22ERR:_GPS_lost.22",
92
            "ERR: Magnet Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A22_.22ERR:_Magnet_Error.22",
93
            "Motor restart" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A23_.22Motor_restart.22",
94
            "BL Limitation" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A24_.22BL_Limitation.22",
95
            "Waypoint range" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A25_.22Waypoint_range.22",
96
            "ERR:No SD-Card" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A26_.22ERR:No_SD-Card.22",
97
            "ERR:SD Logging aborted" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A27_.22ERR:SD_Logging_aborted.22",
98
            "ERR:Flying range!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A28_.22ERR:Flying_range.21.22",
99
            "ERR:Max Altitude" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A29_.22ERR:Max_Altitude.22",
100
            "No GPS Fix" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A30_.22No_GPS_Fix.22",
101
            "compass not calibrated" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A31_.22compass_not_calibrated.22",
102
            "ERR:BL selftest" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A32_.22ERR:BL_selftest.22",
103
            "no ext. compass" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A33_.22no_ext._compass.22",
104
            "compass sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A34_.22compass_sensor.22",
105
            "FAILSAFE pos.!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A35_.22FAILSAFE_pos..21__.22",
106
            "ERR:Redundancy" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A36_.22ERR:Redundancy__.22",
107
            "Redundancy test" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A37_.22Redundancy_test_.22",
108
            "GPS Update rate" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A38_.22GPS_Update_rate.22",
109
            "ERR:Canbus" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A39_.22ERR:Canbus.22",
110
            "ERR: 5V RC-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A40_.22ERR:_5V_RC-Supply.22",
111
            "ERR:Power-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A41_.22ERR:Power-Supply.22",
112
            "ACC not calibr." + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A42_.22ACC_not_calibr..22",
113
            "ERR:Parachute!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A43_.22ERR:Parachute.21.22"
114
        };
2233 - 115
 
116
        [FlagsAttribute]
117
        enum NC_HWError0 : short
118
        {
119
            None = 0,
120
            SPI_RX = 1,
121
            COMPASS_RX = 2,
122
            FC_INCOMPATIBLE = 4,
123
            COMPASS_INCOMPATIBLE = 8,
124
            GPS_RX = 16,
125
            COMPASS_VALUE = 32
126
        };
127
        [FlagsAttribute]
128
        enum FC_HWError0 : short
129
        {
130
            None = 0,
131
            GYRO_NICK = 1,
132
            GYRO_ROLL = 2,
133
            GYRO_YAW = 4,
134
            ACC_NICK = 8,
135
            ACC_ROLL = 16,
136
            ACC_TOP = 32,
137
            PRESSURE = 64,
138
            CAREFREE = 128
139
        };
140
        [FlagsAttribute]
141
        enum FC_HWError1 : short
142
        {
143
            None = 0,
144
            I2C = 1,
145
            BL_MISSING = 2,
146
            SPI_RX = 4,
147
            PPM = 8,
148
            MIXER = 16,
149
            RC_VOLTAGE = 32,
150
            ACC_NOT_CAL = 64,
151
            RES3 = 128
152
        };
153
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
154
        // Various colors for logging info
155
        private Color[] LogMsgTypeColor = { Color.FromArgb(43, 145, 175), Color.Green, Color.Black, Color.Orange, Color.Red };
156
 
157
        string[] sAnalogLabel = new string[32];
158
        string[] sAnalogData = new string[32];
159
        bool bReadContinously = false;
160
        bool check_HWError = false;
161
        bool _bCBInit = true;
162
        bool _init = true;
163
        bool _debugDataAutorefresh = true;
164
        bool _navCtrlDataAutorefresh = true;
165
        bool _blctrlDataAutorefresh = true;
166
        bool _OSDAutorefresh = true;
2254 - 167
        bool _bErrorLog = false;
2233 - 168
        int crcError = 0;
169
        int iLableIndex = 0;
170
        string filePath = Directory.GetCurrentDirectory();
171
        string fileName = "NCLabelTexts.txt";
172
        int _iCtrlAct = 0;
173
        int _iLifeCounter = 0;
174
        int iOSDPage = 0;
175
        int iOSDMax = 0;
2257 - 176
        int[] serChan = new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
177
        string[] serChanTitle = new string[12];
2233 - 178
        /// <summary>
179
        /// interval for sending debugdata (multiplied by 10ms)
180
        /// </summary>
2265 - 181
        byte debugInterval = 10; //(=> 100ms)
2233 - 182
        /// <summary>
183
        /// interval for sending BL-CTRL status (multiplied by 10ms)
184
        /// </summary>
2265 - 185
        byte blctrlInterval = 75;
2233 - 186
        /// <summary>
187
        /// interval for sending NAV-CTRL status (multiplied by 10ms)
188
        /// </summary>
189
        byte navctrlInterval = 80;
190
        /// <summary>
191
        /// interval for sending OSD page update (multiplied by 10ms)
192
        /// </summary>
193
        byte OSDInterval = 85;
194
        /// <summary>
195
        /// datatable for the debug data array - displayed on settings tabpage in datagridview
196
        /// </summary>
197
        DataTable dtAnalog = new DataTable();
2254 - 198
        /// <summary>
199
        /// datatable for motordata (current,temp)
200
        /// </summary>
2250 - 201
        DataTable dtMotors1 = new DataTable();
202
        DataTable dtMotors2 = new DataTable();
203
 
2257 - 204
        DataTable dtWaypoints = new DataTable();
205
 
2233 - 206
        public MainForm()
207
        {
208
            InitializeComponent();
2274 - 209
            _initForm();
210
        }
211
        void _initForm()
212
        {
2257 - 213
            serChanTitle.Initialize();
214
 
2233 - 215
            _readIni();
2257 - 216
 
2259 - 217
            _dataTablesInit();
2257 - 218
 
2233 - 219
            simpleSerialPort.PortClosed += SimpleSerialPort_PortClosed;
220
            simpleSerialPort.PortOpened += SimpleSerialPort_PortOpened;
221
            simpleSerialPort.DataReceived += processMessage;
2265 - 222
 
2233 - 223
            chkbAutoBL.Checked = _blctrlDataAutorefresh;
224
            chkbAutoDbg.Checked = _debugDataAutorefresh;
225
            chkbAutoNav.Checked = _navCtrlDataAutorefresh;
226
            chkbAutoOSD.Checked = _OSDAutorefresh;
2265 - 227
 
2233 - 228
            labelTimingDebug.Text = (debugInterval * 10).ToString();
229
            labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
230
            labelTimingNAV.Text = (navctrlInterval * 10).ToString();
231
            labelTimingOSD.Text = (OSDInterval * 10).ToString();
2265 - 232
 
233
            TabControl1.TabPages.Remove(tabPageTesting); //a testing page
2233 - 234
        }
235
        #region events
236
        private void MainForm_Shown(object sender, EventArgs e)
237
        {
238
            _loadLabelNames();
2257 - 239
            _initSerialCtrl();
2233 - 240
            _init = false;
2265 - 241
            splitContainer1.SplitterDistance = 510;
2233 - 242
        }
243
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
244
        {
245
            _writeIni();
2274 - 246
            // after adding a second language the programm didn't close properly anymore
247
            // so this is kinda workaround...
248
            Dispose(true);
249
            Environment.Exit(0);
2233 - 250
        }
251
        private void SimpleSerialPort_PortOpened()
252
        {
253
            btnConn.Invoke((Action)(() => btnConn.BackColor = Color.FromArgb(192, 255, 192)));
2274 - 254
            if(Thread.CurrentThread.CurrentUICulture.Name== "")
255
                btnConn.Invoke((Action)(() => btnConn.Text = "close" + Environment.NewLine + "serial port"));
256
            else
257
                btnConn.Invoke((Action)(() => btnConn.Text = "COM-Port" + Environment.NewLine + "schliessen"));
2233 - 258
            _getVersion();
259
            Thread.Sleep(100);
260
            _OSDMenue(0);
2257 - 261
            Thread.Sleep(200);
262
            _sendSerialData();
2233 - 263
           // _readCont(true);
264
        }
265
        private void SimpleSerialPort_PortClosed()
266
        {
267
            btnConn.Invoke((Action)(() => btnConn.BackColor = Color.FromArgb(224, 224, 224)));
2274 - 268
            if (Thread.CurrentThread.CurrentUICulture.Name == "")
269
                btnConn.Invoke((Action)(() => btnConn.Text = "open" + Environment.NewLine + "serial port"));
270
            else
271
                btnConn.Invoke((Action)(() => btnConn.Text = "COM-Port" + Environment.NewLine + "öffnen"));
2233 - 272
            _readCont(false);
273
        }
274
        /// <summary>
275
        /// timer for refreshing subscription of subscribed data
276
        /// query lifecounter for connection failure
277
        /// </summary>
278
        private void timer1_Tick(object sender, EventArgs e)
279
        {
280
            if(bReadContinously)
281
            {
282
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
283
 
2250 - 284
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
2233 - 285
 
286
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
287
                check_HWError = true;
288
                _getVersion();
289
                Thread.Sleep(10);
290
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); }
291
                if (_iLifeCounter > 0)
292
                {
293
                    lblLifeCounter.BackColor = Color.FromArgb(0, 224, 0);
294
                    _iLifeCounter = 0;
295
                }
296
                else
297
                {
298
                    Log(LogMsgType.Error, "No communication to NC/FC!");
299
                    lblLifeCounter.BackColor = Color.FromArgb(224, 0, 0);
300
                }
301
            }
302
        }
303
        private void cbOSD_SelectedIndexChanged(object sender, EventArgs e)
304
        {
305
            if (!_bCBInit && cbOSD.SelectedIndex > -1)
306
                _OSDMenue(cbOSD.SelectedIndex);
307
        }
308
        private void chkbAutoDbg_CheckedChanged(object sender, EventArgs e)
309
        {
310
            if(!_init) _debugDataAutorefresh = chkbAutoDbg.Checked;
311
        }
312
        private void chkbAutoNav_CheckedChanged(object sender, EventArgs e)
313
        {
314
            if (!_init) _navCtrlDataAutorefresh = chkbAutoNav.Checked;
315
        }
316
        private void chkbAutoBL_CheckedChanged(object sender, EventArgs e)
317
        {
318
            if (!_init) _blctrlDataAutorefresh = chkbAutoBL.Checked;
319
        }
320
        private void chkbAutoOSD_CheckedChanged(object sender, EventArgs e)
321
        {
322
            if (!_init) _OSDAutorefresh = chkbAutoOSD.Checked;
323
        }
324
        private void cbTimingDebug_SelectedIndexChanged(object sender, EventArgs e)
325
        {
326
            if (cbTimingDebug.SelectedIndex > -1)
327
            {
328
                debugInterval = (byte)(Convert.ToInt16(cbTimingDebug.SelectedItem) / 10);
329
                labelTimingDebug.Text = (debugInterval * 10).ToString();
330
            }
331
        }
332
        private void cbTimingNAV_SelectedIndexChanged(object sender, EventArgs e)
333
        {
334
            if (cbTimingNAV.SelectedIndex > -1)
335
            {
336
                navctrlInterval = (byte)(Convert.ToInt16(cbTimingNAV.SelectedItem) / 10);
337
                labelTimingNAV.Text = (navctrlInterval * 10).ToString();
338
            }
339
        }
340
        private void cbTimingBLCTRL_SelectedIndexChanged(object sender, EventArgs e)
341
        {
342
            if (cbTimingBLCTRL.SelectedIndex > -1)
343
            {
344
                blctrlInterval = (byte)(Convert.ToInt16(cbTimingBLCTRL.SelectedItem) / 10);
345
                labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
346
            }
347
        }
348
        private void cbTimingOSD_SelectedIndexChanged(object sender, EventArgs e)
349
        {
350
            if (cbTimingOSD.SelectedIndex > -1)
351
            {
352
                OSDInterval = (byte)(Convert.ToInt16(cbTimingOSD.SelectedItem) / 10);
353
                labelTimingOSD.Text = (OSDInterval * 10).ToString();
354
            }
355
        }
2254 - 356
        private void rtfError_LinkClicked(object sender, LinkClickedEventArgs e)
357
        {
358
            System.Diagnostics.Process.Start(e.LinkText);
359
        }
2274 - 360
        /// <summary>
361
        /// Combobox for selecting UI language
362
        /// </summary>
363
        /// <param name="sender"></param>
364
        /// <param name="e"></param>
365
        private void cbLanguage_SelectedIndexChanged(object sender, EventArgs e)
366
        {
367
            if (cbLanguage.SelectedIndex == 1)
368
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE");
369
            else
370
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("");
371
            updateStringRessource();
372
        }
373
        /// <summary>
374
        /// the form has to be recreated when changing the language of the UI
375
        /// </summary>
376
        private void updateStringRessource()
377
        {
378
            try
379
            {
380
                Point pt = this.Location;// memorize location of form
381
                Size sz = this.Size;// memorize size of form
382
 
383
                if (simpleSerialPort.Port.IsOpen)
384
                {
385
                    simpleSerialPort.Port.Close();
386
                    Thread.Sleep(200);
387
                    _readCont(false);
388
                    Thread.Sleep(100);
389
                    while (simpleSerialPort.Port.IsOpen | bReadContinously)
390
                        Thread.Sleep(100);
391
                }
392
 
393
                this.Controls.Clear();// clear all controls of form
394
                components.Dispose();// dispose all components and release resources
395
                // delete all events to avoid double instances when calling  InitializeComponent(); 
396
                this.Events.Dispose();
397
                if (timer1 != null)
398
                {
399
                    timer1.Dispose();
400
                    timer1 = null;
401
                }
402
                _init = true;
403
                timer1 = new System.Windows.Forms.Timer();
404
 
405
                dtAnalog = new DataTable();
406
                dtMotors1 = new DataTable();
407
                dtMotors2 = new DataTable();
408
                dtWaypoints = new DataTable();
409
 
410
                InitializeComponent(); // reload UI
411
 
412
                _dataTablesInit();
413
 
414
                simpleSerialPort.PortClosed += SimpleSerialPort_PortClosed;
415
                simpleSerialPort.PortOpened += SimpleSerialPort_PortOpened;
416
                simpleSerialPort.DataReceived += processMessage;
417
 
418
                chkbAutoBL.Checked = _blctrlDataAutorefresh;
419
                chkbAutoDbg.Checked = _debugDataAutorefresh;
420
                chkbAutoNav.Checked = _navCtrlDataAutorefresh;
421
                chkbAutoOSD.Checked = _OSDAutorefresh;
422
 
423
                labelTimingDebug.Text = (debugInterval * 10).ToString();
424
                labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
425
                labelTimingNAV.Text = (navctrlInterval * 10).ToString();
426
                labelTimingOSD.Text = (OSDInterval * 10).ToString();
427
 
428
                TabControl1.TabPages.Remove(tabPageTesting); //a testing page
429
 
430
                this.Size = sz;// set size
431
                this.Location = pt;// position form
432
                _loadLabelNames();
433
                _initSerialCtrl();
434
                _init = false;
435
 
436
            }
437
            catch (Exception ex)
438
            {
439
                MessageBox.Show(ex.Message);
440
            }
441
        }
442
 
2233 - 443
        #endregion events
444
 
445
        /// <summary> Log data to the terminal window. </summary>
446
        /// <param name="msgtype"> The type of message to be written. </param>
447
        /// <param name="msg"> The string containing the message to be shown. </param>
448
        private void Log(LogMsgType msgtype, string msg)
449
        {
450
            rtfTerminal.Invoke(new EventHandler(delegate
451
            {
452
                if (rtfTerminal.Lines.Length >= 1000)   //Wenn Terminal mehr als 1000 Zeilen hat
453
                    rtfTerminal.Select(42, (500 * 129));     //500 löschen
454
                rtfTerminal.Select(rtfTerminal.Text.Length, 0);
455
                rtfTerminal.SelectedText = string.Empty;
456
                rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Regular);
457
                rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
458
                rtfTerminal.AppendText(msg + Environment.NewLine);
459
                rtfTerminal.ScrollToCaret();
460
            }));
461
        }
462
        /// <summary> display the OSD text in 4 lines à 20 chars </summary>
463
        /// <param name="msgtype"> The type of message to be written. </param>
464
        /// <param name="msg"> The string containing the message to be shown. </param>
465
        private void OSD(LogMsgType msgtype, string msg)
466
        {
467
            rtfOSD.Invoke(new EventHandler(delegate
468
            {
469
                if (rtfOSD.Lines.Length > 4)
470
                    rtfOSD.Clear();
471
                rtfOSD.Select(rtfOSD.Text.Length,0);
472
                rtfOSD.SelectedText = string.Empty;
473
                rtfOSD.SelectionFont = new Font(rtfOSD.SelectionFont, FontStyle.Regular);
474
                rtfOSD.SelectionColor = LogMsgTypeColor[(int)msgtype];
475
                rtfOSD.AppendText(msg + Environment.NewLine);
476
                if (rtfOSD.Text.IndexOf("ERR") > 0)
477
                {
478
                    rtfOSD.Select(rtfOSD.Text.IndexOf("ERR"), 40);
479
                    rtfOSD.SelectionColor = LogMsgTypeColor[(int)LogMsgType.Error];
480
                }
481
            }));
482
        }
483
        private void ErrorLog(LogMsgType msgtype, string msg)
484
        {
485
            rtfError.Invoke(new EventHandler(delegate
486
            {
487
                if (rtfError.Lines.Length > 4)
488
                    rtfError.Clear();
489
                rtfError.Focus();
490
                rtfError.Select(rtfError.Text.Length, 0);
491
                rtfError.SelectedText = string.Empty;
492
                rtfError.SelectionFont = new Font(rtfError.SelectionFont, FontStyle.Regular);
493
                rtfError.SelectionColor = LogMsgTypeColor[(int)msgtype];
494
                rtfError.AppendText(msg + Environment.NewLine);
495
 
496
            }));
2254 - 497
            _bErrorLog = true;
2233 - 498
        }
499
 
500
        #region functions        
501
 
2250 - 502
        #region processing received data
503
        /// <summary> Processing the messages and displaying them in the according form controls 
504
        /// function called by simpleSerialPort.DataReceived event
505
        /// </summary>
2233 - 506
        /// <param name="message"> message bytearray recieved by SimpleSerialPort class </param>
507
        private void processMessage(byte[] message)
508
        {
509
            if (message.Length > 0)
510
            {
511
                _iLifeCounter++;
512
                //Log(LogMsgType.Incoming, BitConverter.ToString(message));
513
                //Log(LogMsgType.Incoming, message.Length.ToString());
514
                string s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, message.Length));
515
                char cmdID;
516
                byte adr;
517
                byte[] data;
2257 - 518
                byte[] tmp = null;
2233 - 519
                if (message[0] != '#')
2257 - 520
                {
521
                    int iFound = -1;
522
                    for(int i=0;i<message.Length;i++)   //Sometimes the FC/NC sends strings without termination (like WP messages)
523
                    {                                   //so this is a workaround to not spam the log box
524
                        if (message[i] == 35)
525
                        {
526
                            iFound = i;
527
                            break;
528
                        }                          
529
                    }
530
                    if(iFound>0)
531
                    {
532
                        s = new string(ASCIIEncoding.ASCII.GetChars(message, 0,iFound));
533
                        tmp = new byte[message.Length - iFound];
534
                        Buffer.BlockCopy(message, iFound, tmp, 0, message.Length - iFound);
535
                    }
536
                    s = s.Trim('\0', '\n', '\r');
537
                    if(s.Length > 0)
538
                        Log(LogMsgType.Normal, s);
539
                    if (tmp != null)
540
                    {
541
                        s = new string(ASCIIEncoding.ASCII.GetChars(tmp, 0, tmp.Length));
542
                        processMessage(tmp);
543
                    }
544
                }
2233 - 545
                //Debug.Print(s);
546
                else
547
                {
548
                    FlightControllerMessage.ParseMessage(message, out cmdID, out adr, out data);
549
 
550
                    if (adr == 255) { crcError++; }
551
                    else crcError = 0;
552
                    lblCRCErr.Invoke((Action)(() => lblCRCErr.Text = crcError.ToString()));
2250 - 553
                    //display the active controller (FC / NC) 
2233 - 554
                    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...???
555
                    {
556
                        _iCtrlAct = adr;
557
                        switch (adr)
558
                        {
559
                            case 1:
560
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "FC"));
561
                                lblNCCtrl.Invoke((Action)(() => lblNCCtrl.Text = "FC"));
562
                                _setFieldsNA(); //display fields NA for FC 
563
                                break;
564
                            case 2:
565
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "NC"));
566
                                lblNCCtrl.Invoke((Action)(() => lblNCCtrl.Text = "NC"));
567
                                break;
568
                            case 3:
569
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "MK3MAG"));
570
                                break;
571
                            case 4:
572
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "BL-CTRL"));
573
                                break;
574
                            default:
575
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "...."));
576
                                break;
577
                        }
2257 - 578
                        _loadLabelNames();
2233 - 579
                    }
2257 - 580
                    // else
581
                    //     Debug.Print("Address == 0?");
2233 - 582
 
583
                    if (data != null && data.Length > 0)
584
                    {
585
                        s = new string(ASCIIEncoding.ASCII.GetChars(data, 1, data.Length - 1));
586
                        s = s.Trim('\0', '\n');
587
 
588
                        switch (cmdID)
589
                        {
2250 - 590
                            case 'A': //Label names
591
                                _processLabelNames(s);
2233 - 592
                                break;
593
 
2250 - 594
                            case 'D': //Debug data
2257 - 595
                                _processDebugVals(adr, data);
2233 - 596
                                break;
597
 
2250 - 598
                            case 'V': //Version
599
                                _processVersion(adr, data);
2233 - 600
                                break;
601
 
2250 - 602
                            case 'K'://BL-CTRL data
603
                                _processBLCtrl(data);
2233 - 604
                                break;
605
 
606
                            case 'O': //NC Data
2250 - 607
                                _processNCData(data);
2233 - 608
                                break;
609
 
610
                            case 'E': //NC error-string
611
                                ErrorLog(LogMsgType.Error, "NC Error: " + s);
612
                                break;
613
 
2250 - 614
                            case 'L': //OSD Menue (called by pagenumber)
615
                                _processOSDSingle(data);
2233 - 616
                                break;
617
 
2250 - 618
                            case 'H': //OSD Menue (with autoupdate - called by Key)
619
                                _processOSDAuto(data);
2233 - 620
                                break;
621
 
2257 - 622
                            case 'X': //Waypoint data
623
                                _processWPData(data);
624
                                break;
625
 
2233 - 626
                            //default:
627
                            //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
628
                            //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
629
                            //    break;
630
                        }
631
                    }
632
                    //else
633
                    //{
634
                    //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
635
                    //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
636
                    //}
637
                }
638
            }
639
        }
2250 - 640
        /// <summary>
641
        /// Analog label names 'A'
642
        /// each label name is returned as a single string 
643
        /// and added to string array sAnalogLabel[]
644
        /// and the datatable dtAnalog
645
        /// </summary>
646
        /// <param name="s">the label name</param>
647
        void _processLabelNames(string s)
648
        {
649
            if (iLableIndex < 32)
650
            {
651
                sAnalogLabel[iLableIndex] = s;
652
                if (dtAnalog.Rows.Count < 32)
653
                    dtAnalog.Rows.Add(s, "");
654
                else
655
                    dtAnalog.Rows[iLableIndex].SetField(0, s);
2233 - 656
 
2250 - 657
                _getAnalogLabels(iLableIndex + 1);
658
            }
659
            Debug.Print(s);
660
        }
661
        /// <summary>
662
        /// Debug values 'D'
663
        /// </summary>
664
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
665
        /// <param name="data">the received byte array to process</param>
666
        void _processDebugVals(byte adr,byte[] data)
667
        {
668
            if (data.Length == 66)
669
            {
670
                int[] iAnalogData = new int[32];
671
 
672
                int index = 0;
673
                Int16 i16 = 0;
674
                double dTemp = 0;
675
                for (int i = 2; i < 66; i += 2)
676
                {
677
                    i16 = data[i + 1];
678
                    i16 = (Int16)(i16 << 8);
679
                    iAnalogData[index] = data[i] + i16;
680
                    sAnalogData[index] = (data[i] + i16).ToString();
681
                    dtAnalog.Rows[index].SetField(1, sAnalogData[index]);
682
 
683
                    if (adr == 2) //NC
684
                    {
685
                        switch (index)
686
                        {
687
                            case 0: //pitch (German: nick)
688
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.pitch_angle = ((double)iAnalogData[index] / (double)10)));
689
                                lblNCPitch.Invoke((Action)(() => lblNCPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
690
                                break;
691
                            case 1: //roll
692
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.roll_angle = ((double)iAnalogData[index] / (double)10)));
693
                                lblNCRoll.Invoke((Action)(() => lblNCRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
694
                                break;
695
                            case 4: //altitude
696
                                lblNCAlt.Invoke((Action)(() => lblNCAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m")));
697
                                break;
698
                            case 7: //Voltage
699
                                lblNCVolt.Invoke((Action)(() => lblNCVolt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 V")));
700
                                break;
701
                            case 8: // Current
702
                                lblNCCur.Invoke((Action)(() => lblNCCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A")));
703
                                break;
704
                            case 10: //heading
705
                                lblNCCompass.Invoke((Action)(() => lblNCCompass.Text = sAnalogData[index] + "°"));
706
                                headingIndicator1.Invoke((Action)(() => headingIndicator1.SetHeadingIndicatorParameters(iAnalogData[index])));
707
                                break;
708
                            case 12: // SPI error
709
                                lblNCSPI.Invoke((Action)(() => lblNCSPI.Text = sAnalogData[index]));
710
                                break;
711
                            case 14: //i2c error
712
                                lblNCI2C.Invoke((Action)(() => lblNCI2C.Text = sAnalogData[index]));
713
                                break;
714
                            case 20: //Earthmagnet field
715
                                lblNCMF.Invoke((Action)(() => lblNCMF.Text = sAnalogData[index] + "%"));
716
                                break;
717
                            case 21: //GroundSpeed
718
                                lblNCGSpeed.Invoke((Action)(() => lblNCGSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
719
                                break;
720
                            case 28: //Distance East from saved home position -> calculate distance with distance N + height
721
                                dTemp = Math.Pow((double)iAnalogData[index], 2) + Math.Pow((double)iAnalogData[index - 1], 2);
722
                                dTemp = Math.Sqrt(dTemp) / (double)10; //'flat' distance from HP with N/E
723
                                                                       //  lblNCDist.Invoke((Action)(() => lblNCDist.Text = dTemp.ToString("0.00")));
724
                                dTemp = Math.Pow(dTemp, 2) + Math.Pow(((double)iAnalogData[4] / (double)10), 2); //adding 'height' into calculation
2254 - 725
                                dTemp = Math.Sqrt(dTemp) / (double)10;
726
                                lblNCDistHP.Invoke((Action)(() => lblNCDistHP.Text = dTemp.ToString("0.0 m")));
2250 - 727
                                break;
728
                            case 31: //Sats used
729
                                lblNCSat.Invoke((Action)(() => lblNCSat.Text = sAnalogData[index]));
730
                                break;
731
                        }
732
                    }
733
                    if (adr == 1) //FC
734
                    {
735
                        switch (index)
736
                        {
737
                            case 0: //pitch (German: nick)
738
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.pitch_angle = ((double)iAnalogData[index] / (double)10)));
739
                                lblNCPitch.Invoke((Action)(() => lblNCPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
740
                                break;
741
                            case 1: //roll
742
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.roll_angle = ((double)iAnalogData[index] / (double)10)));
743
                                lblNCRoll.Invoke((Action)(() => lblNCRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
744
                                break;
745
                            case 5: //altitude
746
                                lblNCAlt.Invoke((Action)(() => lblNCAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m")));
747
                                break;
748
                            case 8: //heading
749
                                lblNCCompass.Invoke((Action)(() => lblNCCompass.Text = sAnalogData[index] + "°"));
750
                                headingIndicator1.Invoke((Action)(() => headingIndicator1.SetHeadingIndicatorParameters(iAnalogData[index])));
751
                                break;
752
                            case 9: //Voltage
753
                                lblNCVolt.Invoke((Action)(() => lblNCVolt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 V")));
754
                                break;
755
                            case 10: //Receiver quality
756
                                lblNCRC.Invoke((Action)(() => lblNCRC.Text = sAnalogData[index]));
757
                                break;
758
                            case 22: // Current
759
                                lblNCCur.Invoke((Action)(() => lblNCCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A")));
760
                                break;
761
                            case 23: //capacity used
762
                                lblNCCap.Invoke((Action)(() => lblNCCap.Text = (iAnalogData[index]).ToString("0 mAh")));
763
                                break;
764
                            case 27: // SPI error
765
                                lblNCSPI.Invoke((Action)(() => lblNCSPI.Text = sAnalogData[index]));
766
                                break;
767
                            case 28: //i2c error
768
                                lblNCI2C.Invoke((Action)(() => lblNCI2C.Text = sAnalogData[index]));
769
                                break;
770
                        }
771
                    }
772
                    index++;
773
                }
774
            }
775
            else
776
                Debug.Print("wrong data-length (66): " + data.Length.ToString());
777
        }
778
        /// <summary>
779
        /// Version string 'V'
780
        /// </summary>
781
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
782
        /// <param name="data">the received byte array to process</param>
783
        void _processVersion(byte adr,byte[] data)
784
        {
785
            if (data.Length == 12)
786
            {
787
                if (!check_HWError)
788
                {
789
                    string[] sVersionStruct = new string[10] { "SWMajor: ", "SWMinor: ", "ProtoMajor: ", "LabelTextCRC: ", "SWPatch: ", "HardwareError 1: ", "HardwareError 2: ", "HWMajor: ", "BL_Firmware: ", "Flags: " };
790
                    string sVersion = "";
791
                    //sbyte[] signed = Array.ConvertAll(data, b => unchecked((sbyte)b));
792
                    Log(LogMsgType.Warning, (adr == 1 ? "FC-" : "NC-") + "Version: ");
793
                    sVersion = "HW V" + (data[7] / 10).ToString() + "." + (data[7] % 10).ToString();
794
                    Log(LogMsgType.Incoming, sVersion);
795
                    sVersion = "SW V" + (data[0]).ToString() + "." + (data[1]).ToString() + ((char)(data[4] + 'a')).ToString();
796
                    Log(LogMsgType.Incoming, sVersion);
797
                    Log(LogMsgType.Incoming, "BL-Firmware: V" + (data[8] / 100).ToString() + "." + (data[8] % 100).ToString());
798
                }
799
                if (data[5] > 0) //error0 
800
                {
801
                    if (adr == 1)
802
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[5].ToString() + ": " + ((FC_HWError0)data[5]).ToString());
803
                    if (adr == 2)
804
                        ErrorLog(LogMsgType.Error, "NC - HW-Error " + data[5].ToString() + ": " + ((NC_HWError0)data[5]).ToString());
805
                }
806
                if (data[6] > 0) //error1 
807
                {
808
                    if (adr == 1)
809
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[6].ToString() + ": " + ((FC_HWError1)data[6]).ToString());
810
                    if (adr == 2)
811
                        ErrorLog(LogMsgType.Error, "NC - Unknown HW-ERROR: " + data[6].ToString()); //@moment NC has only one error field
812
                }
2254 - 813
                if((data[5] + data[6] == 0) && _bErrorLog)
814
                    _clearErrorLog(adr==1 ? "FC - HW-Error" : "FC - HW-Error");
2250 - 815
 
816
            }
817
            check_HWError = false;
818
        }
819
        /// <summary>
820
        /// BL-Ctrl data 'K'
821
        /// for FC you have to use a customized firmware
822
        /// </summary>
823
        /// <param name="data">the received byte array to process</param>
824
        void _processBLCtrl(byte[] data)
825
        {
826
            if (data.Length % 6 == 0) //data.Length up to 96 (16 motors x 6 byte data) --> new datastruct in FC -> not standard!
827
            {
828
                bool bAvailable = false;
829
                for (int i = 0; i < data.Length && data[i] < 8; i += 6) // data[i] < 8 --> at moment there are 8 display fields for motors
830
                {
831
 
832
                    if ((data[i + 4] & 128) == 128) //Status bit at pos 7 = 128 dec -- if true, motor is available
833
                        bAvailable = true;
834
                    else
835
                        bAvailable = false;
836
 
837
                    if (data[i] < 4)
838
                    {
839
                        if (bAvailable)
840
                        {
841
                            dtMotors1.Rows[data[i]].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
842
                            dtMotors1.Rows[data[i]].SetField(2, data[i + 2].ToString("0 °C"));
843
                        }
844
                        else
845
                        {
846
                            dtMotors1.Rows[data[i]].SetField(1, "NA");
847
                            dtMotors1.Rows[data[i]].SetField(2, "NA");
848
                        }
849
                    }
850
                    if (data[i] > 3 && data[i] < 8)
851
                    {
852
                        if (bAvailable)
853
                        {
854
                            dtMotors2.Rows[data[i] - 4].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
855
                            dtMotors2.Rows[data[i] - 4].SetField(2, data[i + 2].ToString("0 °C"));
856
                        }
857
                        else
858
                        {
859
                            dtMotors2.Rows[data[i] - 4].SetField(1, "NA");
860
                            dtMotors2.Rows[data[i] - 4].SetField(2, "NA");
861
                        }
862
                    }
863
                }
864
            }
865
 
866
        }
867
        /// <summary>
868
        /// Navi-Ctrl data 'O'
869
        /// GPS-Position, capacatiy, flying time...
870
        /// </summary>
871
        /// <param name="data">the received byte array to process</param>
872
        void _processNCData(byte[] data)
873
        {
874
            int i_32, i_16, iVal;
875
            double d;
876
            i_32 = data[4];
877
            iVal = i_32 << 24;
878
            i_32 = data[3];
879
            iVal += i_32 << 16;
880
            i_32 = data[2];
881
            iVal += i_32 << 8;
882
            iVal += data[1];
883
            d = (double)iVal / Math.Pow(10, 7);
884
            lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = d.ToString("0.######°"))); //GPS-Position: Longitude in decimal degree
885
            //lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = _convertDegree(d))); //GPS-Position: Longitude in minutes, seconds
886
 
887
            i_32 = data[8];
888
            iVal = i_32 << 24;
889
            i_32 = data[7];
890
            iVal += i_32 << 16;
891
            i_32 = data[6];
892
            iVal += i_32 << 8;
893
            iVal += data[5];
894
            d = (double)iVal / Math.Pow(10, 7);
895
            lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = d.ToString("0.######°"))); //GPS-Position: Latitude in decimal degree
2254 - 896
                                                                                            //lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = _convertDegree(d))); //GPS-Position: Latitude in minutes, seconds
2250 - 897
 
2254 - 898
            i_16 = data[28];
899
            i_16 = (Int16)(i_16 << 8);
900
            iVal = data[27] + i_16;
901
            lblNCDistWP.Invoke((Action)(() => lblNCDistWP.Text = ((double)iVal/ (double)10).ToString("0.0 m"))); //Distance to next WP
902
 
903
            i_16 = data[45];
904
            i_16 = (Int16)(i_16 << 8);
905
            iVal = data[44] + i_16;
906
            lblNCDistHP1.Invoke((Action)(() => lblNCDistHP1.Text = ((double)iVal/ (double)10).ToString("0.0 m"))); //Distance to next WP
907
 
908
            lblNCWPIndex.Invoke((Action)(() => lblNCWPIndex.Text = data[48].ToString())); //Waypoint index
909
            lblNCWPCount.Invoke((Action)(() => lblNCWPCount.Text = data[49].ToString())); //Waypoints count
910
 
2250 - 911
            i_16 = data[81];
912
            i_16 = (Int16)(i_16 << 8);
913
            iVal = data[80] + i_16;
914
            lblNCCap.Invoke((Action)(() => lblNCCap.Text = iVal.ToString() + " mAh")); //Capacity used
915
 
916
            i_16 = data[56];
917
            i_16 = (Int16)(i_16 << 8);
918
            iVal = data[55] + i_16;
919
            TimeSpan t = TimeSpan.FromSeconds(iVal);
920
            string Text = t.Hours.ToString("D2") + ":" + t.Minutes.ToString("D2") + ":" + t.Seconds.ToString("D2");
921
            lblNCFlTime.Invoke((Action)(() => lblNCFlTime.Text = Text.ToString())); //Flying time
922
 
923
            lblNCRC.Invoke((Action)(() => lblNCRC.Text = data[66].ToString())); //RC quality
924
            lblNCErrNmbr.Invoke((Action)(() => lblNCErrNmbr.Text = data[69].ToString()));   //NC Errornumber
925
            //if (data[69] > 0)
926
            //    _readNCError();
927
            //break;
928
            if (data[69] > 0 & data[69] < 44)
929
                ErrorLog(LogMsgType.Error, "NC Error [" + data[69].ToString() + "]: " + NC_Error[data[69]]);
2254 - 930
            else
931
                if(_bErrorLog) _clearErrorLog("NC Error");
2250 - 932
 
933
        }
934
        /// <summary>
2257 - 935
        /// Navi-Ctrl WP data struct 'X'
936
        /// called by index
937
        /// </summary>
938
        /// <param name="data">the received byte array to process</param>
939
        void _processWPData(byte[] data)
940
        {
941
            if (data.Length >= 28)
942
            {
943
                int count = data[0];
944
                int index = data[1];
945
                cbWPIndex.Invoke((Action)(() => cbWPIndex.Items.Clear()));
946
                for (int i = 0; i < count; i++)
947
                    cbWPIndex.Invoke((Action)(() => cbWPIndex.Items.Add(i + 1)));
948
                cbWPIndex.Invoke((Action)(() => cbWPIndex.SelectedItem = index));
949
                DataRow dr = dtWaypoints.NewRow();
950
                dr = Waypoints.toDataRow(data, dr);
951
                dtWaypoints.Rows.Add(dr);
952
                dgvWP.Invoke((Action)(() => dgvWP.Update()));
953
            }
954
            else
955
                Debug.Print(new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length)));
956
        }
957
        /// <summary>
2250 - 958
        /// OSD Menue 'L'
959
        /// single page called by pagenumber
960
        /// no autoupdate
961
        /// </summary>
962
        /// <param name="data">the received byte array to process</param>
963
        void _processOSDSingle(byte[] data)
964
        {
965
            if (data.Length == 84)
966
            {
967
                string sMessage = "";
968
                iOSDPage = data[0];
969
                iOSDMax = data[1];
970
                if (cbOSD.Items.Count != iOSDMax) _initOSDCB();
971
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 2, data.Length - 4));
972
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20));
973
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20));
974
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20));
975
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20));
976
                lblOSDPageNr.Invoke((Action)(() => lblOSDPageNr.Text = iOSDPage.ToString("[0]")));
977
 
978
            }
979
            else
980
                OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 84)");
981
 
982
        }
983
        /// <summary>
984
        /// OSD Menue 'H'
985
        /// called by keys (0x01,0x02,0x03,0x04)
986
        /// autoupdate
987
        /// </summary>
988
        /// <param name="data">the received byte array to process</param>
989
        void _processOSDAuto(byte[] data)
990
        {
991
            if (data.Length == 81)
992
            {
993
                string sMessage = "";
994
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length - 1));
995
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20));
996
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20));
997
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20));
998
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20));
999
 
1000
            }
1001
            else
1002
                OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 81)");
1003
        }
1004
        #endregion processing received data
1005
 
2233 - 1006
        /// <summary> send message to controller to request data
1007
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
1008
        /// </summary>
1009
        /// <param name="CMDID"> the command ID </param>
1010
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
1011
        private void _sendControllerMessage(char CMDID, byte address)
1012
        {
1013
            if (simpleSerialPort.Port.IsOpen)
1014
            {
1015
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1016
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address);
1017
                serialStream.Write(bytes, 0, bytes.Length);
1018
 
1019
            }
1020
            else
1021
                Log(LogMsgType.Error, "NOT CONNECTED!");
1022
        }
1023
        /// <summary> send message to controller to request data
1024
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
1025
        /// </summary>
1026
        /// <param name="CMDID"> the command ID </param>
1027
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
1028
        /// <param name="data"> additional data for the request</param>
1029
        private void _sendControllerMessage(char CMDID, byte address, byte[]data)
1030
        {
1031
            if (simpleSerialPort.Port.IsOpen)
1032
            {
1033
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1034
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address,data);
1035
                serialStream.Write(bytes, 0, bytes.Length);
1036
 
1037
            }
1038
            else
1039
                Log(LogMsgType.Error, "NOT CONNECTED!");
1040
        }
1041
 
1042
        /// <summary>
1043
        /// read the analog-label names for the actual controller
1044
        /// and load it into listbox
1045
        /// </summary>
1046
        void _loadLabelNames()
1047
        {
1048
            if (_iCtrlAct > 0 && _iCtrlAct < 3)
1049
            {
1050
                switch (_iCtrlAct)
1051
                {
1052
                    case 1:
1053
                        sAnalogLabel = Properties.Resources.FCLabelTexts.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
1054
                        break;
1055
                    case 2:
1056
                        sAnalogLabel = Properties.Resources.NCLabelTexts.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
1057
                        break;
1058
                }
1059
                for (int i = 0; i < 32; i++)
1060
                {
1061
                    if (dtAnalog.Rows.Count < 32)
1062
                        dtAnalog.Rows.Add(sAnalogLabel[i], "");
1063
                    else
1064
                        dtAnalog.Rows[i].SetField(0, sAnalogLabel[i]);
1065
                }
1066
                dataGridView1.Invoke((Action)(()=>dataGridView1.Refresh()));
1067
            }
1068
        }
1069
        /// <summary>
1070
        /// no longer used...
1071
        /// read the analog-label textfile for the actual controller
1072
        /// </summary>
1073
         private void _loadLabelFile()
1074
        {
1075
            switch (_iCtrlAct)
1076
            {
1077
                case 1:
1078
                    fileName = "FCLabelTexts.txt";
1079
                    break;
1080
                case 2:
1081
                    fileName = "NCLabelTexts.txt";
1082
                    break;
1083
                //default:
1084
                //    fileName = "NCLabelTexts.txt";
1085
                //    break;
1086
            }
1087
 
1088
            if (File.Exists(filePath + "\\" + fileName))
1089
            {
1090
                sAnalogLabel.Initialize();
1091
                sAnalogLabel = File.ReadAllLines(filePath + "\\" + fileName);
1092
                lbLabels.Invoke((Action)(() => lbLabels.Items.Clear()));
1093
                lbLabels.Invoke((Action)(() => lbLabels.Update()));
1094
                lbLabels.Invoke((Action)(() => lbLabels.Items.AddRange(sAnalogLabel)));
1095
                Console.WriteLine("Names loaded from file");
1096
                lblFileName.Invoke((Action)(() => lblFileName.Text = fileName));
1097
            }
1098
            else
1099
            {
1100
                _readCont(false);
1101
                Log(LogMsgType.Error, "Label-file not found!");
1102
                Log(LogMsgType.Error, "Please go to settings-tab and load the label texts from the copter control (FC & NC)");
1103
                Log(LogMsgType.Error, "When done, you have to save the label texts with the 'save' button!");
1104
            }
1105
        }
1106
        /// <summary>
1107
        /// no longer used...
1108
        /// assign the analog-label names from the textfile to the datatable
1109
        /// 
1110
        /// </summary>
1111
        private void _assignLabelNames()
1112
        {
1113
            if (lbLabels.Items.Count == 32)
1114
            {
1115
                lbLabels.Items.CopyTo(sAnalogLabel, 0);
1116
                for (int i = 0; i < 32; i++)
1117
                {
1118
                    if (dtAnalog.Rows.Count < 32)
1119
                        dtAnalog.Rows.Add(sAnalogLabel[i], "");
1120
                    else
1121
                        dtAnalog.Rows[i].SetField(0, sAnalogLabel[i]);
1122
 
1123
                }
1124
            }
1125
        }
1126
        /// <summary>
1127
        /// get the version struct of actual controller
1128
        /// </summary>
1129
        /// <summary>
1130
        /// get the labeltexts for the analog values
1131
        /// </summary>
1132
        private void _getAnalogLabels()
1133
        {
1134
            if (simpleSerialPort.Port.IsOpen)
1135
            {
1136
                iLableIndex = 0;
1137
                for (int i = 0; i < 32; i++)
1138
                {
1139
                    Stream serialStream = simpleSerialPort.Port.BaseStream;
1140
                    byte[] bytes = FlightControllerMessage.CreateMessage('a', 0, new byte[1] { (byte)i });
1141
                    serialStream.Write(bytes, 0, bytes.Length);
1142
                    Thread.Sleep(10);
1143
                }
1144
            }
1145
            else
1146
                Log(LogMsgType.Error, "NOT CONNECTED!");
1147
        }
1148
        /// <summary>
1149
        /// get the labeltext for a single label
1150
        /// </summary>
1151
        /// <param name="iIndex">index of the label</param>
1152
        private void _getAnalogLabels(int iIndex)
1153
        {
1154
            if (simpleSerialPort.Port.IsOpen)
1155
            {
1156
                if (iIndex < 32)
1157
                {
1158
                    iLableIndex = iIndex;
1159
                    _sendControllerMessage('a', 0, new byte[1] { (byte)iLableIndex });
1160
                }
1161
            }
1162
            else
1163
                Log(LogMsgType.Error, "NOT CONNECTED!");
1164
        }
1165
        private void _getVersion()
1166
        {
1167
            _sendControllerMessage('v', 0);
1168
        }
1169
        /// <summary>
1170
        /// get FC version struct via NC
1171
        /// by sending '1' as data (not documented in wiki...)
1172
        /// returns HW error 255 (comment in uart1.c : tells the KopterTool that it is the FC-version)
1173
        /// </summary>
1174
        /// <param name="ctrl">controller number 1=FC</param> 
1175
        private void _getVersion(byte ctrl)
1176
        {
1177
            _sendControllerMessage('v', 0, new byte[1] {ctrl});
1178
        }
1179
        /// <summary>
1180
        /// Switch back to NC by sending the 'Magic Packet' 0x1B,0x1B,0x55,0xAA,0x00
1181
        /// </summary>
1182
        private void _switchToNC()
1183
        {
1184
            if (simpleSerialPort.Port.IsOpen)
1185
            {
1186
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1187
                byte[] bytes = new byte[5] { 0x1B,0x1B,0x55,0xAA,0x00 };
1188
                serialStream.Write(bytes, 0, bytes.Length);
1189
 
1190
                Thread.Sleep(100);
1191
                _getVersion();
1192
                Thread.Sleep(100);
1193
                _OSDMenue(0);
1194
            }
1195
            else
1196
                Log(LogMsgType.Error, "NOT CONNECTED!");
1197
        }
1198
        /// <summary>
1199
        /// switch to FC
1200
        /// </summary>
1201
        private void _switchToFC()
1202
        {
1203
            _sendControllerMessage('u', 2, new byte[1] { (byte)0 });
1204
            Thread.Sleep(100);
1205
            _getVersion();
1206
            Thread.Sleep(100);
1207
            _OSDMenue(0);
1208
        }
1209
        /// <summary>
1210
        /// send RESET signal to FC
1211
        /// </summary>
1212
        private void _resetCtrl()
1213
        {
1214
            _sendControllerMessage('R', 1);
1215
        }
1216
        /// <summary>
1217
        /// poll the debug data (4sec subscription)
1218
        /// </summary>
1219
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1220
        private void _readDebugData(bool auto)
1221
        {
1222
            byte interval = auto ? debugInterval : (byte)0;
1223
            _sendControllerMessage('d', 0, new byte[1] { debugInterval });
1224
        }
1225
        /// <summary>
1226
        /// poll the BL-CTRL status via NC (4sec subscription)
1227
        /// </summary>
1228
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1229
        private void _readBLCtrl(bool auto)
1230
        {
1231
            byte interval = auto ? blctrlInterval : (byte)0;
1232
            _sendControllerMessage('k', 0, new byte[1] { interval });
1233
        }
1234
        /// <summary>
1235
        /// poll the NC data struct (4sec subscription)
1236
        /// </summary>
1237
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1238
        private void _readNavData(bool auto)
1239
        {
1240
            byte interval = auto ? navctrlInterval : (byte)0;
1241
            _sendControllerMessage('o', 2, new byte[1] { interval });
1242
        }
1243
        /// <summary>
1244
        /// get the errortext for pending NC error
1245
        /// </summary>
1246
        private void _readNCError()
1247
        {
1248
            _sendControllerMessage('e', 2);
1249
        }
1250
        /// <summary>
1251
        /// start/stop continous polling of controller values
1252
        /// </summary>
1253
        /// <param name="b">start/stop switch</param>
1254
        void _readCont(bool b)
1255
        {
1256
            bReadContinously = b;
2274 - 1257
 
1258
            if (Thread.CurrentThread.CurrentUICulture.Name == "")
1259
                btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.Text = bReadContinously ? "stop automatic" + Environment.NewLine + "data refresh" : "start automatic" + Environment.NewLine + "data refresh"));
1260
            else
1261
                btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.Text = bReadContinously ? "Aktualisierung" + Environment.NewLine + "beenden" : "Aktualisierung" + Environment.NewLine + "starten"));
2233 - 1262
            btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.BackColor = bReadContinously ? Color.FromArgb(192, 255, 192) : Color.FromArgb(224, 224, 224)));
1263
            if (bReadContinously)
1264
            {
2250 - 1265
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
1266
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
1267
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
1268
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); Thread.Sleep(10);}
2233 - 1269
                lblLifeCounter.Invoke((Action)(() => lblLifeCounter.BackColor = Color.FromArgb(0, 224, 0)));
1270
            }
1271
            else
1272
                lblLifeCounter.Invoke((Action)(() => lblLifeCounter.BackColor = Color.FromArgb(224, 224, 224)));
1273
            _iLifeCounter = 0;
1274
        }
1275
        /// <summary>
2250 - 1276
        /// set values to "NA" when not available with FC
2233 - 1277
        /// </summary>
1278
        void _setFieldsNA()
1279
        {
1280
            Thread.Sleep(100);
2250 - 1281
            _initDTMotors();
2233 - 1282
            lblNCFlTime.Invoke((Action)(() => lblNCFlTime.Text = "NA"));    //FlightTime
2250 - 1283
            lblNCErrNmbr.Invoke((Action)(() => lblNCErrNmbr.Text = "NA"));  //NC ErrorNr
1284
            lblNCMF.Invoke((Action)(() => lblNCMF.Text = "NA"));            //earth magnet field
1285
            lblNCGSpeed.Invoke((Action)(() => lblNCGSpeed.Text = "NA"));    //GroundSpeed
1286
            lblNCDistHP.Invoke((Action)(() => lblNCDistHP.Text = "NA"));    //Distance to HP
1287
            lblNCSat.Invoke((Action)(() => lblNCSat.Text = "NA"));          //Sats used
1288
            lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = "NA"));  //GPS position - longitude
1289
            lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = "NA"));    //GPS position - latitude
2254 - 1290
            lblNCDistWP.Invoke((Action)(() => lblNCDistWP.Text = "NA"));    //next WP distance
1291
            lblNCWPIndex.Invoke((Action)(() => lblNCWPIndex.Text = "NA"));  //index of actual WP
1292
            lblNCWPCount.Invoke((Action)(() => lblNCWPCount.Text = "NA"));  //count of items in WP list
2233 - 1293
        }
1294
        /// <summary>
1295
        /// one time query of the OSD Menue with pagenumber
1296
        /// </summary>
1297
        /// <param name="iMenue">Menue page</param>
1298
        void _OSDMenue(int iMenue)
1299
        {
1300
            if (simpleSerialPort.Port.IsOpen)
1301
            {
1302
                if (iMenue > iOSDMax)
1303
                    iMenue = 0;
1304
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1305
                byte[] bytes = FlightControllerMessage.CreateMessage('l', 0, new byte[1] { (byte)iMenue });
1306
                serialStream.Write(bytes, 0, bytes.Length);
1307
            }
1308
            else
1309
                Log(LogMsgType.Error, "NOT CONNECTED!");
1310
 
1311
        }
1312
        /// <summary>
1313
        /// call the OSDMenue and start autorefresh
1314
        ///  usually by sending a menuekey
1315
        /// 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)
1316
        /// therefore the value has to be negative (inverted) in order to distinguish from old (2 line) menuestyle
1317
        /// and must not have any bits of the menue keys 0x1 0x2 0x4 0x8 (0x10?) --> 0x20 = -33
1318
        /// </summary>
1319
        void _OSDMenueAutoRefresh()
1320
        {
1321
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)(-33)),OSDInterval });
1322
        }
1323
        void _OSDMenueAutoRefresh(byte key)
1324
        {
1325
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)~key), OSDInterval });
1326
        }
1327
        /// <summary>
1328
        /// initialize the OSD menue combobox
1329
        /// combox is filled by numbers from 0 to max pagenumber
1330
        /// </summary>
1331
        void _initOSDCB()
1332
        {
1333
            _bCBInit = true;
1334
            if(iOSDMax == 0)
1335
            {
1336
                _OSDMenue(0);
1337
                Thread.Sleep(10);
1338
            }
1339
            cbOSD.Invoke((Action)(()=>cbOSD.Items.Clear()));
1340
            for(int i = 0; i <= iOSDMax;i++)
1341
            {
1342
                cbOSD.Invoke((Action)(() => cbOSD.Items.Add(i)));
1343
            }
1344
            cbOSD.Invoke((Action)(() => cbOSD.SelectedItem = iOSDPage));
1345
            _bCBInit = false;
1346
        }
2259 - 1347
        /// <summary>
1348
        /// initialize the datatables
1349
        /// with columnnames etc
1350
        /// </summary>
1351
        void _dataTablesInit()
1352
        {
1353
            dtAnalog.Columns.Add("ID");
1354
            dtAnalog.Columns.Add("Value");
1355
            dataGridView1.DataSource = dtAnalog;
1356
 
1357
            dtMotors1.Columns.Add("#");
2274 - 1358
            if (Thread.CurrentThread.CurrentUICulture.Name == "")
1359
                dtMotors1.Columns.Add("Current");
1360
            else
1361
                dtMotors1.Columns.Add("Strom");
2259 - 1362
            dtMotors1.Columns.Add("Temp");
1363
            dtMotors2.Columns.Add("#");
2274 - 1364
            if (Thread.CurrentThread.CurrentUICulture.Name == "")
1365
                dtMotors2.Columns.Add("Current");
1366
            else
1367
                dtMotors2.Columns.Add("Strom");
2259 - 1368
            dtMotors2.Columns.Add("Temp");
1369
            dgvMotors1.DataSource = dtMotors1;
1370
            dgvMotors2.DataSource = dtMotors2;
1371
            _initDTMotors();
1372
            dgvMotors1.Columns[0].Width = 24;
1373
            dgvMotors1.Columns[1].Width = 74;
1374
            dgvMotors1.Columns[2].Width = 74;
1375
            dgvMotors2.Columns[0].Width = 24;
1376
            dgvMotors2.Columns[1].Width = 74;
1377
            dgvMotors2.Columns[2].Width = 74;
1378
 
1379
            dtWaypoints.Columns.Add("Index");
1380
            dtWaypoints.Columns.Add("Type");
1381
            dtWaypoints.Columns.Add("Name");
1382
            dtWaypoints.Columns.Add("Latitude");
1383
            dtWaypoints.Columns.Add("Longitude");
1384
            dtWaypoints.Columns.Add("Altitude");
1385
            dtWaypoints.Columns.Add("Heading");
1386
            dtWaypoints.Columns.Add("Speed");
1387
            dtWaypoints.Columns.Add("Altitude rate");
1388
            dtWaypoints.Columns.Add("Tol.radius");
1389
            dtWaypoints.Columns.Add("Hold time");
1390
            dtWaypoints.Columns.Add("AutoTrigger");
1391
            dtWaypoints.Columns.Add("Cam angle");
1392
            dtWaypoints.Columns.Add("Event");
1393
            dtWaypoints.Columns.Add("Eventchan. Val.");
1394
            dtWaypoints.Columns.Add("Status");
1395
            dgvWP.DataSource = dtWaypoints;
1396
        }
1397
        /// <summary>
1398
        /// read settings from ini-file
1399
        /// </summary>
2233 - 1400
        void _readIni()
1401
        {
1402
            if (!File.Exists(filePath + "\\MKLiveViewSettings.ini"))
1403
                _writeIni();
1404
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
1405
            ini.path = filePath + "\\MKLiveViewSettings.ini";
1406
 
1407
            string sVal = ini.IniReadValue("default", "AutorefreshDebugData");
1408
            _debugDataAutorefresh = Convert.ToBoolean(sVal);
1409
            sVal = ini.IniReadValue("default", "AutorefreshNavCtrlData");
1410
            _navCtrlDataAutorefresh = Convert.ToBoolean(sVal);
1411
            sVal = ini.IniReadValue("default", "AutorefreshBLCtrlData");
1412
            _blctrlDataAutorefresh = Convert.ToBoolean(sVal);
1413
            sVal = ini.IniReadValue("default", "AutorefreshOSDData");
1414
            _OSDAutorefresh = Convert.ToBoolean(sVal);
1415
 
1416
            sVal = ini.IniReadValue("default", "IntervalDebugData");
1417
            debugInterval = (byte)Convert.ToInt16(sVal);
1418
            sVal = ini.IniReadValue("default", "IntervalNavCtrlData");
1419
            navctrlInterval = (byte)Convert.ToInt16(sVal);
1420
            sVal = ini.IniReadValue("default", "IntervalBLCtrlData");
1421
            blctrlInterval = (byte)Convert.ToInt16(sVal);
1422
            sVal = ini.IniReadValue("default", "IntervalOSDData");
1423
            OSDInterval = (byte)Convert.ToInt16(sVal);
2257 - 1424
            for(int i = 0; i < 12; i++)
1425
            {
1426
                sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "Val");
1427
                if(sVal != "")
1428
                    serChan[i] = Convert.ToInt16(sVal);
1429
                sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "Title");
1430
                if(sVal != "")
1431
                    serChanTitle[i] = sVal;
1432
            }
2233 - 1433
        }
2259 - 1434
        /// <summary>
1435
        /// save settings to ini-file
1436
        /// </summary>
2233 - 1437
        void _writeIni()
1438
        {
1439
 
1440
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
1441
            ini.path = filePath + "\\MKLiveViewSettings.ini";
1442
 
1443
            ini.IniWriteValue("default", "AutorefreshDebugData", _debugDataAutorefresh ? "true":"false");
1444
            ini.IniWriteValue("default", "AutorefreshNavCtrlData", _navCtrlDataAutorefresh ? "true":"false");
1445
            ini.IniWriteValue("default", "AutorefreshBLCtrlData", _blctrlDataAutorefresh ? "true":"false");
1446
            ini.IniWriteValue("default", "AutorefreshOSDData", _OSDAutorefresh ? "true":"false");
1447
 
1448
            ini.IniWriteValue("default", "IntervalDebugData", debugInterval.ToString());
1449
            ini.IniWriteValue("default", "IntervalNavCtrlData", navctrlInterval.ToString());
1450
            ini.IniWriteValue("default", "IntervalBLCtrlData", blctrlInterval.ToString());
1451
            ini.IniWriteValue("default", "IntervalOSDData", OSDInterval.ToString());
2257 - 1452
 
1453
            for (int i = 0; i < 12; i++)
1454
            {
1455
                ini.IniWriteValue("serial", "ch" + i.ToString() + "Val", serChan[i].ToString());
1456
                ini.IniWriteValue("serial", "ch" + i.ToString() + "Title", serChanTitle[i]);
1457
            }
1458
 
2233 - 1459
        }
1460
 
2250 - 1461
        /// <summary>
1462
        /// initialize the 2 datatables for motor values
1463
        /// dtMotors1 - motor 1 - 4
1464
        /// dtMotors2 - motor 5 - 8
1465
        /// DataGridView dgvMotors1/2 are bound to dtMotors1/2 
1466
        /// </summary>
1467
        void _initDTMotors()
1468
        {
1469
            for(int i = 0; i < 4; i++)
1470
            {
1471
                if (dtMotors1.Rows.Count < 4)
1472
                    dtMotors1.Rows.Add((i + 1).ToString(), "NA", "NA");
1473
                else
1474
                {
1475
                    dtMotors1.Rows[i].SetField(1, "NA");
1476
                    dtMotors1.Rows[i].SetField(2, "NA");
1477
                }
1478
                if (dtMotors2.Rows.Count < 4)
1479
                    dtMotors2.Rows.Add((i + 5).ToString(), "NA", "NA");
1480
                else
1481
                {
1482
                    dtMotors2.Rows[i].SetField(1, "NA");
1483
                    dtMotors2.Rows[i].SetField(2, "NA");
1484
                }
1485
            }
1486
            dgvMotors1.Invoke((Action)(() => dgvMotors1.Refresh()));
1487
            dgvMotors2.Invoke((Action)(() => dgvMotors2.Refresh()));
1488
        }
1489
 
1490
        /// <summary>
1491
        /// Convert decimal degrees to degrees, minutes, seconds, milliseconds 
1492
        /// </summary>
1493
        /// <param name="coord">the degree value as double</param>
1494
        /// <returns>0° 0' 0,0"</returns>
1495
        string _convertDegree(double coord)
1496
        {
1497
            //double minutes = (degree - Math.Floor(degree)) * 60.0;
1498
            //double seconds = (minutes - Math.Floor(minutes)) * 60.0;
1499
            //double tenths = (seconds - Math.Floor(seconds)) * 10.0;
1500
            //// get rid of fractional part
1501
            //minutes = Math.Floor(minutes);
1502
            //seconds = Math.Floor(seconds);
1503
            //tenths = Math.Floor(tenths);
1504
 
1505
 
1506
            //int sec = (int)Math.Round(coord * 3600);
1507
            //int deg = sec / 3600;
1508
            //sec = Math.Abs(sec % 3600);
1509
            //int min = sec / 60;
1510
            //sec %= 60;
1511
 
1512
            var ts = TimeSpan.FromHours(Math.Abs(coord));
1513
            double deg = Math.Sign(coord) * Math.Floor(ts.TotalHours);
1514
            int min = ts.Minutes;
1515
            int sec = ts.Seconds;
1516
            int milli = ts.Milliseconds;
1517
 
1518
            return deg.ToString("0° ") + min.ToString("0") + "' " + sec.ToString("0") + "," + milli.ToString() + "\"";
1519
        }
2257 - 1520
        /// <summary>
1521
        /// Clear the line in the  errorlog window 
1522
        /// containing the error string when error has ceased
1523
        /// </summary>
1524
        /// <param name="s">substring of errrormessage</param>
2254 - 1525
        void _clearErrorLog(string s)
1526
        {
1527
            rtfError.Invoke((Action)(() =>
1528
            {
1529
                if (rtfError.Text.Contains(s))
1530
                {
1531
                    int iLength = 0;
1532
                    int iStart = rtfError.Text.IndexOf(s);
1533
                    int iEnd = rtfError.Text.IndexOf('\n', iStart);
1534
                    if (iEnd > 0)
1535
                    {
1536
                        iLength = iEnd + 1;
1537
                        int iHttp = rtfError.Text.IndexOf("http", iEnd);
1538
                        if (iHttp == iLength)
1539
                        {
1540
                            int iEnd2 = rtfError.Text.IndexOf('\n', iLength);
1541
                            if (iEnd2 > iLength)
1542
                            {
1543
                                iLength = iEnd2 + 1;
1544
                                rtfError.Select(iStart, iLength);
1545
                                rtfError.SelectedText = string.Empty;
1546
                                if(rtfError.Text.Length < 2) _bErrorLog = false;
1547
                            }
1548
 
1549
                        }
1550
                        else
1551
                        {
1552
                            rtfError.Select(iStart, iLength);
1553
                            rtfError.SelectedText = string.Empty;
1554
                            if(rtfError.Text.Length < 2) _bErrorLog = false;
1555
                        }
1556
                    }
1557
                }
1558
            }));
1559
 
1560
        }
2257 - 1561
        /// <summary>
1562
        /// request the Waypoint at index
1563
        /// </summary>
1564
        /// <param name="index"></param>
1565
        void _getpWP(int index)
1566
        {
1567
            if (simpleSerialPort.Port.IsOpen)
1568
            {
1569
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1570
                byte[] bytes = FlightControllerMessage.CreateMessage('x', 2, new byte[1] { (byte)index });
1571
                serialStream.Write(bytes, 0, bytes.Length);
1572
            }
1573
            else
1574
                Log(LogMsgType.Error, "NOT CONNECTED!");
1575
 
1576
        }
1577
        /// <summary>
1578
        /// Sending the serial channel values
1579
        /// </summary>
1580
        void _sendSerialData()
1581
        {
1582
            byte[] serData = new byte[12];
1583
            for(int i = 0; i < 12; i++)
1584
            {
1585
                serData[i] = unchecked((byte)(serChan[i] - 127));
1586
            }
1587
            _sendControllerMessage('y', 1, serData);
1588
        }
2259 - 1589
        /// <summary>
1590
        /// init the controls for displaying
1591
        /// and setting serial control channels
1592
        /// </summary>
2257 - 1593
        void _initSerialCtrl()
1594
        {
1595
            trckbarSerial1.Value = serChan[0];
1596
            textBoxSerial1.Text = serChanTitle[0];
1597
            lblTbSerial1.Text = serChan[0].ToString();
1598
            trckbarSerial2.Value = serChan[1];
1599
            textBoxSerial2.Text = serChanTitle[1];
1600
            lblTbSerial2.Text = serChan[1].ToString();
2259 - 1601
            trckbarSerial3.Value = serChan[2];
1602
            textBoxSerial3.Text = serChanTitle[2];
1603
            lblTbSerial3.Text = serChan[2].ToString();
1604
            trckbarSerial4.Value = serChan[3];
1605
            textBoxSerial4.Text = serChanTitle[3];
1606
            lblTbSerial4.Text = serChan[3].ToString();
2265 - 1607
            trckbarSerial5.Value = serChan[4];
1608
            textBoxSerial5.Text = serChanTitle[4];
1609
            lblTbSerial5.Text = serChan[4].ToString();
1610
            trckbarSerial6.Value = serChan[5];
1611
            textBoxSerial6.Text = serChanTitle[5];
1612
            lblTbSerial6.Text = serChan[5].ToString();
1613
            trckbarSerial7.Value = serChan[6];
1614
            textBoxSerial7.Text = serChanTitle[6];
1615
            lblTbSerial7.Text = serChan[6].ToString();
1616
            trckbarSerial8.Value = serChan[7];
1617
            textBoxSerial8.Text = serChanTitle[7];
1618
            lblTbSerial8.Text = serChan[7].ToString();
2257 - 1619
        }
2233 - 1620
        #endregion functions
1621
 
1622
        #region buttons
1623
        private void buttonReset_Click(object sender, EventArgs e)
1624
        {
1625
            _resetCtrl();
1626
        }
1627
        private void btnVersion_Click(object sender, EventArgs e)
1628
        {
1629
            _getVersion();
1630
        }
1631
        private void btnAnalogLabels_Click(object sender, EventArgs e)
1632
        {
1633
            _getAnalogLabels(0);
1634
        }
1635
        private void btnDbgData_Click(object sender, EventArgs e)
1636
        {
1637
            _readDebugData(false); //onetime reading of debug data --> subscription lasts 4sec - this means you will receive data for 4 seconds
1638
        }
1639
        private void btnSaveLabels_Click(object sender, EventArgs e)
1640
        {
1641
            switch (_iCtrlAct)
1642
            {
1643
                case 1:
1644
                    fileName = "FCLabelTexts.txt";
1645
                    break;
1646
                case 2:
1647
                    fileName = "NCLabelTexts.txt";
1648
                    break;
1649
                default:
1650
                    fileName = "NCLabelTexts.txt";
1651
                    break;
1652
            }
1653
            if (sAnalogLabel[0] != null)
1654
            {
1655
                File.WriteAllLines(filePath + "\\" + fileName, sAnalogLabel);
1656
                Console.WriteLine("Names saved to file");
1657
                _loadLabelFile();
1658
            }
1659
            else
1660
                Log(LogMsgType.Warning, "there's no data -> read first from fc/nc!");
1661
        }
1662
        private void btnLoadLabels_Click(object sender, EventArgs e)
1663
        {
1664
            _assignLabelNames();
1665
        }
1666
        private void btnReadLabelFile_Click(object sender, EventArgs e)
1667
        {
1668
            _loadLabelFile();
1669
        }
1670
        private void btnSwitchFC_Click(object sender, EventArgs e)
1671
        {
1672
            _switchToFC();
1673
        }
1674
        private void btnSwitchNC_Click(object sender, EventArgs e)
1675
        {
1676
            _switchToNC();
1677
        }
1678
        private void btnReadDbgCont_Click(object sender, EventArgs e)
1679
        {
1680
            _readCont(!bReadContinously);
1681
        }
1682
        private void btnReadBLCtrl_Click(object sender, EventArgs e)
1683
        {
1684
 
1685
            if (_iCtrlAct == 2) _readBLCtrl(false);
1686
            else Log(LogMsgType.Warning, "only available when connected to NC");
1687
        }
1688
        private void btnGetNaviData_Click(object sender, EventArgs e)
1689
        {
1690
            if (_iCtrlAct == 2) _readNavData(false);
1691
            else Log(LogMsgType.Warning, "only available when connected to NC");
1692
        }
1693
        private void btnConn_Click(object sender, EventArgs e)
1694
        {
1695
            simpleSerialPort.Connect(!simpleSerialPort.Port.IsOpen);
1696
        }
1697
        private void button3_Click(object sender, EventArgs e)
1698
        {
1699
            _getVersion(1);
1700
        }
1701
        private void button4_Click(object sender, EventArgs e)
1702
        {
1703
            _getVersion(2);
1704
        }
1705
        private void btnOSD_Click(object sender, EventArgs e)
1706
        {
1707
            if (iOSDPage > iOSDMax)
1708
                iOSDPage = 0;
1709
            _OSDMenue(iOSDPage);
1710
        }
1711
        private void btnOSDForward_Click(object sender, EventArgs e)
1712
        {
1713
            iOSDPage++;
1714
            if (iOSDPage > iOSDMax)
1715
                iOSDPage = 0;
1716
 
1717
            _OSDMenue(iOSDPage);
1718
        }
1719
        private void btnOSDBackward_Click(object sender, EventArgs e)
1720
        {
1721
            iOSDPage--;
1722
            if (iOSDPage < 0)
1723
                iOSDPage = iOSDMax;
1724
 
1725
            _OSDMenue(iOSDPage);
1726
        }
1727
        private void btnOSDAuto_Click(object sender, EventArgs e)
1728
        {
1729
            _OSDMenueAutoRefresh();
1730
        }
1731
        /// call the OSDMenue with Key 0x8
1732
        private void btnOSDLeave_Click(object sender, EventArgs e)
1733
        {
1734
            _OSDMenueAutoRefresh(8);
1735
        }
1736
        /// call the OSDMenue with Key 0x4
1737
        private void btnOSDEnter_Click(object sender, EventArgs e)
1738
        {
1739
            _OSDMenueAutoRefresh(4);
1740
        }
2257 - 1741
        private void btnGetWP_Click(object sender, EventArgs e)
1742
        {
1743
            if(cbWPIndex.Items.Count >0)
1744
            _getpWP((int)cbWPIndex.SelectedItem);
1745
            else
1746
                _getpWP(1);
1747
        }
2233 - 1748
        #endregion buttons
2259 - 1749
        #region serial control channels - buttons & events
2257 - 1750
        private void tbSerial1_Scroll(object sender, EventArgs e)
1751
        {
1752
            lblTbSerial1.Text = trckbarSerial1.Value.ToString();
1753
            serChan[0] = trckbarSerial1.Value;
1754
            if (!_init) _sendSerialData();
1755
        }
1756
        private void textBoxSerial1_TextChanged(object sender, EventArgs e)
1757
        {
1758
            serChanTitle[0] = textBoxSerial1.Text;
1759
        }
1760
        private void btnSer1_0_Click(object sender, EventArgs e)
1761
        {
1762
            trckbarSerial1.Value = 0;
1763
        }
1764
        private void btnSer1_127_Click(object sender, EventArgs e)
1765
        {
1766
            trckbarSerial1.Value = 127;
1767
        }
1768
        private void btnSer1_254_Click(object sender, EventArgs e)
1769
        {
1770
            trckbarSerial1.Value = 254;
1771
        }
1772
        private void trckbarSerial1_ValueChanged(object sender, EventArgs e)
1773
        {
1774
            lblTbSerial1.Text = trckbarSerial1.Value.ToString();
1775
            serChan[0] = trckbarSerial1.Value;
1776
            if (!_init) _sendSerialData();
1777
        }
1778
        private void textBoxSerial2_TextChanged(object sender, EventArgs e)
1779
        {
2259 - 1780
            serChanTitle[1] = textBoxSerial2.Text;
2257 - 1781
        }
1782
        private void trckbarSerial2_ValueChanged(object sender, EventArgs e)
1783
        {
1784
            lblTbSerial2.Text = trckbarSerial2.Value.ToString();
1785
            serChan[1] = trckbarSerial2.Value;
1786
            if (!_init) _sendSerialData();
1787
        }
1788
        private void btnSer2_0_Click(object sender, EventArgs e)
1789
        {
1790
            trckbarSerial2.Value = 0;
1791
        }
1792
        private void btnSer2_127_Click(object sender, EventArgs e)
1793
        {
1794
            trckbarSerial2.Value = 127;
1795
        }
1796
        private void btnSer2_254_Click(object sender, EventArgs e)
1797
        {
1798
            trckbarSerial2.Value = 254;
1799
        }
2259 - 1800
        private void textBoxSerial3_TextChanged(object sender, EventArgs e)
1801
        {
1802
            serChanTitle[2] = textBoxSerial3.Text;
1803
        }
1804
        private void trckbarSerial3_ValueChanged(object sender, EventArgs e)
1805
        {
1806
            lblTbSerial3.Text = trckbarSerial3.Value.ToString();
1807
            serChan[2] = trckbarSerial3.Value;
1808
            if (!_init) _sendSerialData();
1809
        }
1810
        private void btnSer3_0_Click(object sender, EventArgs e)
1811
        {
1812
            trckbarSerial3.Value = 0;
1813
        }
1814
        private void btnSer3_127_Click(object sender, EventArgs e)
1815
        {
1816
            trckbarSerial3.Value = 127;
1817
        }
1818
        private void btnSer3_254_Click(object sender, EventArgs e)
1819
        {
1820
            trckbarSerial3.Value = 254;
1821
        }
1822
        private void textBoxSerial4_TextChanged(object sender, EventArgs e)
1823
        {
1824
            serChanTitle[3] = textBoxSerial4.Text;
1825
        }
1826
        private void trckbarSerial4_ValueChanged(object sender, EventArgs e)
1827
        {
1828
            lblTbSerial4.Text = trckbarSerial4.Value.ToString();
1829
            serChan[3] = trckbarSerial4.Value;
1830
            if (!_init) _sendSerialData();
1831
        }
1832
        private void btnSer4_0_Click(object sender, EventArgs e)
1833
        {
1834
            trckbarSerial4.Value = 0;
1835
        }
1836
        private void btnSer4_127_Click(object sender, EventArgs e)
1837
        {
1838
            trckbarSerial4.Value = 127;
1839
        }
1840
        private void btnSer4_254_Click(object sender, EventArgs e)
1841
        {
1842
            trckbarSerial4.Value = 254;
1843
        }
2265 - 1844
        private void tbSerial5_Scroll(object sender, EventArgs e)
1845
        {
1846
            lblTbSerial5.Text = trckbarSerial5.Value.ToString();
1847
            serChan[4] = trckbarSerial5.Value;
1848
            if (!_init) _sendSerialData();
1849
        }
1850
        private void textBoxSerial5_TextChanged(object sender, EventArgs e)
1851
        {
1852
            serChanTitle[4] = textBoxSerial5.Text;
1853
        }
1854
        private void btnSer5_0_Click(object sender, EventArgs e)
1855
        {
1856
            trckbarSerial5.Value = 0;
1857
        }
1858
        private void btnSer5_127_Click(object sender, EventArgs e)
1859
        {
1860
            trckbarSerial5.Value = 127;
1861
        }
1862
        private void btnSer5_254_Click(object sender, EventArgs e)
1863
        {
1864
            trckbarSerial5.Value = 254;
1865
        }
1866
        private void trckbarSerial5_ValueChanged(object sender, EventArgs e)
1867
        {
1868
            lblTbSerial5.Text = trckbarSerial5.Value.ToString();
1869
            serChan[4] = trckbarSerial5.Value;
1870
            if (!_init) _sendSerialData();
1871
        }
1872
        private void tbSerial6_Scroll(object sender, EventArgs e)
1873
        {
1874
            lblTbSerial6.Text = trckbarSerial6.Value.ToString();
1875
            serChan[5] = trckbarSerial6.Value;
1876
            if (!_init) _sendSerialData();
1877
        }
1878
        private void textBoxSerial6_TextChanged(object sender, EventArgs e)
1879
        {
1880
            serChanTitle[5] = textBoxSerial6.Text;
1881
        }
1882
        private void btnSer6_0_Click(object sender, EventArgs e)
1883
        {
1884
            trckbarSerial6.Value = 0;
1885
        }
1886
        private void btnSer6_127_Click(object sender, EventArgs e)
1887
        {
1888
            trckbarSerial6.Value = 127;
1889
        }
1890
        private void btnSer6_254_Click(object sender, EventArgs e)
1891
        {
1892
            trckbarSerial6.Value = 254;
1893
        }
1894
        private void trckbarSerial6_ValueChanged(object sender, EventArgs e)
1895
        {
1896
            lblTbSerial6.Text = trckbarSerial6.Value.ToString();
1897
            serChan[5] = trckbarSerial6.Value;
1898
            if (!_init) _sendSerialData();
1899
        }
1900
        private void tbSerial7_Scroll(object sender, EventArgs e)
1901
        {
1902
            lblTbSerial7.Text = trckbarSerial7.Value.ToString();
1903
            serChan[6] = trckbarSerial7.Value;
1904
            if (!_init) _sendSerialData();
1905
        }
1906
        private void textBoxSerial7_TextChanged(object sender, EventArgs e)
1907
        {
1908
            serChanTitle[6] = textBoxSerial7.Text;
1909
        }
1910
        private void btnSer7_0_Click(object sender, EventArgs e)
1911
        {
1912
            trckbarSerial7.Value = 0;
1913
        }
1914
        private void btnSer7_127_Click(object sender, EventArgs e)
1915
        {
1916
            trckbarSerial7.Value = 127;
1917
        }
1918
        private void btnSer7_254_Click(object sender, EventArgs e)
1919
        {
1920
            trckbarSerial7.Value = 254;
1921
        }
1922
        private void trckbarSerial7_ValueChanged(object sender, EventArgs e)
1923
        {
1924
            lblTbSerial7.Text = trckbarSerial7.Value.ToString();
1925
            serChan[6] = trckbarSerial7.Value;
1926
            if (!_init) _sendSerialData();
1927
        }
1928
        private void tbSerial8_Scroll(object sender, EventArgs e)
1929
        {
1930
            lblTbSerial8.Text = trckbarSerial8.Value.ToString();
1931
            serChan[7] = trckbarSerial8.Value;
1932
            if (!_init) _sendSerialData();
1933
        }
1934
        private void textBoxSerial8_TextChanged(object sender, EventArgs e)
1935
        {
1936
            serChanTitle[7] = textBoxSerial8.Text;
1937
        }
1938
        private void btnSer8_0_Click(object sender, EventArgs e)
1939
        {
1940
            trckbarSerial8.Value = 0;
1941
        }
1942
        private void btnSer8_127_Click(object sender, EventArgs e)
1943
        {
1944
            trckbarSerial8.Value = 127;
1945
        }
1946
        private void btnSer8_254_Click(object sender, EventArgs e)
1947
        {
1948
            trckbarSerial8.Value = 254;
1949
        }
1950
        private void trckbarSerial8_ValueChanged(object sender, EventArgs e)
1951
        {
1952
            lblTbSerial8.Text = trckbarSerial8.Value.ToString();
1953
            serChan[7] = trckbarSerial8.Value;
1954
            if (!_init) _sendSerialData();
1955
        }
2259 - 1956
        #endregion serial control channels
1957
 
2233 - 1958
    }
1959
    public class IniFile
1960
    {
1961
        public string path;
1962
 
1963
        [DllImport("kernel32")]
1964
        private static extern long WritePrivateProfileString(string section,
1965
          string key, string val, string filePath);
1966
 
1967
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
1968
        static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
1969
               uint nSize, string lpFileName);
1970
 
1971
        [DllImport("kernel32")]
1972
        private static extern int GetPrivateProfileString(string section,
1973
          string key, string def, StringBuilder retVal,
1974
          int size, string filePath);
1975
 
1976
        public IniFile(string INIPath)
1977
        {
1978
            path = INIPath;
1979
        }
1980
 
1981
        public void IniWriteValue(string Section, string Key, string Value)
1982
        {
1983
            WritePrivateProfileString(Section, Key, Value, this.path);
1984
        }
1985
 
1986
        public string IniReadValue(string Section, string Key)
1987
        {
1988
            StringBuilder temp = new StringBuilder(255);
1989
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
1990
            return temp.ToString();
1991
        }
1992
        //Ini_sections auslesen in String-Array
1993
        public string[] IniSectionNames()
1994
        {
1995
 
1996
            //  uint MAX_BUFFER = 32767;
1997
            uint MAX_BUFFER = 8388608;
1998
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
1999
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, this.path);
2000
            if (bytesReturned == 0)
2001
            {
2002
                Marshal.FreeCoTaskMem(pReturnedString);
2003
                return null;
2004
            }
2005
            string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
2006
            Marshal.FreeCoTaskMem(pReturnedString);
2007
            //use of Substring below removes terminating null for split
2008
            return local.Substring(0, local.Length - 1).Split('\0');
2009
 
2010
 
2011
        }
2012
    }
2013
    public static class ControlExtensions
2014
    {
2015
        /// <summary> 
2016
        /// Execute a threadsafe operation, when accessing a control via another thread 
2017
        /// action is a lamdaexpression
2018
        /// e.g. comboBox1.ExecuteThreadSafe(() => comboBox1.Enabled = true);
2019
        /// </summary>
2020
        /// <param name="control"> The control </param>
2021
        /// <param name="action"> The 'action' to perform </param>
2022
        public static void ExecuteThreadSafe(this Control control, Action action)
2023
        {
2024
            if (control.InvokeRequired)
2025
            {
2026
                control.BeginInvoke(action); //"BeginInvoke" is an async call -> threadsafety error when called to many times successively -> then take "Invoke"
2027
            }
2028
            else
2029
            {
2030
                action.Invoke();
2031
            }
2032
        }
2033
    }
2034
 
2035
}