Subversion Repositories Projects

Rev

Rev 2257 | 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)
32
/// and the sourcode (http://hdl.lib.byu.edu/1877/2748)
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>
181
        byte debugInterval = 25; //(=> 250ms)
182
        /// <summary>
183
        /// interval for sending BL-CTRL status (multiplied by 10ms)
184
        /// </summary>
185
        byte blctrlInterval = 45;
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();
2257 - 209
            serChanTitle.Initialize();
210
 
2233 - 211
            _readIni();
2257 - 212
 
2259 - 213
            _dataTablesInit();
2257 - 214
 
2233 - 215
            simpleSerialPort.PortClosed += SimpleSerialPort_PortClosed;
216
            simpleSerialPort.PortOpened += SimpleSerialPort_PortOpened;
217
            simpleSerialPort.DataReceived += processMessage;
218
            chkbAutoBL.Checked = _blctrlDataAutorefresh;
219
            chkbAutoDbg.Checked = _debugDataAutorefresh;
220
            chkbAutoNav.Checked = _navCtrlDataAutorefresh;
221
            chkbAutoOSD.Checked = _OSDAutorefresh;
222
            labelTimingDebug.Text = (debugInterval * 10).ToString();
223
            labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
224
            labelTimingNAV.Text = (navctrlInterval * 10).ToString();
225
            labelTimingOSD.Text = (OSDInterval * 10).ToString();
2257 - 226
            TabControl1.TabPages.Remove(tabPageTesting);
2233 - 227
        }
2257 - 228
 
2233 - 229
        #region events
230
        private void MainForm_Shown(object sender, EventArgs e)
231
        {
232
            _loadLabelNames();
2257 - 233
            _initSerialCtrl();
2233 - 234
            _init = false;
2250 - 235
            splitContainer1.SplitterDistance = 514;
2233 - 236
        }
237
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
238
        {
239
            _writeIni();
240
        }
241
        private void SimpleSerialPort_PortOpened()
242
        {
243
            btnConn.Invoke((Action)(() => btnConn.BackColor = Color.FromArgb(192, 255, 192)));
244
            btnConn.Invoke((Action)(() => btnConn.Text = "close" + Environment.NewLine + "serial port"));
245
            _getVersion();
246
            Thread.Sleep(100);
247
            _OSDMenue(0);
2257 - 248
            Thread.Sleep(200);
249
            _sendSerialData();
2233 - 250
           // _readCont(true);
251
        }
252
        private void SimpleSerialPort_PortClosed()
253
        {
254
            btnConn.Invoke((Action)(() => btnConn.BackColor = Color.FromArgb(224, 224, 224)));
255
            btnConn.Invoke((Action)(() => btnConn.Text = "open" + Environment.NewLine + "serial port"));
256
            _readCont(false);
257
        }
258
        /// <summary>
259
        /// timer for refreshing subscription of subscribed data
260
        /// query lifecounter for connection failure
261
        /// </summary>
262
        private void timer1_Tick(object sender, EventArgs e)
263
        {
264
            if(bReadContinously)
265
            {
266
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
267
 
2250 - 268
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
2233 - 269
 
270
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
271
                check_HWError = true;
272
                _getVersion();
273
                Thread.Sleep(10);
274
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); }
275
                if (_iLifeCounter > 0)
276
                {
277
                    lblLifeCounter.BackColor = Color.FromArgb(0, 224, 0);
278
                    _iLifeCounter = 0;
279
                }
280
                else
281
                {
282
                    Log(LogMsgType.Error, "No communication to NC/FC!");
283
                    lblLifeCounter.BackColor = Color.FromArgb(224, 0, 0);
284
                }
285
            }
286
        }
287
        private void cbOSD_SelectedIndexChanged(object sender, EventArgs e)
288
        {
289
            if (!_bCBInit && cbOSD.SelectedIndex > -1)
290
                _OSDMenue(cbOSD.SelectedIndex);
291
        }
292
        private void chkbAutoDbg_CheckedChanged(object sender, EventArgs e)
293
        {
294
            if(!_init) _debugDataAutorefresh = chkbAutoDbg.Checked;
295
        }
296
        private void chkbAutoNav_CheckedChanged(object sender, EventArgs e)
297
        {
298
            if (!_init) _navCtrlDataAutorefresh = chkbAutoNav.Checked;
299
        }
300
        private void chkbAutoBL_CheckedChanged(object sender, EventArgs e)
301
        {
302
            if (!_init) _blctrlDataAutorefresh = chkbAutoBL.Checked;
303
        }
304
        private void chkbAutoOSD_CheckedChanged(object sender, EventArgs e)
305
        {
306
            if (!_init) _OSDAutorefresh = chkbAutoOSD.Checked;
307
        }
308
        private void cbTimingDebug_SelectedIndexChanged(object sender, EventArgs e)
309
        {
310
            if (cbTimingDebug.SelectedIndex > -1)
311
            {
312
                debugInterval = (byte)(Convert.ToInt16(cbTimingDebug.SelectedItem) / 10);
313
                labelTimingDebug.Text = (debugInterval * 10).ToString();
314
            }
315
        }
316
        private void cbTimingNAV_SelectedIndexChanged(object sender, EventArgs e)
317
        {
318
            if (cbTimingNAV.SelectedIndex > -1)
319
            {
320
                navctrlInterval = (byte)(Convert.ToInt16(cbTimingNAV.SelectedItem) / 10);
321
                labelTimingNAV.Text = (navctrlInterval * 10).ToString();
322
            }
323
        }
324
        private void cbTimingBLCTRL_SelectedIndexChanged(object sender, EventArgs e)
325
        {
326
            if (cbTimingBLCTRL.SelectedIndex > -1)
327
            {
328
                blctrlInterval = (byte)(Convert.ToInt16(cbTimingBLCTRL.SelectedItem) / 10);
329
                labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
330
            }
331
        }
332
        private void cbTimingOSD_SelectedIndexChanged(object sender, EventArgs e)
333
        {
334
            if (cbTimingOSD.SelectedIndex > -1)
335
            {
336
                OSDInterval = (byte)(Convert.ToInt16(cbTimingOSD.SelectedItem) / 10);
337
                labelTimingOSD.Text = (OSDInterval * 10).ToString();
338
            }
339
        }
2254 - 340
        private void rtfError_LinkClicked(object sender, LinkClickedEventArgs e)
341
        {
342
            System.Diagnostics.Process.Start(e.LinkText);
343
        }
2257 - 344
 
2233 - 345
        #endregion events
346
 
347
        /// <summary> Log data to the terminal window. </summary>
348
        /// <param name="msgtype"> The type of message to be written. </param>
349
        /// <param name="msg"> The string containing the message to be shown. </param>
350
        private void Log(LogMsgType msgtype, string msg)
351
        {
352
            rtfTerminal.Invoke(new EventHandler(delegate
353
            {
354
                if (rtfTerminal.Lines.Length >= 1000)   //Wenn Terminal mehr als 1000 Zeilen hat
355
                    rtfTerminal.Select(42, (500 * 129));     //500 löschen
356
                rtfTerminal.Select(rtfTerminal.Text.Length, 0);
357
                rtfTerminal.SelectedText = string.Empty;
358
                rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Regular);
359
                rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
360
                rtfTerminal.AppendText(msg + Environment.NewLine);
361
                rtfTerminal.ScrollToCaret();
362
            }));
363
        }
364
        /// <summary> display the OSD text in 4 lines à 20 chars </summary>
365
        /// <param name="msgtype"> The type of message to be written. </param>
366
        /// <param name="msg"> The string containing the message to be shown. </param>
367
        private void OSD(LogMsgType msgtype, string msg)
368
        {
369
            rtfOSD.Invoke(new EventHandler(delegate
370
            {
371
                if (rtfOSD.Lines.Length > 4)
372
                    rtfOSD.Clear();
373
                rtfOSD.Select(rtfOSD.Text.Length,0);
374
                rtfOSD.SelectedText = string.Empty;
375
                rtfOSD.SelectionFont = new Font(rtfOSD.SelectionFont, FontStyle.Regular);
376
                rtfOSD.SelectionColor = LogMsgTypeColor[(int)msgtype];
377
                rtfOSD.AppendText(msg + Environment.NewLine);
378
                if (rtfOSD.Text.IndexOf("ERR") > 0)
379
                {
380
                    rtfOSD.Select(rtfOSD.Text.IndexOf("ERR"), 40);
381
                    rtfOSD.SelectionColor = LogMsgTypeColor[(int)LogMsgType.Error];
382
                }
383
            }));
384
        }
385
        private void ErrorLog(LogMsgType msgtype, string msg)
386
        {
387
            rtfError.Invoke(new EventHandler(delegate
388
            {
389
                if (rtfError.Lines.Length > 4)
390
                    rtfError.Clear();
391
                rtfError.Focus();
392
                rtfError.Select(rtfError.Text.Length, 0);
393
                rtfError.SelectedText = string.Empty;
394
                rtfError.SelectionFont = new Font(rtfError.SelectionFont, FontStyle.Regular);
395
                rtfError.SelectionColor = LogMsgTypeColor[(int)msgtype];
396
                rtfError.AppendText(msg + Environment.NewLine);
397
 
398
            }));
2254 - 399
            _bErrorLog = true;
2233 - 400
        }
401
 
402
        #region functions        
403
 
2250 - 404
        #region processing received data
405
        /// <summary> Processing the messages and displaying them in the according form controls 
406
        /// function called by simpleSerialPort.DataReceived event
407
        /// </summary>
2233 - 408
        /// <param name="message"> message bytearray recieved by SimpleSerialPort class </param>
409
        private void processMessage(byte[] message)
410
        {
411
            if (message.Length > 0)
412
            {
413
                _iLifeCounter++;
414
                //Log(LogMsgType.Incoming, BitConverter.ToString(message));
415
                //Log(LogMsgType.Incoming, message.Length.ToString());
416
                string s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, message.Length));
417
                char cmdID;
418
                byte adr;
419
                byte[] data;
2257 - 420
                byte[] tmp = null;
2233 - 421
                if (message[0] != '#')
2257 - 422
                {
423
                    int iFound = -1;
424
                    for(int i=0;i<message.Length;i++)   //Sometimes the FC/NC sends strings without termination (like WP messages)
425
                    {                                   //so this is a workaround to not spam the log box
426
                        if (message[i] == 35)
427
                        {
428
                            iFound = i;
429
                            break;
430
                        }                          
431
                    }
432
                    if(iFound>0)
433
                    {
434
                        s = new string(ASCIIEncoding.ASCII.GetChars(message, 0,iFound));
435
                        tmp = new byte[message.Length - iFound];
436
                        Buffer.BlockCopy(message, iFound, tmp, 0, message.Length - iFound);
437
                    }
438
                    s = s.Trim('\0', '\n', '\r');
439
                    if(s.Length > 0)
440
                        Log(LogMsgType.Normal, s);
441
                    if (tmp != null)
442
                    {
443
                        s = new string(ASCIIEncoding.ASCII.GetChars(tmp, 0, tmp.Length));
444
                        processMessage(tmp);
445
                    }
446
                }
2233 - 447
                //Debug.Print(s);
448
                else
449
                {
450
                    FlightControllerMessage.ParseMessage(message, out cmdID, out adr, out data);
451
 
452
                    if (adr == 255) { crcError++; }
453
                    else crcError = 0;
454
                    lblCRCErr.Invoke((Action)(() => lblCRCErr.Text = crcError.ToString()));
2250 - 455
                    //display the active controller (FC / NC) 
2233 - 456
                    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...???
457
                    {
458
                        _iCtrlAct = adr;
459
                        switch (adr)
460
                        {
461
                            case 1:
462
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "FC"));
463
                                lblNCCtrl.Invoke((Action)(() => lblNCCtrl.Text = "FC"));
464
                                _setFieldsNA(); //display fields NA for FC 
465
                                break;
466
                            case 2:
467
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "NC"));
468
                                lblNCCtrl.Invoke((Action)(() => lblNCCtrl.Text = "NC"));
469
                                break;
470
                            case 3:
471
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "MK3MAG"));
472
                                break;
473
                            case 4:
474
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "BL-CTRL"));
475
                                break;
476
                            default:
477
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "...."));
478
                                break;
479
                        }
2257 - 480
                        _loadLabelNames();
2233 - 481
                    }
2257 - 482
                    // else
483
                    //     Debug.Print("Address == 0?");
2233 - 484
 
485
                    if (data != null && data.Length > 0)
486
                    {
487
                        s = new string(ASCIIEncoding.ASCII.GetChars(data, 1, data.Length - 1));
488
                        s = s.Trim('\0', '\n');
489
 
490
                        switch (cmdID)
491
                        {
2250 - 492
                            case 'A': //Label names
493
                                _processLabelNames(s);
2233 - 494
                                break;
495
 
2250 - 496
                            case 'D': //Debug data
2257 - 497
                                _processDebugVals(adr, data);
2233 - 498
                                break;
499
 
2250 - 500
                            case 'V': //Version
501
                                _processVersion(adr, data);
2233 - 502
                                break;
503
 
2250 - 504
                            case 'K'://BL-CTRL data
505
                                _processBLCtrl(data);
2233 - 506
                                break;
507
 
508
                            case 'O': //NC Data
2250 - 509
                                _processNCData(data);
2233 - 510
                                break;
511
 
512
                            case 'E': //NC error-string
513
                                ErrorLog(LogMsgType.Error, "NC Error: " + s);
514
                                break;
515
 
2250 - 516
                            case 'L': //OSD Menue (called by pagenumber)
517
                                _processOSDSingle(data);
2233 - 518
                                break;
519
 
2250 - 520
                            case 'H': //OSD Menue (with autoupdate - called by Key)
521
                                _processOSDAuto(data);
2233 - 522
                                break;
523
 
2257 - 524
                            case 'X': //Waypoint data
525
                                _processWPData(data);
526
                                break;
527
 
2233 - 528
                            //default:
529
                            //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
530
                            //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
531
                            //    break;
532
                        }
533
                    }
534
                    //else
535
                    //{
536
                    //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
537
                    //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
538
                    //}
539
                }
540
            }
541
        }
2250 - 542
        /// <summary>
543
        /// Analog label names 'A'
544
        /// each label name is returned as a single string 
545
        /// and added to string array sAnalogLabel[]
546
        /// and the datatable dtAnalog
547
        /// </summary>
548
        /// <param name="s">the label name</param>
549
        void _processLabelNames(string s)
550
        {
551
            if (iLableIndex < 32)
552
            {
553
                sAnalogLabel[iLableIndex] = s;
554
                if (dtAnalog.Rows.Count < 32)
555
                    dtAnalog.Rows.Add(s, "");
556
                else
557
                    dtAnalog.Rows[iLableIndex].SetField(0, s);
2233 - 558
 
2250 - 559
                _getAnalogLabels(iLableIndex + 1);
560
            }
561
            Debug.Print(s);
562
        }
563
        /// <summary>
564
        /// Debug values 'D'
565
        /// </summary>
566
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
567
        /// <param name="data">the received byte array to process</param>
568
        void _processDebugVals(byte adr,byte[] data)
569
        {
570
            if (data.Length == 66)
571
            {
572
                int[] iAnalogData = new int[32];
573
 
574
                int index = 0;
575
                Int16 i16 = 0;
576
                double dTemp = 0;
577
                for (int i = 2; i < 66; i += 2)
578
                {
579
                    i16 = data[i + 1];
580
                    i16 = (Int16)(i16 << 8);
581
                    iAnalogData[index] = data[i] + i16;
582
                    sAnalogData[index] = (data[i] + i16).ToString();
583
                    dtAnalog.Rows[index].SetField(1, sAnalogData[index]);
584
 
585
                    if (adr == 2) //NC
586
                    {
587
                        switch (index)
588
                        {
589
                            case 0: //pitch (German: nick)
590
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.pitch_angle = ((double)iAnalogData[index] / (double)10)));
591
                                lblNCPitch.Invoke((Action)(() => lblNCPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
592
                                break;
593
                            case 1: //roll
594
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.roll_angle = ((double)iAnalogData[index] / (double)10)));
595
                                lblNCRoll.Invoke((Action)(() => lblNCRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
596
                                break;
597
                            case 4: //altitude
598
                                lblNCAlt.Invoke((Action)(() => lblNCAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m")));
599
                                break;
600
                            case 7: //Voltage
601
                                lblNCVolt.Invoke((Action)(() => lblNCVolt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 V")));
602
                                break;
603
                            case 8: // Current
604
                                lblNCCur.Invoke((Action)(() => lblNCCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A")));
605
                                break;
606
                            case 10: //heading
607
                                lblNCCompass.Invoke((Action)(() => lblNCCompass.Text = sAnalogData[index] + "°"));
608
                                headingIndicator1.Invoke((Action)(() => headingIndicator1.SetHeadingIndicatorParameters(iAnalogData[index])));
609
                                break;
610
                            case 12: // SPI error
611
                                lblNCSPI.Invoke((Action)(() => lblNCSPI.Text = sAnalogData[index]));
612
                                break;
613
                            case 14: //i2c error
614
                                lblNCI2C.Invoke((Action)(() => lblNCI2C.Text = sAnalogData[index]));
615
                                break;
616
                            case 20: //Earthmagnet field
617
                                lblNCMF.Invoke((Action)(() => lblNCMF.Text = sAnalogData[index] + "%"));
618
                                break;
619
                            case 21: //GroundSpeed
620
                                lblNCGSpeed.Invoke((Action)(() => lblNCGSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
621
                                break;
622
                            case 28: //Distance East from saved home position -> calculate distance with distance N + height
623
                                dTemp = Math.Pow((double)iAnalogData[index], 2) + Math.Pow((double)iAnalogData[index - 1], 2);
624
                                dTemp = Math.Sqrt(dTemp) / (double)10; //'flat' distance from HP with N/E
625
                                                                       //  lblNCDist.Invoke((Action)(() => lblNCDist.Text = dTemp.ToString("0.00")));
626
                                dTemp = Math.Pow(dTemp, 2) + Math.Pow(((double)iAnalogData[4] / (double)10), 2); //adding 'height' into calculation
2254 - 627
                                dTemp = Math.Sqrt(dTemp) / (double)10;
628
                                lblNCDistHP.Invoke((Action)(() => lblNCDistHP.Text = dTemp.ToString("0.0 m")));
2250 - 629
                                break;
630
                            case 31: //Sats used
631
                                lblNCSat.Invoke((Action)(() => lblNCSat.Text = sAnalogData[index]));
632
                                break;
633
                        }
634
                    }
635
                    if (adr == 1) //FC
636
                    {
637
                        switch (index)
638
                        {
639
                            case 0: //pitch (German: nick)
640
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.pitch_angle = ((double)iAnalogData[index] / (double)10)));
641
                                lblNCPitch.Invoke((Action)(() => lblNCPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
642
                                break;
643
                            case 1: //roll
644
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.roll_angle = ((double)iAnalogData[index] / (double)10)));
645
                                lblNCRoll.Invoke((Action)(() => lblNCRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
646
                                break;
647
                            case 5: //altitude
648
                                lblNCAlt.Invoke((Action)(() => lblNCAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m")));
649
                                break;
650
                            case 8: //heading
651
                                lblNCCompass.Invoke((Action)(() => lblNCCompass.Text = sAnalogData[index] + "°"));
652
                                headingIndicator1.Invoke((Action)(() => headingIndicator1.SetHeadingIndicatorParameters(iAnalogData[index])));
653
                                break;
654
                            case 9: //Voltage
655
                                lblNCVolt.Invoke((Action)(() => lblNCVolt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 V")));
656
                                break;
657
                            case 10: //Receiver quality
658
                                lblNCRC.Invoke((Action)(() => lblNCRC.Text = sAnalogData[index]));
659
                                break;
660
                            case 22: // Current
661
                                lblNCCur.Invoke((Action)(() => lblNCCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A")));
662
                                break;
663
                            case 23: //capacity used
664
                                lblNCCap.Invoke((Action)(() => lblNCCap.Text = (iAnalogData[index]).ToString("0 mAh")));
665
                                break;
666
                            case 27: // SPI error
667
                                lblNCSPI.Invoke((Action)(() => lblNCSPI.Text = sAnalogData[index]));
668
                                break;
669
                            case 28: //i2c error
670
                                lblNCI2C.Invoke((Action)(() => lblNCI2C.Text = sAnalogData[index]));
671
                                break;
672
                        }
673
                    }
674
                    index++;
675
                }
676
            }
677
            else
678
                Debug.Print("wrong data-length (66): " + data.Length.ToString());
679
        }
680
        /// <summary>
681
        /// Version string 'V'
682
        /// </summary>
683
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
684
        /// <param name="data">the received byte array to process</param>
685
        void _processVersion(byte adr,byte[] data)
686
        {
687
            if (data.Length == 12)
688
            {
689
                if (!check_HWError)
690
                {
691
                    string[] sVersionStruct = new string[10] { "SWMajor: ", "SWMinor: ", "ProtoMajor: ", "LabelTextCRC: ", "SWPatch: ", "HardwareError 1: ", "HardwareError 2: ", "HWMajor: ", "BL_Firmware: ", "Flags: " };
692
                    string sVersion = "";
693
                    //sbyte[] signed = Array.ConvertAll(data, b => unchecked((sbyte)b));
694
                    Log(LogMsgType.Warning, (adr == 1 ? "FC-" : "NC-") + "Version: ");
695
                    sVersion = "HW V" + (data[7] / 10).ToString() + "." + (data[7] % 10).ToString();
696
                    Log(LogMsgType.Incoming, sVersion);
697
                    sVersion = "SW V" + (data[0]).ToString() + "." + (data[1]).ToString() + ((char)(data[4] + 'a')).ToString();
698
                    Log(LogMsgType.Incoming, sVersion);
699
                    Log(LogMsgType.Incoming, "BL-Firmware: V" + (data[8] / 100).ToString() + "." + (data[8] % 100).ToString());
700
                }
701
                if (data[5] > 0) //error0 
702
                {
703
                    if (adr == 1)
704
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[5].ToString() + ": " + ((FC_HWError0)data[5]).ToString());
705
                    if (adr == 2)
706
                        ErrorLog(LogMsgType.Error, "NC - HW-Error " + data[5].ToString() + ": " + ((NC_HWError0)data[5]).ToString());
707
                }
708
                if (data[6] > 0) //error1 
709
                {
710
                    if (adr == 1)
711
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[6].ToString() + ": " + ((FC_HWError1)data[6]).ToString());
712
                    if (adr == 2)
713
                        ErrorLog(LogMsgType.Error, "NC - Unknown HW-ERROR: " + data[6].ToString()); //@moment NC has only one error field
714
                }
2254 - 715
                if((data[5] + data[6] == 0) && _bErrorLog)
716
                    _clearErrorLog(adr==1 ? "FC - HW-Error" : "FC - HW-Error");
2250 - 717
 
718
            }
719
            check_HWError = false;
720
        }
721
        /// <summary>
722
        /// BL-Ctrl data 'K'
723
        /// for FC you have to use a customized firmware
724
        /// </summary>
725
        /// <param name="data">the received byte array to process</param>
726
        void _processBLCtrl(byte[] data)
727
        {
728
            if (data.Length % 6 == 0) //data.Length up to 96 (16 motors x 6 byte data) --> new datastruct in FC -> not standard!
729
            {
730
                bool bAvailable = false;
731
                for (int i = 0; i < data.Length && data[i] < 8; i += 6) // data[i] < 8 --> at moment there are 8 display fields for motors
732
                {
733
 
734
                    if ((data[i + 4] & 128) == 128) //Status bit at pos 7 = 128 dec -- if true, motor is available
735
                        bAvailable = true;
736
                    else
737
                        bAvailable = false;
738
 
739
                    if (data[i] < 4)
740
                    {
741
                        if (bAvailable)
742
                        {
743
                            dtMotors1.Rows[data[i]].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
744
                            dtMotors1.Rows[data[i]].SetField(2, data[i + 2].ToString("0 °C"));
745
                        }
746
                        else
747
                        {
748
                            dtMotors1.Rows[data[i]].SetField(1, "NA");
749
                            dtMotors1.Rows[data[i]].SetField(2, "NA");
750
                        }
751
                    }
752
                    if (data[i] > 3 && data[i] < 8)
753
                    {
754
                        if (bAvailable)
755
                        {
756
                            dtMotors2.Rows[data[i] - 4].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
757
                            dtMotors2.Rows[data[i] - 4].SetField(2, data[i + 2].ToString("0 °C"));
758
                        }
759
                        else
760
                        {
761
                            dtMotors2.Rows[data[i] - 4].SetField(1, "NA");
762
                            dtMotors2.Rows[data[i] - 4].SetField(2, "NA");
763
                        }
764
                    }
765
                }
766
            }
767
 
768
        }
769
        /// <summary>
770
        /// Navi-Ctrl data 'O'
771
        /// GPS-Position, capacatiy, flying time...
772
        /// </summary>
773
        /// <param name="data">the received byte array to process</param>
774
        void _processNCData(byte[] data)
775
        {
776
            int i_32, i_16, iVal;
777
            double d;
778
            i_32 = data[4];
779
            iVal = i_32 << 24;
780
            i_32 = data[3];
781
            iVal += i_32 << 16;
782
            i_32 = data[2];
783
            iVal += i_32 << 8;
784
            iVal += data[1];
785
            d = (double)iVal / Math.Pow(10, 7);
786
            lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = d.ToString("0.######°"))); //GPS-Position: Longitude in decimal degree
787
            //lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = _convertDegree(d))); //GPS-Position: Longitude in minutes, seconds
788
 
789
            i_32 = data[8];
790
            iVal = i_32 << 24;
791
            i_32 = data[7];
792
            iVal += i_32 << 16;
793
            i_32 = data[6];
794
            iVal += i_32 << 8;
795
            iVal += data[5];
796
            d = (double)iVal / Math.Pow(10, 7);
797
            lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = d.ToString("0.######°"))); //GPS-Position: Latitude in decimal degree
2254 - 798
                                                                                            //lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = _convertDegree(d))); //GPS-Position: Latitude in minutes, seconds
2250 - 799
 
2254 - 800
            i_16 = data[28];
801
            i_16 = (Int16)(i_16 << 8);
802
            iVal = data[27] + i_16;
803
            lblNCDistWP.Invoke((Action)(() => lblNCDistWP.Text = ((double)iVal/ (double)10).ToString("0.0 m"))); //Distance to next WP
804
 
805
            i_16 = data[45];
806
            i_16 = (Int16)(i_16 << 8);
807
            iVal = data[44] + i_16;
808
            lblNCDistHP1.Invoke((Action)(() => lblNCDistHP1.Text = ((double)iVal/ (double)10).ToString("0.0 m"))); //Distance to next WP
809
 
810
            lblNCWPIndex.Invoke((Action)(() => lblNCWPIndex.Text = data[48].ToString())); //Waypoint index
811
            lblNCWPCount.Invoke((Action)(() => lblNCWPCount.Text = data[49].ToString())); //Waypoints count
812
 
2250 - 813
            i_16 = data[81];
814
            i_16 = (Int16)(i_16 << 8);
815
            iVal = data[80] + i_16;
816
            lblNCCap.Invoke((Action)(() => lblNCCap.Text = iVal.ToString() + " mAh")); //Capacity used
817
 
818
            i_16 = data[56];
819
            i_16 = (Int16)(i_16 << 8);
820
            iVal = data[55] + i_16;
821
            TimeSpan t = TimeSpan.FromSeconds(iVal);
822
            string Text = t.Hours.ToString("D2") + ":" + t.Minutes.ToString("D2") + ":" + t.Seconds.ToString("D2");
823
            lblNCFlTime.Invoke((Action)(() => lblNCFlTime.Text = Text.ToString())); //Flying time
824
 
825
            lblNCRC.Invoke((Action)(() => lblNCRC.Text = data[66].ToString())); //RC quality
826
            lblNCErrNmbr.Invoke((Action)(() => lblNCErrNmbr.Text = data[69].ToString()));   //NC Errornumber
827
            //if (data[69] > 0)
828
            //    _readNCError();
829
            //break;
830
            if (data[69] > 0 & data[69] < 44)
831
                ErrorLog(LogMsgType.Error, "NC Error [" + data[69].ToString() + "]: " + NC_Error[data[69]]);
2254 - 832
            else
833
                if(_bErrorLog) _clearErrorLog("NC Error");
2250 - 834
 
835
        }
836
        /// <summary>
2257 - 837
        /// Navi-Ctrl WP data struct 'X'
838
        /// called by index
839
        /// </summary>
840
        /// <param name="data">the received byte array to process</param>
841
        void _processWPData(byte[] data)
842
        {
843
            if (data.Length >= 28)
844
            {
845
                int count = data[0];
846
                int index = data[1];
847
                cbWPIndex.Invoke((Action)(() => cbWPIndex.Items.Clear()));
848
                for (int i = 0; i < count; i++)
849
                    cbWPIndex.Invoke((Action)(() => cbWPIndex.Items.Add(i + 1)));
850
                cbWPIndex.Invoke((Action)(() => cbWPIndex.SelectedItem = index));
851
                DataRow dr = dtWaypoints.NewRow();
852
                dr = Waypoints.toDataRow(data, dr);
853
                dtWaypoints.Rows.Add(dr);
854
                dgvWP.Invoke((Action)(() => dgvWP.Update()));
855
            }
856
            else
857
                Debug.Print(new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length)));
858
        }
859
        /// <summary>
2250 - 860
        /// OSD Menue 'L'
861
        /// single page called by pagenumber
862
        /// no autoupdate
863
        /// </summary>
864
        /// <param name="data">the received byte array to process</param>
865
        void _processOSDSingle(byte[] data)
866
        {
867
            if (data.Length == 84)
868
            {
869
                string sMessage = "";
870
                iOSDPage = data[0];
871
                iOSDMax = data[1];
872
                if (cbOSD.Items.Count != iOSDMax) _initOSDCB();
873
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 2, data.Length - 4));
874
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20));
875
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20));
876
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20));
877
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20));
878
                lblOSDPageNr.Invoke((Action)(() => lblOSDPageNr.Text = iOSDPage.ToString("[0]")));
879
 
880
            }
881
            else
882
                OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 84)");
883
 
884
        }
885
        /// <summary>
886
        /// OSD Menue 'H'
887
        /// called by keys (0x01,0x02,0x03,0x04)
888
        /// autoupdate
889
        /// </summary>
890
        /// <param name="data">the received byte array to process</param>
891
        void _processOSDAuto(byte[] data)
892
        {
893
            if (data.Length == 81)
894
            {
895
                string sMessage = "";
896
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length - 1));
897
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20));
898
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20));
899
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20));
900
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20));
901
 
902
            }
903
            else
904
                OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 81)");
905
        }
906
        #endregion processing received data
907
 
2233 - 908
        /// <summary> send message to controller to request data
909
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
910
        /// </summary>
911
        /// <param name="CMDID"> the command ID </param>
912
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
913
        private void _sendControllerMessage(char CMDID, byte address)
914
        {
915
            if (simpleSerialPort.Port.IsOpen)
916
            {
917
                Stream serialStream = simpleSerialPort.Port.BaseStream;
918
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address);
919
                serialStream.Write(bytes, 0, bytes.Length);
920
 
921
            }
922
            else
923
                Log(LogMsgType.Error, "NOT CONNECTED!");
924
        }
925
        /// <summary> send message to controller to request data
926
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
927
        /// </summary>
928
        /// <param name="CMDID"> the command ID </param>
929
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
930
        /// <param name="data"> additional data for the request</param>
931
        private void _sendControllerMessage(char CMDID, byte address, byte[]data)
932
        {
933
            if (simpleSerialPort.Port.IsOpen)
934
            {
935
                Stream serialStream = simpleSerialPort.Port.BaseStream;
936
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address,data);
937
                serialStream.Write(bytes, 0, bytes.Length);
938
 
939
            }
940
            else
941
                Log(LogMsgType.Error, "NOT CONNECTED!");
942
        }
943
 
944
        /// <summary>
945
        /// read the analog-label names for the actual controller
946
        /// and load it into listbox
947
        /// </summary>
948
        void _loadLabelNames()
949
        {
950
            if (_iCtrlAct > 0 && _iCtrlAct < 3)
951
            {
952
                switch (_iCtrlAct)
953
                {
954
                    case 1:
955
                        sAnalogLabel = Properties.Resources.FCLabelTexts.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
956
                        break;
957
                    case 2:
958
                        sAnalogLabel = Properties.Resources.NCLabelTexts.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
959
                        break;
960
                }
961
                for (int i = 0; i < 32; i++)
962
                {
963
                    if (dtAnalog.Rows.Count < 32)
964
                        dtAnalog.Rows.Add(sAnalogLabel[i], "");
965
                    else
966
                        dtAnalog.Rows[i].SetField(0, sAnalogLabel[i]);
967
                }
968
                dataGridView1.Invoke((Action)(()=>dataGridView1.Refresh()));
969
            }
970
        }
971
        /// <summary>
972
        /// no longer used...
973
        /// read the analog-label textfile for the actual controller
974
        /// </summary>
975
         private void _loadLabelFile()
976
        {
977
            switch (_iCtrlAct)
978
            {
979
                case 1:
980
                    fileName = "FCLabelTexts.txt";
981
                    break;
982
                case 2:
983
                    fileName = "NCLabelTexts.txt";
984
                    break;
985
                //default:
986
                //    fileName = "NCLabelTexts.txt";
987
                //    break;
988
            }
989
 
990
            if (File.Exists(filePath + "\\" + fileName))
991
            {
992
                sAnalogLabel.Initialize();
993
                sAnalogLabel = File.ReadAllLines(filePath + "\\" + fileName);
994
                lbLabels.Invoke((Action)(() => lbLabels.Items.Clear()));
995
                lbLabels.Invoke((Action)(() => lbLabels.Update()));
996
                lbLabels.Invoke((Action)(() => lbLabels.Items.AddRange(sAnalogLabel)));
997
                Console.WriteLine("Names loaded from file");
998
                lblFileName.Invoke((Action)(() => lblFileName.Text = fileName));
999
            }
1000
            else
1001
            {
1002
                _readCont(false);
1003
                Log(LogMsgType.Error, "Label-file not found!");
1004
                Log(LogMsgType.Error, "Please go to settings-tab and load the label texts from the copter control (FC & NC)");
1005
                Log(LogMsgType.Error, "When done, you have to save the label texts with the 'save' button!");
1006
            }
1007
        }
1008
        /// <summary>
1009
        /// no longer used...
1010
        /// assign the analog-label names from the textfile to the datatable
1011
        /// 
1012
        /// </summary>
1013
        private void _assignLabelNames()
1014
        {
1015
            if (lbLabels.Items.Count == 32)
1016
            {
1017
                lbLabels.Items.CopyTo(sAnalogLabel, 0);
1018
                for (int i = 0; i < 32; i++)
1019
                {
1020
                    if (dtAnalog.Rows.Count < 32)
1021
                        dtAnalog.Rows.Add(sAnalogLabel[i], "");
1022
                    else
1023
                        dtAnalog.Rows[i].SetField(0, sAnalogLabel[i]);
1024
 
1025
                }
1026
            }
1027
        }
1028
        /// <summary>
1029
        /// get the version struct of actual controller
1030
        /// </summary>
1031
        /// <summary>
1032
        /// get the labeltexts for the analog values
1033
        /// </summary>
1034
        private void _getAnalogLabels()
1035
        {
1036
            if (simpleSerialPort.Port.IsOpen)
1037
            {
1038
                iLableIndex = 0;
1039
                for (int i = 0; i < 32; i++)
1040
                {
1041
                    Stream serialStream = simpleSerialPort.Port.BaseStream;
1042
                    byte[] bytes = FlightControllerMessage.CreateMessage('a', 0, new byte[1] { (byte)i });
1043
                    serialStream.Write(bytes, 0, bytes.Length);
1044
                    Thread.Sleep(10);
1045
                }
1046
            }
1047
            else
1048
                Log(LogMsgType.Error, "NOT CONNECTED!");
1049
        }
1050
        /// <summary>
1051
        /// get the labeltext for a single label
1052
        /// </summary>
1053
        /// <param name="iIndex">index of the label</param>
1054
        private void _getAnalogLabels(int iIndex)
1055
        {
1056
            if (simpleSerialPort.Port.IsOpen)
1057
            {
1058
                if (iIndex < 32)
1059
                {
1060
                    iLableIndex = iIndex;
1061
                    _sendControllerMessage('a', 0, new byte[1] { (byte)iLableIndex });
1062
                }
1063
            }
1064
            else
1065
                Log(LogMsgType.Error, "NOT CONNECTED!");
1066
        }
1067
        private void _getVersion()
1068
        {
1069
            _sendControllerMessage('v', 0);
1070
        }
1071
        /// <summary>
1072
        /// get FC version struct via NC
1073
        /// by sending '1' as data (not documented in wiki...)
1074
        /// returns HW error 255 (comment in uart1.c : tells the KopterTool that it is the FC-version)
1075
        /// </summary>
1076
        /// <param name="ctrl">controller number 1=FC</param> 
1077
        private void _getVersion(byte ctrl)
1078
        {
1079
            _sendControllerMessage('v', 0, new byte[1] {ctrl});
1080
        }
1081
        /// <summary>
1082
        /// Switch back to NC by sending the 'Magic Packet' 0x1B,0x1B,0x55,0xAA,0x00
1083
        /// </summary>
1084
        private void _switchToNC()
1085
        {
1086
            if (simpleSerialPort.Port.IsOpen)
1087
            {
1088
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1089
                byte[] bytes = new byte[5] { 0x1B,0x1B,0x55,0xAA,0x00 };
1090
                serialStream.Write(bytes, 0, bytes.Length);
1091
 
1092
                Thread.Sleep(100);
1093
                _getVersion();
1094
                Thread.Sleep(100);
1095
                _OSDMenue(0);
1096
            }
1097
            else
1098
                Log(LogMsgType.Error, "NOT CONNECTED!");
1099
        }
1100
        /// <summary>
1101
        /// switch to FC
1102
        /// </summary>
1103
        private void _switchToFC()
1104
        {
1105
            _sendControllerMessage('u', 2, new byte[1] { (byte)0 });
1106
            Thread.Sleep(100);
1107
            _getVersion();
1108
            Thread.Sleep(100);
1109
            _OSDMenue(0);
1110
        }
1111
        /// <summary>
1112
        /// send RESET signal to FC
1113
        /// </summary>
1114
        private void _resetCtrl()
1115
        {
1116
            _sendControllerMessage('R', 1);
1117
        }
1118
        /// <summary>
1119
        /// poll the debug data (4sec subscription)
1120
        /// </summary>
1121
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1122
        private void _readDebugData(bool auto)
1123
        {
1124
            byte interval = auto ? debugInterval : (byte)0;
1125
            _sendControllerMessage('d', 0, new byte[1] { debugInterval });
1126
        }
1127
        /// <summary>
1128
        /// poll the BL-CTRL status via NC (4sec subscription)
1129
        /// </summary>
1130
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1131
        private void _readBLCtrl(bool auto)
1132
        {
1133
            byte interval = auto ? blctrlInterval : (byte)0;
1134
            _sendControllerMessage('k', 0, new byte[1] { interval });
1135
        }
1136
        /// <summary>
1137
        /// poll the NC data struct (4sec subscription)
1138
        /// </summary>
1139
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1140
        private void _readNavData(bool auto)
1141
        {
1142
            byte interval = auto ? navctrlInterval : (byte)0;
1143
            _sendControllerMessage('o', 2, new byte[1] { interval });
1144
        }
1145
        /// <summary>
1146
        /// get the errortext for pending NC error
1147
        /// </summary>
1148
        private void _readNCError()
1149
        {
1150
            _sendControllerMessage('e', 2);
1151
        }
1152
        /// <summary>
1153
        /// start/stop continous polling of controller values
1154
        /// </summary>
1155
        /// <param name="b">start/stop switch</param>
1156
        void _readCont(bool b)
1157
        {
1158
            bReadContinously = b;
1159
            btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.Text = bReadContinously ? "stop automatic" + Environment.NewLine + "data refresh" : "start automatic" + Environment.NewLine + "data refresh"));
1160
            btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.BackColor = bReadContinously ? Color.FromArgb(192, 255, 192) : Color.FromArgb(224, 224, 224)));
1161
            if (bReadContinously)
1162
            {
2250 - 1163
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
1164
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
1165
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
1166
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); Thread.Sleep(10);}
2233 - 1167
                lblLifeCounter.Invoke((Action)(() => lblLifeCounter.BackColor = Color.FromArgb(0, 224, 0)));
1168
            }
1169
            else
1170
                lblLifeCounter.Invoke((Action)(() => lblLifeCounter.BackColor = Color.FromArgb(224, 224, 224)));
1171
            _iLifeCounter = 0;
1172
        }
1173
        /// <summary>
2250 - 1174
        /// set values to "NA" when not available with FC
2233 - 1175
        /// </summary>
1176
        void _setFieldsNA()
1177
        {
1178
            Thread.Sleep(100);
2250 - 1179
            _initDTMotors();
2233 - 1180
            lblNCFlTime.Invoke((Action)(() => lblNCFlTime.Text = "NA"));    //FlightTime
2250 - 1181
            lblNCErrNmbr.Invoke((Action)(() => lblNCErrNmbr.Text = "NA"));  //NC ErrorNr
1182
            lblNCMF.Invoke((Action)(() => lblNCMF.Text = "NA"));            //earth magnet field
1183
            lblNCGSpeed.Invoke((Action)(() => lblNCGSpeed.Text = "NA"));    //GroundSpeed
1184
            lblNCDistHP.Invoke((Action)(() => lblNCDistHP.Text = "NA"));    //Distance to HP
1185
            lblNCSat.Invoke((Action)(() => lblNCSat.Text = "NA"));          //Sats used
1186
            lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = "NA"));  //GPS position - longitude
1187
            lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = "NA"));    //GPS position - latitude
2254 - 1188
            lblNCDistWP.Invoke((Action)(() => lblNCDistWP.Text = "NA"));    //next WP distance
1189
            lblNCWPIndex.Invoke((Action)(() => lblNCWPIndex.Text = "NA"));  //index of actual WP
1190
            lblNCWPCount.Invoke((Action)(() => lblNCWPCount.Text = "NA"));  //count of items in WP list
2233 - 1191
        }
1192
        /// <summary>
1193
        /// one time query of the OSD Menue with pagenumber
1194
        /// </summary>
1195
        /// <param name="iMenue">Menue page</param>
1196
        void _OSDMenue(int iMenue)
1197
        {
1198
            if (simpleSerialPort.Port.IsOpen)
1199
            {
1200
                if (iMenue > iOSDMax)
1201
                    iMenue = 0;
1202
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1203
                byte[] bytes = FlightControllerMessage.CreateMessage('l', 0, new byte[1] { (byte)iMenue });
1204
                serialStream.Write(bytes, 0, bytes.Length);
1205
            }
1206
            else
1207
                Log(LogMsgType.Error, "NOT CONNECTED!");
1208
 
1209
        }
1210
        /// <summary>
1211
        /// call the OSDMenue and start autorefresh
1212
        ///  usually by sending a menuekey
1213
        /// 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)
1214
        /// therefore the value has to be negative (inverted) in order to distinguish from old (2 line) menuestyle
1215
        /// and must not have any bits of the menue keys 0x1 0x2 0x4 0x8 (0x10?) --> 0x20 = -33
1216
        /// </summary>
1217
        void _OSDMenueAutoRefresh()
1218
        {
1219
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)(-33)),OSDInterval });
1220
        }
1221
        void _OSDMenueAutoRefresh(byte key)
1222
        {
1223
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)~key), OSDInterval });
1224
        }
1225
        /// <summary>
1226
        /// initialize the OSD menue combobox
1227
        /// combox is filled by numbers from 0 to max pagenumber
1228
        /// </summary>
1229
        void _initOSDCB()
1230
        {
1231
            _bCBInit = true;
1232
            if(iOSDMax == 0)
1233
            {
1234
                _OSDMenue(0);
1235
                Thread.Sleep(10);
1236
            }
1237
            cbOSD.Invoke((Action)(()=>cbOSD.Items.Clear()));
1238
            for(int i = 0; i <= iOSDMax;i++)
1239
            {
1240
                cbOSD.Invoke((Action)(() => cbOSD.Items.Add(i)));
1241
            }
1242
            cbOSD.Invoke((Action)(() => cbOSD.SelectedItem = iOSDPage));
1243
            _bCBInit = false;
1244
        }
2259 - 1245
        /// <summary>
1246
        /// initialize the datatables
1247
        /// with columnnames etc
1248
        /// </summary>
1249
        void _dataTablesInit()
1250
        {
1251
            dtAnalog.Columns.Add("ID");
1252
            dtAnalog.Columns.Add("Value");
1253
            dataGridView1.DataSource = dtAnalog;
1254
 
1255
            dtMotors1.Columns.Add("#");
1256
            dtMotors1.Columns.Add("Current");
1257
            dtMotors1.Columns.Add("Temp");
1258
            dtMotors2.Columns.Add("#");
1259
            dtMotors2.Columns.Add("Current");
1260
            dtMotors2.Columns.Add("Temp");
1261
            dgvMotors1.DataSource = dtMotors1;
1262
            dgvMotors2.DataSource = dtMotors2;
1263
            _initDTMotors();
1264
            dgvMotors1.Columns[0].Width = 24;
1265
            dgvMotors1.Columns[1].Width = 74;
1266
            dgvMotors1.Columns[2].Width = 74;
1267
            dgvMotors2.Columns[0].Width = 24;
1268
            dgvMotors2.Columns[1].Width = 74;
1269
            dgvMotors2.Columns[2].Width = 74;
1270
 
1271
            dtWaypoints.Columns.Add("Index");
1272
            dtWaypoints.Columns.Add("Type");
1273
            dtWaypoints.Columns.Add("Name");
1274
            dtWaypoints.Columns.Add("Latitude");
1275
            dtWaypoints.Columns.Add("Longitude");
1276
            dtWaypoints.Columns.Add("Altitude");
1277
            dtWaypoints.Columns.Add("Heading");
1278
            dtWaypoints.Columns.Add("Speed");
1279
            dtWaypoints.Columns.Add("Altitude rate");
1280
            dtWaypoints.Columns.Add("Tol.radius");
1281
            dtWaypoints.Columns.Add("Hold time");
1282
            dtWaypoints.Columns.Add("AutoTrigger");
1283
            dtWaypoints.Columns.Add("Cam angle");
1284
            dtWaypoints.Columns.Add("Event");
1285
            dtWaypoints.Columns.Add("Eventchan. Val.");
1286
            dtWaypoints.Columns.Add("Status");
1287
            dgvWP.DataSource = dtWaypoints;
1288
        }
1289
        /// <summary>
1290
        /// read settings from ini-file
1291
        /// </summary>
2233 - 1292
        void _readIni()
1293
        {
1294
            if (!File.Exists(filePath + "\\MKLiveViewSettings.ini"))
1295
                _writeIni();
1296
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
1297
            ini.path = filePath + "\\MKLiveViewSettings.ini";
1298
 
1299
            string sVal = ini.IniReadValue("default", "AutorefreshDebugData");
1300
            _debugDataAutorefresh = Convert.ToBoolean(sVal);
1301
            sVal = ini.IniReadValue("default", "AutorefreshNavCtrlData");
1302
            _navCtrlDataAutorefresh = Convert.ToBoolean(sVal);
1303
            sVal = ini.IniReadValue("default", "AutorefreshBLCtrlData");
1304
            _blctrlDataAutorefresh = Convert.ToBoolean(sVal);
1305
            sVal = ini.IniReadValue("default", "AutorefreshOSDData");
1306
            _OSDAutorefresh = Convert.ToBoolean(sVal);
1307
 
1308
            sVal = ini.IniReadValue("default", "IntervalDebugData");
1309
            debugInterval = (byte)Convert.ToInt16(sVal);
1310
            sVal = ini.IniReadValue("default", "IntervalNavCtrlData");
1311
            navctrlInterval = (byte)Convert.ToInt16(sVal);
1312
            sVal = ini.IniReadValue("default", "IntervalBLCtrlData");
1313
            blctrlInterval = (byte)Convert.ToInt16(sVal);
1314
            sVal = ini.IniReadValue("default", "IntervalOSDData");
1315
            OSDInterval = (byte)Convert.ToInt16(sVal);
2257 - 1316
            for(int i = 0; i < 12; i++)
1317
            {
1318
                sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "Val");
1319
                if(sVal != "")
1320
                    serChan[i] = Convert.ToInt16(sVal);
1321
                sVal = ini.IniReadValue("serial", "ch" + i.ToString() + "Title");
1322
                if(sVal != "")
1323
                    serChanTitle[i] = sVal;
1324
            }
2233 - 1325
        }
2259 - 1326
        /// <summary>
1327
        /// save settings to ini-file
1328
        /// </summary>
2233 - 1329
        void _writeIni()
1330
        {
1331
 
1332
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
1333
            ini.path = filePath + "\\MKLiveViewSettings.ini";
1334
 
1335
            ini.IniWriteValue("default", "AutorefreshDebugData", _debugDataAutorefresh ? "true":"false");
1336
            ini.IniWriteValue("default", "AutorefreshNavCtrlData", _navCtrlDataAutorefresh ? "true":"false");
1337
            ini.IniWriteValue("default", "AutorefreshBLCtrlData", _blctrlDataAutorefresh ? "true":"false");
1338
            ini.IniWriteValue("default", "AutorefreshOSDData", _OSDAutorefresh ? "true":"false");
1339
 
1340
            ini.IniWriteValue("default", "IntervalDebugData", debugInterval.ToString());
1341
            ini.IniWriteValue("default", "IntervalNavCtrlData", navctrlInterval.ToString());
1342
            ini.IniWriteValue("default", "IntervalBLCtrlData", blctrlInterval.ToString());
1343
            ini.IniWriteValue("default", "IntervalOSDData", OSDInterval.ToString());
2257 - 1344
 
1345
            for (int i = 0; i < 12; i++)
1346
            {
1347
                ini.IniWriteValue("serial", "ch" + i.ToString() + "Val", serChan[i].ToString());
1348
                ini.IniWriteValue("serial", "ch" + i.ToString() + "Title", serChanTitle[i]);
1349
            }
1350
 
2233 - 1351
        }
1352
 
2250 - 1353
        /// <summary>
1354
        /// initialize the 2 datatables for motor values
1355
        /// dtMotors1 - motor 1 - 4
1356
        /// dtMotors2 - motor 5 - 8
1357
        /// DataGridView dgvMotors1/2 are bound to dtMotors1/2 
1358
        /// </summary>
1359
        void _initDTMotors()
1360
        {
1361
            for(int i = 0; i < 4; i++)
1362
            {
1363
                if (dtMotors1.Rows.Count < 4)
1364
                    dtMotors1.Rows.Add((i + 1).ToString(), "NA", "NA");
1365
                else
1366
                {
1367
                    dtMotors1.Rows[i].SetField(1, "NA");
1368
                    dtMotors1.Rows[i].SetField(2, "NA");
1369
                }
1370
                if (dtMotors2.Rows.Count < 4)
1371
                    dtMotors2.Rows.Add((i + 5).ToString(), "NA", "NA");
1372
                else
1373
                {
1374
                    dtMotors2.Rows[i].SetField(1, "NA");
1375
                    dtMotors2.Rows[i].SetField(2, "NA");
1376
                }
1377
            }
1378
            dgvMotors1.Invoke((Action)(() => dgvMotors1.Refresh()));
1379
            dgvMotors2.Invoke((Action)(() => dgvMotors2.Refresh()));
1380
        }
1381
 
1382
        /// <summary>
1383
        /// Convert decimal degrees to degrees, minutes, seconds, milliseconds 
1384
        /// </summary>
1385
        /// <param name="coord">the degree value as double</param>
1386
        /// <returns>0° 0' 0,0"</returns>
1387
        string _convertDegree(double coord)
1388
        {
1389
            //double minutes = (degree - Math.Floor(degree)) * 60.0;
1390
            //double seconds = (minutes - Math.Floor(minutes)) * 60.0;
1391
            //double tenths = (seconds - Math.Floor(seconds)) * 10.0;
1392
            //// get rid of fractional part
1393
            //minutes = Math.Floor(minutes);
1394
            //seconds = Math.Floor(seconds);
1395
            //tenths = Math.Floor(tenths);
1396
 
1397
 
1398
            //int sec = (int)Math.Round(coord * 3600);
1399
            //int deg = sec / 3600;
1400
            //sec = Math.Abs(sec % 3600);
1401
            //int min = sec / 60;
1402
            //sec %= 60;
1403
 
1404
            var ts = TimeSpan.FromHours(Math.Abs(coord));
1405
            double deg = Math.Sign(coord) * Math.Floor(ts.TotalHours);
1406
            int min = ts.Minutes;
1407
            int sec = ts.Seconds;
1408
            int milli = ts.Milliseconds;
1409
 
1410
            return deg.ToString("0° ") + min.ToString("0") + "' " + sec.ToString("0") + "," + milli.ToString() + "\"";
1411
        }
2257 - 1412
        /// <summary>
1413
        /// Clear the line in the  errorlog window 
1414
        /// containing the error string when error has ceased
1415
        /// </summary>
1416
        /// <param name="s">substring of errrormessage</param>
2254 - 1417
        void _clearErrorLog(string s)
1418
        {
1419
            rtfError.Invoke((Action)(() =>
1420
            {
1421
                if (rtfError.Text.Contains(s))
1422
                {
1423
                    int iLength = 0;
1424
                    int iStart = rtfError.Text.IndexOf(s);
1425
                    int iEnd = rtfError.Text.IndexOf('\n', iStart);
1426
                    if (iEnd > 0)
1427
                    {
1428
                        iLength = iEnd + 1;
1429
                        int iHttp = rtfError.Text.IndexOf("http", iEnd);
1430
                        if (iHttp == iLength)
1431
                        {
1432
                            int iEnd2 = rtfError.Text.IndexOf('\n', iLength);
1433
                            if (iEnd2 > iLength)
1434
                            {
1435
                                iLength = iEnd2 + 1;
1436
                                rtfError.Select(iStart, iLength);
1437
                                rtfError.SelectedText = string.Empty;
1438
                                if(rtfError.Text.Length < 2) _bErrorLog = false;
1439
                            }
1440
 
1441
                        }
1442
                        else
1443
                        {
1444
                            rtfError.Select(iStart, iLength);
1445
                            rtfError.SelectedText = string.Empty;
1446
                            if(rtfError.Text.Length < 2) _bErrorLog = false;
1447
                        }
1448
                    }
1449
                }
1450
            }));
1451
 
1452
        }
2257 - 1453
        /// <summary>
1454
        /// request the Waypoint at index
1455
        /// </summary>
1456
        /// <param name="index"></param>
1457
        void _getpWP(int index)
1458
        {
1459
            if (simpleSerialPort.Port.IsOpen)
1460
            {
1461
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1462
                byte[] bytes = FlightControllerMessage.CreateMessage('x', 2, new byte[1] { (byte)index });
1463
                serialStream.Write(bytes, 0, bytes.Length);
1464
            }
1465
            else
1466
                Log(LogMsgType.Error, "NOT CONNECTED!");
1467
 
1468
        }
1469
        /// <summary>
1470
        /// Sending the serial channel values
1471
        /// </summary>
1472
        void _sendSerialData()
1473
        {
1474
            byte[] serData = new byte[12];
1475
            for(int i = 0; i < 12; i++)
1476
            {
1477
                serData[i] = unchecked((byte)(serChan[i] - 127));
1478
            }
1479
            _sendControllerMessage('y', 1, serData);
1480
        }
2259 - 1481
        /// <summary>
1482
        /// init the controls for displaying
1483
        /// and setting serial control channels
1484
        /// </summary>
2257 - 1485
        void _initSerialCtrl()
1486
        {
1487
            trckbarSerial1.Value = serChan[0];
1488
            textBoxSerial1.Text = serChanTitle[0];
1489
            lblTbSerial1.Text = serChan[0].ToString();
1490
            trckbarSerial2.Value = serChan[1];
1491
            textBoxSerial2.Text = serChanTitle[1];
1492
            lblTbSerial2.Text = serChan[1].ToString();
2259 - 1493
            trckbarSerial3.Value = serChan[2];
1494
            textBoxSerial3.Text = serChanTitle[2];
1495
            lblTbSerial3.Text = serChan[2].ToString();
1496
            trckbarSerial4.Value = serChan[3];
1497
            textBoxSerial4.Text = serChanTitle[3];
1498
            lblTbSerial4.Text = serChan[3].ToString();
2257 - 1499
        }
2233 - 1500
        #endregion functions
1501
 
1502
        #region buttons
1503
        private void buttonReset_Click(object sender, EventArgs e)
1504
        {
1505
            _resetCtrl();
1506
        }
1507
        private void btnVersion_Click(object sender, EventArgs e)
1508
        {
1509
            _getVersion();
1510
        }
1511
        private void btnAnalogLabels_Click(object sender, EventArgs e)
1512
        {
1513
            _getAnalogLabels(0);
1514
        }
1515
        private void btnDbgData_Click(object sender, EventArgs e)
1516
        {
1517
            _readDebugData(false); //onetime reading of debug data --> subscription lasts 4sec - this means you will receive data for 4 seconds
1518
        }
1519
        private void btnSaveLabels_Click(object sender, EventArgs e)
1520
        {
1521
            switch (_iCtrlAct)
1522
            {
1523
                case 1:
1524
                    fileName = "FCLabelTexts.txt";
1525
                    break;
1526
                case 2:
1527
                    fileName = "NCLabelTexts.txt";
1528
                    break;
1529
                default:
1530
                    fileName = "NCLabelTexts.txt";
1531
                    break;
1532
            }
1533
            if (sAnalogLabel[0] != null)
1534
            {
1535
                File.WriteAllLines(filePath + "\\" + fileName, sAnalogLabel);
1536
                Console.WriteLine("Names saved to file");
1537
                _loadLabelFile();
1538
            }
1539
            else
1540
                Log(LogMsgType.Warning, "there's no data -> read first from fc/nc!");
1541
        }
1542
        private void btnLoadLabels_Click(object sender, EventArgs e)
1543
        {
1544
            _assignLabelNames();
1545
        }
1546
        private void btnReadLabelFile_Click(object sender, EventArgs e)
1547
        {
1548
            _loadLabelFile();
1549
        }
1550
        private void btnSwitchFC_Click(object sender, EventArgs e)
1551
        {
1552
            _switchToFC();
1553
        }
1554
        private void btnSwitchNC_Click(object sender, EventArgs e)
1555
        {
1556
            _switchToNC();
1557
        }
1558
        private void btnReadDbgCont_Click(object sender, EventArgs e)
1559
        {
1560
            _readCont(!bReadContinously);
1561
        }
1562
        private void btnReadBLCtrl_Click(object sender, EventArgs e)
1563
        {
1564
 
1565
            if (_iCtrlAct == 2) _readBLCtrl(false);
1566
            else Log(LogMsgType.Warning, "only available when connected to NC");
1567
        }
1568
        private void btnGetNaviData_Click(object sender, EventArgs e)
1569
        {
1570
            if (_iCtrlAct == 2) _readNavData(false);
1571
            else Log(LogMsgType.Warning, "only available when connected to NC");
1572
        }
1573
        private void btnConn_Click(object sender, EventArgs e)
1574
        {
1575
            simpleSerialPort.Connect(!simpleSerialPort.Port.IsOpen);
1576
        }
1577
        private void button3_Click(object sender, EventArgs e)
1578
        {
1579
            _getVersion(1);
1580
        }
1581
        private void button4_Click(object sender, EventArgs e)
1582
        {
1583
            _getVersion(2);
1584
        }
1585
        private void btnOSD_Click(object sender, EventArgs e)
1586
        {
1587
            if (iOSDPage > iOSDMax)
1588
                iOSDPage = 0;
1589
            _OSDMenue(iOSDPage);
1590
        }
1591
        private void btnOSDForward_Click(object sender, EventArgs e)
1592
        {
1593
            iOSDPage++;
1594
            if (iOSDPage > iOSDMax)
1595
                iOSDPage = 0;
1596
 
1597
            _OSDMenue(iOSDPage);
1598
        }
1599
        private void btnOSDBackward_Click(object sender, EventArgs e)
1600
        {
1601
            iOSDPage--;
1602
            if (iOSDPage < 0)
1603
                iOSDPage = iOSDMax;
1604
 
1605
            _OSDMenue(iOSDPage);
1606
        }
1607
        private void btnOSDAuto_Click(object sender, EventArgs e)
1608
        {
1609
            _OSDMenueAutoRefresh();
1610
        }
1611
        /// call the OSDMenue with Key 0x8
1612
        private void btnOSDLeave_Click(object sender, EventArgs e)
1613
        {
1614
            _OSDMenueAutoRefresh(8);
1615
        }
1616
        /// call the OSDMenue with Key 0x4
1617
        private void btnOSDEnter_Click(object sender, EventArgs e)
1618
        {
1619
            _OSDMenueAutoRefresh(4);
1620
        }
2257 - 1621
        private void btnGetWP_Click(object sender, EventArgs e)
1622
        {
1623
            if(cbWPIndex.Items.Count >0)
1624
            _getpWP((int)cbWPIndex.SelectedItem);
1625
            else
1626
                _getpWP(1);
1627
        }
2233 - 1628
        #endregion buttons
2259 - 1629
        #region serial control channels - buttons & events
2257 - 1630
        private void tbSerial1_Scroll(object sender, EventArgs e)
1631
        {
1632
            lblTbSerial1.Text = trckbarSerial1.Value.ToString();
1633
            serChan[0] = trckbarSerial1.Value;
1634
            if (!_init) _sendSerialData();
1635
        }
1636
        private void textBoxSerial1_TextChanged(object sender, EventArgs e)
1637
        {
1638
            serChanTitle[0] = textBoxSerial1.Text;
1639
        }
1640
        private void btnSer1_0_Click(object sender, EventArgs e)
1641
        {
1642
            trckbarSerial1.Value = 0;
1643
        }
1644
        private void btnSer1_127_Click(object sender, EventArgs e)
1645
        {
1646
            trckbarSerial1.Value = 127;
1647
        }
1648
        private void btnSer1_254_Click(object sender, EventArgs e)
1649
        {
1650
            trckbarSerial1.Value = 254;
1651
        }
1652
        private void trckbarSerial1_ValueChanged(object sender, EventArgs e)
1653
        {
1654
            lblTbSerial1.Text = trckbarSerial1.Value.ToString();
1655
            serChan[0] = trckbarSerial1.Value;
1656
            if (!_init) _sendSerialData();
1657
        }
1658
        private void textBoxSerial2_TextChanged(object sender, EventArgs e)
1659
        {
2259 - 1660
            serChanTitle[1] = textBoxSerial2.Text;
2257 - 1661
        }
1662
        private void trckbarSerial2_ValueChanged(object sender, EventArgs e)
1663
        {
1664
            lblTbSerial2.Text = trckbarSerial2.Value.ToString();
1665
            serChan[1] = trckbarSerial2.Value;
1666
            if (!_init) _sendSerialData();
1667
        }
1668
        private void btnSer2_0_Click(object sender, EventArgs e)
1669
        {
1670
            trckbarSerial2.Value = 0;
1671
        }
1672
        private void btnSer2_127_Click(object sender, EventArgs e)
1673
        {
1674
            trckbarSerial2.Value = 127;
1675
        }
1676
        private void btnSer2_254_Click(object sender, EventArgs e)
1677
        {
1678
            trckbarSerial2.Value = 254;
1679
        }
2259 - 1680
        private void textBoxSerial3_TextChanged(object sender, EventArgs e)
1681
        {
1682
            serChanTitle[2] = textBoxSerial3.Text;
1683
        }
1684
        private void trckbarSerial3_ValueChanged(object sender, EventArgs e)
1685
        {
1686
            lblTbSerial3.Text = trckbarSerial3.Value.ToString();
1687
            serChan[2] = trckbarSerial3.Value;
1688
            if (!_init) _sendSerialData();
1689
        }
1690
        private void btnSer3_0_Click(object sender, EventArgs e)
1691
        {
1692
            trckbarSerial3.Value = 0;
1693
        }
1694
        private void btnSer3_127_Click(object sender, EventArgs e)
1695
        {
1696
            trckbarSerial3.Value = 127;
1697
        }
1698
        private void btnSer3_254_Click(object sender, EventArgs e)
1699
        {
1700
            trckbarSerial3.Value = 254;
1701
        }
1702
        private void textBoxSerial4_TextChanged(object sender, EventArgs e)
1703
        {
1704
            serChanTitle[3] = textBoxSerial4.Text;
1705
        }
1706
        private void trckbarSerial4_ValueChanged(object sender, EventArgs e)
1707
        {
1708
            lblTbSerial4.Text = trckbarSerial4.Value.ToString();
1709
            serChan[3] = trckbarSerial4.Value;
1710
            if (!_init) _sendSerialData();
1711
        }
1712
        private void btnSer4_0_Click(object sender, EventArgs e)
1713
        {
1714
            trckbarSerial4.Value = 0;
1715
        }
1716
        private void btnSer4_127_Click(object sender, EventArgs e)
1717
        {
1718
            trckbarSerial4.Value = 127;
1719
        }
1720
        private void btnSer4_254_Click(object sender, EventArgs e)
1721
        {
1722
            trckbarSerial4.Value = 254;
1723
        }
1724
        #endregion serial control channels
1725
 
2233 - 1726
    }
1727
    public class IniFile
1728
    {
1729
        public string path;
1730
 
1731
        [DllImport("kernel32")]
1732
        private static extern long WritePrivateProfileString(string section,
1733
          string key, string val, string filePath);
1734
 
1735
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
1736
        static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
1737
               uint nSize, string lpFileName);
1738
 
1739
        [DllImport("kernel32")]
1740
        private static extern int GetPrivateProfileString(string section,
1741
          string key, string def, StringBuilder retVal,
1742
          int size, string filePath);
1743
 
1744
        public IniFile(string INIPath)
1745
        {
1746
            path = INIPath;
1747
        }
1748
 
1749
        public void IniWriteValue(string Section, string Key, string Value)
1750
        {
1751
            WritePrivateProfileString(Section, Key, Value, this.path);
1752
        }
1753
 
1754
        public string IniReadValue(string Section, string Key)
1755
        {
1756
            StringBuilder temp = new StringBuilder(255);
1757
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
1758
            return temp.ToString();
1759
        }
1760
        //Ini_sections auslesen in String-Array
1761
        public string[] IniSectionNames()
1762
        {
1763
 
1764
            //  uint MAX_BUFFER = 32767;
1765
            uint MAX_BUFFER = 8388608;
1766
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
1767
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, this.path);
1768
            if (bytesReturned == 0)
1769
            {
1770
                Marshal.FreeCoTaskMem(pReturnedString);
1771
                return null;
1772
            }
1773
            string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
1774
            Marshal.FreeCoTaskMem(pReturnedString);
1775
            //use of Substring below removes terminating null for split
1776
            return local.Substring(0, local.Length - 1).Split('\0');
1777
 
1778
 
1779
        }
1780
    }
1781
    public static class ControlExtensions
1782
    {
1783
        /// <summary> 
1784
        /// Execute a threadsafe operation, when accessing a control via another thread 
1785
        /// action is a lamdaexpression
1786
        /// e.g. comboBox1.ExecuteThreadSafe(() => comboBox1.Enabled = true);
1787
        /// </summary>
1788
        /// <param name="control"> The control </param>
1789
        /// <param name="action"> The 'action' to perform </param>
1790
        public static void ExecuteThreadSafe(this Control control, Action action)
1791
        {
1792
            if (control.InvokeRequired)
1793
            {
1794
                control.BeginInvoke(action); //"BeginInvoke" is an async call -> threadsafety error when called to many times successively -> then take "Invoke"
1795
            }
1796
            else
1797
            {
1798
                action.Invoke();
1799
            }
1800
        }
1801
    }
1802
 
1803
}