Subversion Repositories Projects

Rev

Rev 2236 | 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
///============================================================================
38
 
39
using System;
40
using System.Data;
41
using System.Drawing;
42
using System.Text;
43
using System.Windows.Forms;
44
using System.IO;
45
using System.Threading;
46
using System.Diagnostics;
47
using System.Runtime.InteropServices;
48
 
49
namespace MKLiveView
50
{
51
    public partial class MainForm : Form
52
    {
2250 - 53
        String[] NC_Error = new string[44]
54
        {
55
            "No Error",
56
            "FC not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A1_.22FC_not_compatible_.22",
57
            "MK3Mag not compatible" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A2_.22MK3Mag_not_compatible_.22",
58
            "no FC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A3_.22no_FC_communication_.22",
59
            "no compass communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A4_.22no_compass_communication_.22",
60
            "no GPS communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A5_.22no_GPS_communication_.22",
61
            "bad compass value" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A6_.22bad_compass_value.22",
62
            "RC Signal lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A7_.22RC_Signal_lost_.22",
63
            "FC spi rx error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A8_.22FC_spi_rx_error_.22",
64
            "ERR: no NC communication" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A9:_.22ERR:_no_NC_communication.22",
65
            "ERR: FC Nick Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A10_.22ERR:_FC_Nick_Gyro.22",
66
            "ERR: FC Roll Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A11_.22ERR:_FC_Roll_Gyro.22",
67
            "ERR: FC Yaw Gyro" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A12_.22ERR:_FC_Yaw_Gyro.22",
68
            "ERR: FC Nick ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A13_.22ERR:_FC_Nick_ACC.22",
69
            "ERR: FC Roll ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A14_.22ERR:_FC_Roll_ACC.22",
70
            "ERR: FC Z-ACC" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A15_.22ERR:_FC_Z-ACC.22",
71
            "ERR: Pressure sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A16_.22ERR:_Pressure_sensor.22",
72
            "ERR: FC I2C" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A17_.22ERR:_FC_I2C.22",
73
            "ERR: Bl Missing" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A18_.22ERR:_Bl_Missing.22",
74
            "Mixer Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A19_.22Mixer_Error.22",
75
            "FC: Carefree Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A20_.22FC:_Carefree_Error.22",
76
            "ERR: GPS lost" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A21_.22ERR:_GPS_lost.22",
77
            "ERR: Magnet Error" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A22_.22ERR:_Magnet_Error.22",
78
            "Motor restart" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A23_.22Motor_restart.22",
79
            "BL Limitation" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A24_.22BL_Limitation.22",
80
            "Waypoint range" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A25_.22Waypoint_range.22",
81
            "ERR:No SD-Card" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A26_.22ERR:No_SD-Card.22",
82
            "ERR:SD Logging aborted" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A27_.22ERR:SD_Logging_aborted.22",
83
            "ERR:Flying range!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A28_.22ERR:Flying_range.21.22",
84
            "ERR:Max Altitude" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A29_.22ERR:Max_Altitude.22",
85
            "No GPS Fix" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A30_.22No_GPS_Fix.22",
86
            "compass not calibrated" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A31_.22compass_not_calibrated.22",
87
            "ERR:BL selftest" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A32_.22ERR:BL_selftest.22",
88
            "no ext. compass" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A33_.22no_ext._compass.22",
89
            "compass sensor" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A34_.22compass_sensor.22",
90
            "FAILSAFE pos.!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A35_.22FAILSAFE_pos..21__.22",
91
            "ERR:Redundancy" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A36_.22ERR:Redundancy__.22",
92
            "Redundancy test" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A37_.22Redundancy_test_.22",
93
            "GPS Update rate" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A38_.22GPS_Update_rate.22",
94
            "ERR:Canbus" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A39_.22ERR:Canbus.22",
95
            "ERR: 5V RC-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A40_.22ERR:_5V_RC-Supply.22",
96
            "ERR:Power-Supply" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A41_.22ERR:Power-Supply.22",
97
            "ACC not calibr." + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A42_.22ACC_not_calibr..22",
98
            "ERR:Parachute!" + Environment.NewLine + "http://wiki.mikrokopter.de/ErrorCodes#A43_.22ERR:Parachute.21.22"
99
        };
2233 - 100
 
101
        [FlagsAttribute]
102
        enum NC_HWError0 : short
103
        {
104
            None = 0,
105
            SPI_RX = 1,
106
            COMPASS_RX = 2,
107
            FC_INCOMPATIBLE = 4,
108
            COMPASS_INCOMPATIBLE = 8,
109
            GPS_RX = 16,
110
            COMPASS_VALUE = 32
111
        };
112
        [FlagsAttribute]
113
        enum FC_HWError0 : short
114
        {
115
            None = 0,
116
            GYRO_NICK = 1,
117
            GYRO_ROLL = 2,
118
            GYRO_YAW = 4,
119
            ACC_NICK = 8,
120
            ACC_ROLL = 16,
121
            ACC_TOP = 32,
122
            PRESSURE = 64,
123
            CAREFREE = 128
124
        };
125
        [FlagsAttribute]
126
        enum FC_HWError1 : short
127
        {
128
            None = 0,
129
            I2C = 1,
130
            BL_MISSING = 2,
131
            SPI_RX = 4,
132
            PPM = 8,
133
            MIXER = 16,
134
            RC_VOLTAGE = 32,
135
            ACC_NOT_CAL = 64,
136
            RES3 = 128
137
        };
138
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
139
        // Various colors for logging info
140
        private Color[] LogMsgTypeColor = { Color.FromArgb(43, 145, 175), Color.Green, Color.Black, Color.Orange, Color.Red };
141
 
142
        string[] sAnalogLabel = new string[32];
143
        string[] sAnalogData = new string[32];
144
        bool bReadContinously = false;
145
        bool check_HWError = false;
146
        bool _bCBInit = true;
147
        bool _init = true;
148
        bool _debugDataAutorefresh = true;
149
        bool _navCtrlDataAutorefresh = true;
150
        bool _blctrlDataAutorefresh = true;
151
        bool _OSDAutorefresh = true;
152
        int crcError = 0;
153
        int iLableIndex = 0;
154
        string filePath = Directory.GetCurrentDirectory();
155
        string fileName = "NCLabelTexts.txt";
156
        int _iCtrlAct = 0;
157
        int _iLifeCounter = 0;
158
        int iOSDPage = 0;
159
        int iOSDMax = 0;
160
        /// <summary>
161
        /// interval for sending debugdata (multiplied by 10ms)
162
        /// </summary>
163
        byte debugInterval = 25; //(=> 250ms)
164
        /// <summary>
165
        /// interval for sending BL-CTRL status (multiplied by 10ms)
166
        /// </summary>
167
        byte blctrlInterval = 45;
168
        /// <summary>
169
        /// interval for sending NAV-CTRL status (multiplied by 10ms)
170
        /// </summary>
171
        byte navctrlInterval = 80;
172
        /// <summary>
173
        /// interval for sending OSD page update (multiplied by 10ms)
174
        /// </summary>
175
        byte OSDInterval = 85;
176
        /// <summary>
177
        /// datatable for the debug data array - displayed on settings tabpage in datagridview
178
        /// </summary>
179
        DataTable dtAnalog = new DataTable();
2250 - 180
 
181
        DataTable dtMotors1 = new DataTable();
182
        DataTable dtMotors2 = new DataTable();
183
 
2233 - 184
        public MainForm()
185
        {
186
            InitializeComponent();
187
            _readIni();
188
            dtAnalog.Columns.Add("ID");
189
            dtAnalog.Columns.Add("Value");
190
            dataGridView1.DataSource = dtAnalog;
2250 - 191
            dtMotors1.Columns.Add("#");
192
            dtMotors1.Columns.Add("Current");
193
            dtMotors1.Columns.Add("Temp");
194
            dtMotors2.Columns.Add("#");
195
            dtMotors2.Columns.Add("Current");
196
            dtMotors2.Columns.Add("Temp");
197
            dgvMotors1.DataSource = dtMotors1;
198
            dgvMotors2.DataSource = dtMotors2;
199
            _initDTMotors();
200
            dgvMotors1.Columns[0].Width = 24;
201
            dgvMotors1.Columns[1].Width = 74;
202
            dgvMotors1.Columns[2].Width = 74;
203
            dgvMotors2.Columns[0].Width = 24;
204
            dgvMotors2.Columns[1].Width = 74;
205
            dgvMotors2.Columns[2].Width = 74;
2233 - 206
            simpleSerialPort.PortClosed += SimpleSerialPort_PortClosed;
207
            simpleSerialPort.PortOpened += SimpleSerialPort_PortOpened;
208
            simpleSerialPort.DataReceived += processMessage;
209
            chkbAutoBL.Checked = _blctrlDataAutorefresh;
210
            chkbAutoDbg.Checked = _debugDataAutorefresh;
211
            chkbAutoNav.Checked = _navCtrlDataAutorefresh;
212
            chkbAutoOSD.Checked = _OSDAutorefresh;
213
            labelTimingDebug.Text = (debugInterval * 10).ToString();
214
            labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
215
            labelTimingNAV.Text = (navctrlInterval * 10).ToString();
216
            labelTimingOSD.Text = (OSDInterval * 10).ToString();
217
            tabControl1.TabPages.Remove(tabPageTesting);
218
        }
219
        #region events
220
        private void MainForm_Shown(object sender, EventArgs e)
221
        {
222
            _loadLabelNames();
223
            _init = false;
2250 - 224
            splitContainer1.SplitterDistance = 514;
2233 - 225
        }
226
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
227
        {
228
            _writeIni();
229
        }
230
        private void SimpleSerialPort_PortOpened()
231
        {
232
            btnConn.Invoke((Action)(() => btnConn.BackColor = Color.FromArgb(192, 255, 192)));
233
            btnConn.Invoke((Action)(() => btnConn.Text = "close" + Environment.NewLine + "serial port"));
234
            _getVersion();
235
            Thread.Sleep(100);
236
            _OSDMenue(0);
237
           // _readCont(true);
238
        }
239
        private void SimpleSerialPort_PortClosed()
240
        {
241
            btnConn.Invoke((Action)(() => btnConn.BackColor = Color.FromArgb(224, 224, 224)));
242
            btnConn.Invoke((Action)(() => btnConn.Text = "open" + Environment.NewLine + "serial port"));
243
            _readCont(false);
244
        }
245
        /// <summary>
246
        /// timer for refreshing subscription of subscribed data
247
        /// query lifecounter for connection failure
248
        /// </summary>
249
        private void timer1_Tick(object sender, EventArgs e)
250
        {
251
            if(bReadContinously)
252
            {
253
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
254
 
2250 - 255
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
2233 - 256
 
257
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
258
                check_HWError = true;
259
                _getVersion();
260
                Thread.Sleep(10);
261
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); }
262
                if (_iLifeCounter > 0)
263
                {
264
                    lblLifeCounter.BackColor = Color.FromArgb(0, 224, 0);
265
                    _iLifeCounter = 0;
266
                }
267
                else
268
                {
269
                    Log(LogMsgType.Error, "No communication to NC/FC!");
270
                    lblLifeCounter.BackColor = Color.FromArgb(224, 0, 0);
271
                }
272
            }
273
        }
274
        private void cbOSD_SelectedIndexChanged(object sender, EventArgs e)
275
        {
276
            if (!_bCBInit && cbOSD.SelectedIndex > -1)
277
                _OSDMenue(cbOSD.SelectedIndex);
278
        }
279
        private void chkbAutoDbg_CheckedChanged(object sender, EventArgs e)
280
        {
281
            if(!_init) _debugDataAutorefresh = chkbAutoDbg.Checked;
282
        }
283
        private void chkbAutoNav_CheckedChanged(object sender, EventArgs e)
284
        {
285
            if (!_init) _navCtrlDataAutorefresh = chkbAutoNav.Checked;
286
        }
287
        private void chkbAutoBL_CheckedChanged(object sender, EventArgs e)
288
        {
289
            if (!_init) _blctrlDataAutorefresh = chkbAutoBL.Checked;
290
        }
291
        private void chkbAutoOSD_CheckedChanged(object sender, EventArgs e)
292
        {
293
            if (!_init) _OSDAutorefresh = chkbAutoOSD.Checked;
294
        }
295
        private void cbTimingDebug_SelectedIndexChanged(object sender, EventArgs e)
296
        {
297
            if (cbTimingDebug.SelectedIndex > -1)
298
            {
299
                debugInterval = (byte)(Convert.ToInt16(cbTimingDebug.SelectedItem) / 10);
300
                labelTimingDebug.Text = (debugInterval * 10).ToString();
301
            }
302
        }
303
        private void cbTimingNAV_SelectedIndexChanged(object sender, EventArgs e)
304
        {
305
            if (cbTimingNAV.SelectedIndex > -1)
306
            {
307
                navctrlInterval = (byte)(Convert.ToInt16(cbTimingNAV.SelectedItem) / 10);
308
                labelTimingNAV.Text = (navctrlInterval * 10).ToString();
309
            }
310
        }
311
        private void cbTimingBLCTRL_SelectedIndexChanged(object sender, EventArgs e)
312
        {
313
            if (cbTimingBLCTRL.SelectedIndex > -1)
314
            {
315
                blctrlInterval = (byte)(Convert.ToInt16(cbTimingBLCTRL.SelectedItem) / 10);
316
                labelTimingBLCTRL.Text = (blctrlInterval * 10).ToString();
317
            }
318
        }
319
        private void cbTimingOSD_SelectedIndexChanged(object sender, EventArgs e)
320
        {
321
            if (cbTimingOSD.SelectedIndex > -1)
322
            {
323
                OSDInterval = (byte)(Convert.ToInt16(cbTimingOSD.SelectedItem) / 10);
324
                labelTimingOSD.Text = (OSDInterval * 10).ToString();
325
            }
326
        }
327
        #endregion events
328
 
329
        /// <summary> Log data to the terminal window. </summary>
330
        /// <param name="msgtype"> The type of message to be written. </param>
331
        /// <param name="msg"> The string containing the message to be shown. </param>
332
        private void Log(LogMsgType msgtype, string msg)
333
        {
334
            rtfTerminal.Invoke(new EventHandler(delegate
335
            {
336
                if (rtfTerminal.Lines.Length >= 1000)   //Wenn Terminal mehr als 1000 Zeilen hat
337
                    rtfTerminal.Select(42, (500 * 129));     //500 löschen
338
                rtfTerminal.Select(rtfTerminal.Text.Length, 0);
339
                rtfTerminal.SelectedText = string.Empty;
340
                rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Regular);
341
                rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
342
                rtfTerminal.AppendText(msg + Environment.NewLine);
343
                rtfTerminal.ScrollToCaret();
344
            }));
345
        }
346
        /// <summary> display the OSD text in 4 lines à 20 chars </summary>
347
        /// <param name="msgtype"> The type of message to be written. </param>
348
        /// <param name="msg"> The string containing the message to be shown. </param>
349
        private void OSD(LogMsgType msgtype, string msg)
350
        {
351
            rtfOSD.Invoke(new EventHandler(delegate
352
            {
353
                if (rtfOSD.Lines.Length > 4)
354
                    rtfOSD.Clear();
355
                rtfOSD.Select(rtfOSD.Text.Length,0);
356
                rtfOSD.SelectedText = string.Empty;
357
                rtfOSD.SelectionFont = new Font(rtfOSD.SelectionFont, FontStyle.Regular);
358
                rtfOSD.SelectionColor = LogMsgTypeColor[(int)msgtype];
359
                rtfOSD.AppendText(msg + Environment.NewLine);
360
                if (rtfOSD.Text.IndexOf("ERR") > 0)
361
                {
362
                    rtfOSD.Select(rtfOSD.Text.IndexOf("ERR"), 40);
363
                    rtfOSD.SelectionColor = LogMsgTypeColor[(int)LogMsgType.Error];
364
                }
365
            }));
366
        }
367
        private void ErrorLog(LogMsgType msgtype, string msg)
368
        {
369
            rtfError.Invoke(new EventHandler(delegate
370
            {
371
                if (rtfError.Lines.Length > 4)
372
                    rtfError.Clear();
373
                rtfError.Focus();
374
                rtfError.Select(rtfError.Text.Length, 0);
375
                rtfError.SelectedText = string.Empty;
376
                rtfError.SelectionFont = new Font(rtfError.SelectionFont, FontStyle.Regular);
377
                rtfError.SelectionColor = LogMsgTypeColor[(int)msgtype];
378
                rtfError.AppendText(msg + Environment.NewLine);
379
 
380
            }));
381
        }
382
 
383
        #region functions        
384
 
2250 - 385
        #region processing received data
386
        /// <summary> Processing the messages and displaying them in the according form controls 
387
        /// function called by simpleSerialPort.DataReceived event
388
        /// </summary>
2233 - 389
        /// <param name="message"> message bytearray recieved by SimpleSerialPort class </param>
390
        private void processMessage(byte[] message)
391
        {
392
            if (message.Length > 0)
393
            {
394
                _iLifeCounter++;
395
                //Log(LogMsgType.Incoming, BitConverter.ToString(message));
396
                //Log(LogMsgType.Incoming, message.Length.ToString());
397
                string s = new string(ASCIIEncoding.ASCII.GetChars(message, 0, message.Length));
398
                char cmdID;
399
                byte adr;
400
                byte[] data;
401
                if (message[0] != '#')
402
                    Log(LogMsgType.Normal, s.Trim('\0', '\n','\r'));
403
                //Debug.Print(s);
404
                else
405
                {
406
                    FlightControllerMessage.ParseMessage(message, out cmdID, out adr, out data);
407
 
408
                    if (adr == 255) { crcError++; }
409
                    else crcError = 0;
410
                    lblCRCErr.Invoke((Action)(() => lblCRCErr.Text = crcError.ToString()));
2250 - 411
                    //display the active controller (FC / NC) 
2233 - 412
                    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...???
413
                    {
414
                        _iCtrlAct = adr;
415
                        switch (adr)
416
                        {
417
                            case 1:
418
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "FC"));
419
                                lblNCCtrl.Invoke((Action)(() => lblNCCtrl.Text = "FC"));
420
                                _setFieldsNA(); //display fields NA for FC 
421
                                break;
422
                            case 2:
423
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "NC"));
424
                                lblNCCtrl.Invoke((Action)(() => lblNCCtrl.Text = "NC"));
425
                                break;
426
                            case 3:
427
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "MK3MAG"));
428
                                break;
429
                            case 4:
430
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "BL-CTRL"));
431
                                break;
432
                            default:
433
                                lblCtrl.Invoke((Action)(() => lblCtrl.Text = "...."));
434
                                break;
435
                        }
2250 - 436
                        _loadLabelNames();
2233 - 437
                    }
438
                   // else
439
                   //     Debug.Print("Address == 0?");
440
 
441
                    if (data != null && data.Length > 0)
442
                    {
443
                        s = new string(ASCIIEncoding.ASCII.GetChars(data, 1, data.Length - 1));
444
                        s = s.Trim('\0', '\n');
445
 
446
                        switch (cmdID)
447
                        {
2250 - 448
                            case 'A': //Label names
449
                                _processLabelNames(s);
2233 - 450
                                break;
451
 
2250 - 452
                            case 'D': //Debug data
453
                                _processDebugVals(adr,data);
2233 - 454
                                break;
455
 
2250 - 456
                            case 'V': //Version
457
                                _processVersion(adr, data);
2233 - 458
                                break;
459
 
2250 - 460
                            case 'K'://BL-CTRL data
461
                                _processBLCtrl(data);
2233 - 462
                                break;
463
 
464
                            case 'O': //NC Data
2250 - 465
                                _processNCData(data);
2233 - 466
                                break;
467
 
468
                            case 'E': //NC error-string
469
                                ErrorLog(LogMsgType.Error, "NC Error: " + s);
470
                                break;
471
 
2250 - 472
                            case 'L': //OSD Menue (called by pagenumber)
473
                                _processOSDSingle(data);
2233 - 474
                                break;
475
 
2250 - 476
                            case 'H': //OSD Menue (with autoupdate - called by Key)
477
                                _processOSDAuto(data);
2233 - 478
                                break;
479
 
480
                            //default:
481
                            //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
482
                            //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
483
                            //    break;
484
                        }
485
                    }
486
                    //else
487
                    //{
488
                    //    Log(LogMsgType.Incoming, "cmd: " + cmdID.ToString());
489
                    //    Log(LogMsgType.Incoming, BitConverter.ToString(data));
490
                    //}
491
                }
492
            }
493
        }
2250 - 494
        /// <summary>
495
        /// Analog label names 'A'
496
        /// each label name is returned as a single string 
497
        /// and added to string array sAnalogLabel[]
498
        /// and the datatable dtAnalog
499
        /// </summary>
500
        /// <param name="s">the label name</param>
501
        void _processLabelNames(string s)
502
        {
503
            if (iLableIndex < 32)
504
            {
505
                sAnalogLabel[iLableIndex] = s;
506
                if (dtAnalog.Rows.Count < 32)
507
                    dtAnalog.Rows.Add(s, "");
508
                else
509
                    dtAnalog.Rows[iLableIndex].SetField(0, s);
2233 - 510
 
2250 - 511
                _getAnalogLabels(iLableIndex + 1);
512
            }
513
            Debug.Print(s);
514
        }
515
        /// <summary>
516
        /// Debug values 'D'
517
        /// </summary>
518
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
519
        /// <param name="data">the received byte array to process</param>
520
        void _processDebugVals(byte adr,byte[] data)
521
        {
522
            if (data.Length == 66)
523
            {
524
                int[] iAnalogData = new int[32];
525
 
526
                int index = 0;
527
                Int16 i16 = 0;
528
                double dTemp = 0;
529
                for (int i = 2; i < 66; i += 2)
530
                {
531
                    i16 = data[i + 1];
532
                    i16 = (Int16)(i16 << 8);
533
                    iAnalogData[index] = data[i] + i16;
534
                    sAnalogData[index] = (data[i] + i16).ToString();
535
                    dtAnalog.Rows[index].SetField(1, sAnalogData[index]);
536
 
537
                    if (adr == 2) //NC
538
                    {
539
                        switch (index)
540
                        {
541
                            case 0: //pitch (German: nick)
542
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.pitch_angle = ((double)iAnalogData[index] / (double)10)));
543
                                lblNCPitch.Invoke((Action)(() => lblNCPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
544
                                break;
545
                            case 1: //roll
546
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.roll_angle = ((double)iAnalogData[index] / (double)10)));
547
                                lblNCRoll.Invoke((Action)(() => lblNCRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
548
                                break;
549
                            case 4: //altitude
550
                                lblNCAlt.Invoke((Action)(() => lblNCAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m")));
551
                                break;
552
                            case 7: //Voltage
553
                                lblNCVolt.Invoke((Action)(() => lblNCVolt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 V")));
554
                                break;
555
                            case 8: // Current
556
                                lblNCCur.Invoke((Action)(() => lblNCCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A")));
557
                                break;
558
                            case 10: //heading
559
                                lblNCCompass.Invoke((Action)(() => lblNCCompass.Text = sAnalogData[index] + "°"));
560
                                headingIndicator1.Invoke((Action)(() => headingIndicator1.SetHeadingIndicatorParameters(iAnalogData[index])));
561
                                break;
562
                            case 12: // SPI error
563
                                lblNCSPI.Invoke((Action)(() => lblNCSPI.Text = sAnalogData[index]));
564
                                break;
565
                            case 14: //i2c error
566
                                lblNCI2C.Invoke((Action)(() => lblNCI2C.Text = sAnalogData[index]));
567
                                break;
568
                            case 20: //Earthmagnet field
569
                                lblNCMF.Invoke((Action)(() => lblNCMF.Text = sAnalogData[index] + "%"));
570
                                break;
571
                            case 21: //GroundSpeed
572
                                lblNCGSpeed.Invoke((Action)(() => lblNCGSpeed.Text = ((double)iAnalogData[index] / (double)100).ToString("0.00 m/s")));
573
                                break;
574
                            case 28: //Distance East from saved home position -> calculate distance with distance N + height
575
                                dTemp = Math.Pow((double)iAnalogData[index], 2) + Math.Pow((double)iAnalogData[index - 1], 2);
576
                                dTemp = Math.Sqrt(dTemp) / (double)10; //'flat' distance from HP with N/E
577
                                                                       //  lblNCDist.Invoke((Action)(() => lblNCDist.Text = dTemp.ToString("0.00")));
578
                                dTemp = Math.Pow(dTemp, 2) + Math.Pow(((double)iAnalogData[4] / (double)10), 2); //adding 'height' into calculation
579
                                dTemp = Math.Sqrt(dTemp);
580
                                lblNCDistHP.Invoke((Action)(() => lblNCDistHP.Text = dTemp.ToString("0 m")));
581
                                break;
582
                            case 31: //Sats used
583
                                lblNCSat.Invoke((Action)(() => lblNCSat.Text = sAnalogData[index]));
584
                                break;
585
                        }
586
                    }
587
                    if (adr == 1) //FC
588
                    {
589
                        switch (index)
590
                        {
591
                            case 0: //pitch (German: nick)
592
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.pitch_angle = ((double)iAnalogData[index] / (double)10)));
593
                                lblNCPitch.Invoke((Action)(() => lblNCPitch.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
594
                                break;
595
                            case 1: //roll
596
                                artificialHorizon1.Invoke((Action)(() => artificialHorizon1.roll_angle = ((double)iAnalogData[index] / (double)10)));
597
                                lblNCRoll.Invoke((Action)(() => lblNCRoll.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0°")));
598
                                break;
599
                            case 5: //altitude
600
                                lblNCAlt.Invoke((Action)(() => lblNCAlt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 m")));
601
                                break;
602
                            case 8: //heading
603
                                lblNCCompass.Invoke((Action)(() => lblNCCompass.Text = sAnalogData[index] + "°"));
604
                                headingIndicator1.Invoke((Action)(() => headingIndicator1.SetHeadingIndicatorParameters(iAnalogData[index])));
605
                                break;
606
                            case 9: //Voltage
607
                                lblNCVolt.Invoke((Action)(() => lblNCVolt.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 V")));
608
                                break;
609
                            case 10: //Receiver quality
610
                                lblNCRC.Invoke((Action)(() => lblNCRC.Text = sAnalogData[index]));
611
                                break;
612
                            case 22: // Current
613
                                lblNCCur.Invoke((Action)(() => lblNCCur.Text = ((double)iAnalogData[index] / (double)10).ToString("0.0 A")));
614
                                break;
615
                            case 23: //capacity used
616
                                lblNCCap.Invoke((Action)(() => lblNCCap.Text = (iAnalogData[index]).ToString("0 mAh")));
617
                                break;
618
                            case 27: // SPI error
619
                                lblNCSPI.Invoke((Action)(() => lblNCSPI.Text = sAnalogData[index]));
620
                                break;
621
                            case 28: //i2c error
622
                                lblNCI2C.Invoke((Action)(() => lblNCI2C.Text = sAnalogData[index]));
623
                                break;
624
                        }
625
                    }
626
                    index++;
627
                }
628
            }
629
            else
630
                Debug.Print("wrong data-length (66): " + data.Length.ToString());
631
        }
632
        /// <summary>
633
        /// Version string 'V'
634
        /// </summary>
635
        /// <param name="adr">adress of the active controller (1-FC, 2-NC)</param>
636
        /// <param name="data">the received byte array to process</param>
637
        void _processVersion(byte adr,byte[] data)
638
        {
639
            if (data.Length == 12)
640
            {
641
                if (!check_HWError)
642
                {
643
                    string[] sVersionStruct = new string[10] { "SWMajor: ", "SWMinor: ", "ProtoMajor: ", "LabelTextCRC: ", "SWPatch: ", "HardwareError 1: ", "HardwareError 2: ", "HWMajor: ", "BL_Firmware: ", "Flags: " };
644
                    string sVersion = "";
645
                    //sbyte[] signed = Array.ConvertAll(data, b => unchecked((sbyte)b));
646
                    Log(LogMsgType.Warning, (adr == 1 ? "FC-" : "NC-") + "Version: ");
647
                    sVersion = "HW V" + (data[7] / 10).ToString() + "." + (data[7] % 10).ToString();
648
                    Log(LogMsgType.Incoming, sVersion);
649
                    sVersion = "SW V" + (data[0]).ToString() + "." + (data[1]).ToString() + ((char)(data[4] + 'a')).ToString();
650
                    Log(LogMsgType.Incoming, sVersion);
651
                    Log(LogMsgType.Incoming, "BL-Firmware: V" + (data[8] / 100).ToString() + "." + (data[8] % 100).ToString());
652
                }
653
                if (data[5] > 0) //error0 
654
                {
655
                    if (adr == 1)
656
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[5].ToString() + ": " + ((FC_HWError0)data[5]).ToString());
657
                    if (adr == 2)
658
                        ErrorLog(LogMsgType.Error, "NC - HW-Error " + data[5].ToString() + ": " + ((NC_HWError0)data[5]).ToString());
659
                }
660
                if (data[6] > 0) //error1 
661
                {
662
                    if (adr == 1)
663
                        ErrorLog(LogMsgType.Error, "FC - HW-Error " + data[6].ToString() + ": " + ((FC_HWError1)data[6]).ToString());
664
                    if (adr == 2)
665
                        ErrorLog(LogMsgType.Error, "NC - Unknown HW-ERROR: " + data[6].ToString()); //@moment NC has only one error field
666
                }
667
 
668
            }
669
            check_HWError = false;
670
        }
671
        /// <summary>
672
        /// BL-Ctrl data 'K'
673
        /// for FC you have to use a customized firmware
674
        /// </summary>
675
        /// <param name="data">the received byte array to process</param>
676
        void _processBLCtrl(byte[] data)
677
        {
678
            if (data.Length % 6 == 0) //data.Length up to 96 (16 motors x 6 byte data) --> new datastruct in FC -> not standard!
679
            {
680
                bool bAvailable = false;
681
                for (int i = 0; i < data.Length && data[i] < 8; i += 6) // data[i] < 8 --> at moment there are 8 display fields for motors
682
                {
683
 
684
                    if ((data[i + 4] & 128) == 128) //Status bit at pos 7 = 128 dec -- if true, motor is available
685
                        bAvailable = true;
686
                    else
687
                        bAvailable = false;
688
 
689
                    if (data[i] < 4)
690
                    {
691
                        if (bAvailable)
692
                        {
693
                            dtMotors1.Rows[data[i]].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
694
                            dtMotors1.Rows[data[i]].SetField(2, data[i + 2].ToString("0 °C"));
695
                        }
696
                        else
697
                        {
698
                            dtMotors1.Rows[data[i]].SetField(1, "NA");
699
                            dtMotors1.Rows[data[i]].SetField(2, "NA");
700
                        }
701
                    }
702
                    if (data[i] > 3 && data[i] < 8)
703
                    {
704
                        if (bAvailable)
705
                        {
706
                            dtMotors2.Rows[data[i] - 4].SetField(1, ((double)data[i + 1] / (double)10).ToString("0.0 A"));
707
                            dtMotors2.Rows[data[i] - 4].SetField(2, data[i + 2].ToString("0 °C"));
708
                        }
709
                        else
710
                        {
711
                            dtMotors2.Rows[data[i] - 4].SetField(1, "NA");
712
                            dtMotors2.Rows[data[i] - 4].SetField(2, "NA");
713
                        }
714
                    }
715
                }
716
            }
717
 
718
        }
719
        /// <summary>
720
        /// Navi-Ctrl data 'O'
721
        /// GPS-Position, capacatiy, flying time...
722
        /// </summary>
723
        /// <param name="data">the received byte array to process</param>
724
        void _processNCData(byte[] data)
725
        {
726
            int i_32, i_16, iVal;
727
            double d;
728
            i_32 = data[4];
729
            iVal = i_32 << 24;
730
            i_32 = data[3];
731
            iVal += i_32 << 16;
732
            i_32 = data[2];
733
            iVal += i_32 << 8;
734
            iVal += data[1];
735
            d = (double)iVal / Math.Pow(10, 7);
736
            lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = d.ToString("0.######°"))); //GPS-Position: Longitude in decimal degree
737
            //lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = _convertDegree(d))); //GPS-Position: Longitude in minutes, seconds
738
 
739
            i_32 = data[8];
740
            iVal = i_32 << 24;
741
            i_32 = data[7];
742
            iVal += i_32 << 16;
743
            i_32 = data[6];
744
            iVal += i_32 << 8;
745
            iVal += data[5];
746
            d = (double)iVal / Math.Pow(10, 7);
747
            lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = d.ToString("0.######°"))); //GPS-Position: Latitude in decimal degree
748
            //lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = _convertDegree(d))); //GPS-Position: Latitude in minutes, seconds
749
 
750
            i_16 = data[81];
751
            i_16 = (Int16)(i_16 << 8);
752
            iVal = data[80] + i_16;
753
            lblNCCap.Invoke((Action)(() => lblNCCap.Text = iVal.ToString() + " mAh")); //Capacity used
754
 
755
            i_16 = data[56];
756
            i_16 = (Int16)(i_16 << 8);
757
            iVal = data[55] + i_16;
758
            TimeSpan t = TimeSpan.FromSeconds(iVal);
759
            string Text = t.Hours.ToString("D2") + ":" + t.Minutes.ToString("D2") + ":" + t.Seconds.ToString("D2");
760
            lblNCFlTime.Invoke((Action)(() => lblNCFlTime.Text = Text.ToString())); //Flying time
761
 
762
            lblNCRC.Invoke((Action)(() => lblNCRC.Text = data[66].ToString())); //RC quality
763
            lblNCErrNmbr.Invoke((Action)(() => lblNCErrNmbr.Text = data[69].ToString()));   //NC Errornumber
764
            //if (data[69] > 0)
765
            //    _readNCError();
766
            //break;
767
            if (data[69] > 0 & data[69] < 44)
768
                ErrorLog(LogMsgType.Error, "NC Error [" + data[69].ToString() + "]: " + NC_Error[data[69]]);
769
 
770
        }
771
        /// <summary>
772
        /// OSD Menue 'L'
773
        /// single page called by pagenumber
774
        /// no autoupdate
775
        /// </summary>
776
        /// <param name="data">the received byte array to process</param>
777
        void _processOSDSingle(byte[] data)
778
        {
779
            if (data.Length == 84)
780
            {
781
                string sMessage = "";
782
                iOSDPage = data[0];
783
                iOSDMax = data[1];
784
                if (cbOSD.Items.Count != iOSDMax) _initOSDCB();
785
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 2, data.Length - 4));
786
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20));
787
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20));
788
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20));
789
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20));
790
                lblOSDPageNr.Invoke((Action)(() => lblOSDPageNr.Text = iOSDPage.ToString("[0]")));
791
 
792
            }
793
            else
794
                OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 84)");
795
 
796
        }
797
        /// <summary>
798
        /// OSD Menue 'H'
799
        /// called by keys (0x01,0x02,0x03,0x04)
800
        /// autoupdate
801
        /// </summary>
802
        /// <param name="data">the received byte array to process</param>
803
        void _processOSDAuto(byte[] data)
804
        {
805
            if (data.Length == 81)
806
            {
807
                string sMessage = "";
808
                sMessage = new string(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length - 1));
809
                OSD(LogMsgType.Incoming, sMessage.Substring(0, 20));
810
                OSD(LogMsgType.Incoming, sMessage.Substring(20, 20));
811
                OSD(LogMsgType.Incoming, sMessage.Substring(40, 20));
812
                OSD(LogMsgType.Incoming, sMessage.Substring(60, 20));
813
 
814
            }
815
            else
816
                OSD(LogMsgType.Incoming, "Wrong length: " + data.Length + " (should be 81)");
817
        }
818
        #endregion processing received data
819
 
2233 - 820
        /// <summary> send message to controller to request data
821
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
822
        /// </summary>
823
        /// <param name="CMDID"> the command ID </param>
824
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
825
        private void _sendControllerMessage(char CMDID, byte address)
826
        {
827
            if (simpleSerialPort.Port.IsOpen)
828
            {
829
                Stream serialStream = simpleSerialPort.Port.BaseStream;
830
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address);
831
                serialStream.Write(bytes, 0, bytes.Length);
832
 
833
            }
834
            else
835
                Log(LogMsgType.Error, "NOT CONNECTED!");
836
        }
837
        /// <summary> send message to controller to request data
838
        /// for detailed info see http://wiki.mikrokopter.de/en/SerialProtocol/
839
        /// </summary>
840
        /// <param name="CMDID"> the command ID </param>
841
        /// <param name="address"> the address of the controller: 0-any, 1-FC, 2-NC </param>
842
        /// <param name="data"> additional data for the request</param>
843
        private void _sendControllerMessage(char CMDID, byte address, byte[]data)
844
        {
845
            if (simpleSerialPort.Port.IsOpen)
846
            {
847
                Stream serialStream = simpleSerialPort.Port.BaseStream;
848
                byte[] bytes = FlightControllerMessage.CreateMessage(CMDID, address,data);
849
                serialStream.Write(bytes, 0, bytes.Length);
850
 
851
            }
852
            else
853
                Log(LogMsgType.Error, "NOT CONNECTED!");
854
        }
855
 
856
        /// <summary>
857
        /// read the analog-label names for the actual controller
858
        /// and load it into listbox
859
        /// </summary>
860
        void _loadLabelNames()
861
        {
862
            if (_iCtrlAct > 0 && _iCtrlAct < 3)
863
            {
864
                switch (_iCtrlAct)
865
                {
866
                    case 1:
867
                        sAnalogLabel = Properties.Resources.FCLabelTexts.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
868
                        break;
869
                    case 2:
870
                        sAnalogLabel = Properties.Resources.NCLabelTexts.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
871
                        break;
872
                }
873
                for (int i = 0; i < 32; i++)
874
                {
875
                    if (dtAnalog.Rows.Count < 32)
876
                        dtAnalog.Rows.Add(sAnalogLabel[i], "");
877
                    else
878
                        dtAnalog.Rows[i].SetField(0, sAnalogLabel[i]);
879
                }
880
                dataGridView1.Invoke((Action)(()=>dataGridView1.Refresh()));
881
            }
882
        }
883
        /// <summary>
884
        /// no longer used...
885
        /// read the analog-label textfile for the actual controller
886
        /// </summary>
887
         private void _loadLabelFile()
888
        {
889
            switch (_iCtrlAct)
890
            {
891
                case 1:
892
                    fileName = "FCLabelTexts.txt";
893
                    break;
894
                case 2:
895
                    fileName = "NCLabelTexts.txt";
896
                    break;
897
                //default:
898
                //    fileName = "NCLabelTexts.txt";
899
                //    break;
900
            }
901
 
902
            if (File.Exists(filePath + "\\" + fileName))
903
            {
904
                sAnalogLabel.Initialize();
905
                sAnalogLabel = File.ReadAllLines(filePath + "\\" + fileName);
906
                lbLabels.Invoke((Action)(() => lbLabels.Items.Clear()));
907
                lbLabels.Invoke((Action)(() => lbLabels.Update()));
908
                lbLabels.Invoke((Action)(() => lbLabels.Items.AddRange(sAnalogLabel)));
909
                Console.WriteLine("Names loaded from file");
910
                lblFileName.Invoke((Action)(() => lblFileName.Text = fileName));
911
            }
912
            else
913
            {
914
                _readCont(false);
915
                Log(LogMsgType.Error, "Label-file not found!");
916
                Log(LogMsgType.Error, "Please go to settings-tab and load the label texts from the copter control (FC & NC)");
917
                Log(LogMsgType.Error, "When done, you have to save the label texts with the 'save' button!");
918
            }
919
        }
920
        /// <summary>
921
        /// no longer used...
922
        /// assign the analog-label names from the textfile to the datatable
923
        /// 
924
        /// </summary>
925
        private void _assignLabelNames()
926
        {
927
            if (lbLabels.Items.Count == 32)
928
            {
929
                lbLabels.Items.CopyTo(sAnalogLabel, 0);
930
                for (int i = 0; i < 32; i++)
931
                {
932
                    if (dtAnalog.Rows.Count < 32)
933
                        dtAnalog.Rows.Add(sAnalogLabel[i], "");
934
                    else
935
                        dtAnalog.Rows[i].SetField(0, sAnalogLabel[i]);
936
 
937
                }
938
            }
939
        }
940
        /// <summary>
941
        /// get the version struct of actual controller
942
        /// </summary>
943
        /// <summary>
944
        /// get the labeltexts for the analog values
945
        /// </summary>
946
        private void _getAnalogLabels()
947
        {
948
            if (simpleSerialPort.Port.IsOpen)
949
            {
950
                iLableIndex = 0;
951
                for (int i = 0; i < 32; i++)
952
                {
953
                    Stream serialStream = simpleSerialPort.Port.BaseStream;
954
                    byte[] bytes = FlightControllerMessage.CreateMessage('a', 0, new byte[1] { (byte)i });
955
                    serialStream.Write(bytes, 0, bytes.Length);
956
                    Thread.Sleep(10);
957
                }
958
            }
959
            else
960
                Log(LogMsgType.Error, "NOT CONNECTED!");
961
        }
962
        /// <summary>
963
        /// get the labeltext for a single label
964
        /// </summary>
965
        /// <param name="iIndex">index of the label</param>
966
        private void _getAnalogLabels(int iIndex)
967
        {
968
            if (simpleSerialPort.Port.IsOpen)
969
            {
970
                if (iIndex < 32)
971
                {
972
                    iLableIndex = iIndex;
973
                    _sendControllerMessage('a', 0, new byte[1] { (byte)iLableIndex });
974
                }
975
            }
976
            else
977
                Log(LogMsgType.Error, "NOT CONNECTED!");
978
        }
979
        private void _getVersion()
980
        {
981
            _sendControllerMessage('v', 0);
982
        }
983
        /// <summary>
984
        /// get FC version struct via NC
985
        /// by sending '1' as data (not documented in wiki...)
986
        /// returns HW error 255 (comment in uart1.c : tells the KopterTool that it is the FC-version)
987
        /// </summary>
988
        /// <param name="ctrl">controller number 1=FC</param> 
989
        private void _getVersion(byte ctrl)
990
        {
991
            _sendControllerMessage('v', 0, new byte[1] {ctrl});
992
        }
993
        /// <summary>
994
        /// Switch back to NC by sending the 'Magic Packet' 0x1B,0x1B,0x55,0xAA,0x00
995
        /// </summary>
996
        private void _switchToNC()
997
        {
998
            if (simpleSerialPort.Port.IsOpen)
999
            {
1000
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1001
                byte[] bytes = new byte[5] { 0x1B,0x1B,0x55,0xAA,0x00 };
1002
                serialStream.Write(bytes, 0, bytes.Length);
1003
 
1004
                Thread.Sleep(100);
1005
                _getVersion();
1006
                Thread.Sleep(100);
1007
                _OSDMenue(0);
1008
            }
1009
            else
1010
                Log(LogMsgType.Error, "NOT CONNECTED!");
1011
        }
1012
        /// <summary>
1013
        /// switch to FC
1014
        /// </summary>
1015
        private void _switchToFC()
1016
        {
1017
            _sendControllerMessage('u', 2, new byte[1] { (byte)0 });
1018
            Thread.Sleep(100);
1019
            _getVersion();
1020
            Thread.Sleep(100);
1021
            _OSDMenue(0);
1022
        }
1023
        /// <summary>
1024
        /// send RESET signal to FC
1025
        /// </summary>
1026
        private void _resetCtrl()
1027
        {
1028
            _sendControllerMessage('R', 1);
1029
        }
1030
        /// <summary>
1031
        /// poll the debug data (4sec subscription)
1032
        /// </summary>
1033
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1034
        private void _readDebugData(bool auto)
1035
        {
1036
            byte interval = auto ? debugInterval : (byte)0;
1037
            _sendControllerMessage('d', 0, new byte[1] { debugInterval });
1038
        }
1039
        /// <summary>
1040
        /// poll the BL-CTRL status via NC (4sec subscription)
1041
        /// </summary>
1042
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1043
        private void _readBLCtrl(bool auto)
1044
        {
1045
            byte interval = auto ? blctrlInterval : (byte)0;
1046
            _sendControllerMessage('k', 0, new byte[1] { interval });
1047
        }
1048
        /// <summary>
1049
        /// poll the NC data struct (4sec subscription)
1050
        /// </summary>
1051
        /// <param name="auto"> onetimequery(false) or autoupdate(true) with set timing interval </param>
1052
        private void _readNavData(bool auto)
1053
        {
1054
            byte interval = auto ? navctrlInterval : (byte)0;
1055
            _sendControllerMessage('o', 2, new byte[1] { interval });
1056
        }
1057
        /// <summary>
1058
        /// get the errortext for pending NC error
1059
        /// </summary>
1060
        private void _readNCError()
1061
        {
1062
            _sendControllerMessage('e', 2);
1063
        }
1064
        /// <summary>
1065
        /// start/stop continous polling of controller values
1066
        /// </summary>
1067
        /// <param name="b">start/stop switch</param>
1068
        void _readCont(bool b)
1069
        {
1070
            bReadContinously = b;
1071
            btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.Text = bReadContinously ? "stop automatic" + Environment.NewLine + "data refresh" : "start automatic" + Environment.NewLine + "data refresh"));
1072
            btnReadDebugCont.Invoke((Action)(() => btnReadDebugCont.BackColor = bReadContinously ? Color.FromArgb(192, 255, 192) : Color.FromArgb(224, 224, 224)));
1073
            if (bReadContinously)
1074
            {
2250 - 1075
                if (_debugDataAutorefresh) { _readDebugData(true); Thread.Sleep(10); }
1076
                if (_blctrlDataAutorefresh) { _readBLCtrl(true); Thread.Sleep(10); }
1077
                if (_navCtrlDataAutorefresh && _iCtrlAct == 2) { _readNavData(true); Thread.Sleep(10); }
1078
                if (_OSDAutorefresh) { _OSDMenueAutoRefresh(); Thread.Sleep(10);}
2233 - 1079
                lblLifeCounter.Invoke((Action)(() => lblLifeCounter.BackColor = Color.FromArgb(0, 224, 0)));
1080
            }
1081
            else
1082
                lblLifeCounter.Invoke((Action)(() => lblLifeCounter.BackColor = Color.FromArgb(224, 224, 224)));
1083
            _iLifeCounter = 0;
1084
        }
1085
        /// <summary>
2250 - 1086
        /// set values to "NA" when not available with FC
2233 - 1087
        /// </summary>
1088
        void _setFieldsNA()
1089
        {
1090
            Thread.Sleep(100);
2250 - 1091
            _initDTMotors();
2233 - 1092
            lblNCFlTime.Invoke((Action)(() => lblNCFlTime.Text = "NA"));    //FlightTime
2250 - 1093
            lblNCErrNmbr.Invoke((Action)(() => lblNCErrNmbr.Text = "NA"));  //NC ErrorNr
1094
            lblNCMF.Invoke((Action)(() => lblNCMF.Text = "NA"));            //earth magnet field
1095
            lblNCGSpeed.Invoke((Action)(() => lblNCGSpeed.Text = "NA"));    //GroundSpeed
1096
            lblNCDistHP.Invoke((Action)(() => lblNCDistHP.Text = "NA"));    //Distance to HP
1097
            lblNCSat.Invoke((Action)(() => lblNCSat.Text = "NA"));          //Sats used
1098
            lblNCGPSLong.Invoke((Action)(() => lblNCGPSLong.Text = "NA"));  //GPS position - longitude
1099
            lblNCGPSLat.Invoke((Action)(() => lblNCGPSLat.Text = "NA"));    //GPS position - latitude
2233 - 1100
        }
1101
        /// <summary>
1102
        /// one time query of the OSD Menue with pagenumber
1103
        /// </summary>
1104
        /// <param name="iMenue">Menue page</param>
1105
        void _OSDMenue(int iMenue)
1106
        {
1107
            if (simpleSerialPort.Port.IsOpen)
1108
            {
1109
                if (iMenue > iOSDMax)
1110
                    iMenue = 0;
1111
                Stream serialStream = simpleSerialPort.Port.BaseStream;
1112
                byte[] bytes = FlightControllerMessage.CreateMessage('l', 0, new byte[1] { (byte)iMenue });
1113
                serialStream.Write(bytes, 0, bytes.Length);
1114
            }
1115
            else
1116
                Log(LogMsgType.Error, "NOT CONNECTED!");
1117
 
1118
        }
1119
        /// <summary>
1120
        /// call the OSDMenue and start autorefresh
1121
        ///  usually by sending a menuekey
1122
        /// 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)
1123
        /// therefore the value has to be negative (inverted) in order to distinguish from old (2 line) menuestyle
1124
        /// and must not have any bits of the menue keys 0x1 0x2 0x4 0x8 (0x10?) --> 0x20 = -33
1125
        /// </summary>
1126
        void _OSDMenueAutoRefresh()
1127
        {
1128
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)(-33)),OSDInterval });
1129
        }
1130
        void _OSDMenueAutoRefresh(byte key)
1131
        {
1132
            _sendControllerMessage('h', 0, new byte[2] { unchecked((byte)~key), OSDInterval });
1133
        }
1134
        /// <summary>
1135
        /// initialize the OSD menue combobox
1136
        /// combox is filled by numbers from 0 to max pagenumber
1137
        /// </summary>
1138
        void _initOSDCB()
1139
        {
1140
            _bCBInit = true;
1141
            if(iOSDMax == 0)
1142
            {
1143
                _OSDMenue(0);
1144
                Thread.Sleep(10);
1145
            }
1146
            cbOSD.Invoke((Action)(()=>cbOSD.Items.Clear()));
1147
            for(int i = 0; i <= iOSDMax;i++)
1148
            {
1149
                cbOSD.Invoke((Action)(() => cbOSD.Items.Add(i)));
1150
            }
1151
            cbOSD.Invoke((Action)(() => cbOSD.SelectedItem = iOSDPage));
1152
            _bCBInit = false;
1153
        }
1154
        void _readIni()
1155
        {
1156
            if (!File.Exists(filePath + "\\MKLiveViewSettings.ini"))
1157
                _writeIni();
1158
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
1159
            ini.path = filePath + "\\MKLiveViewSettings.ini";
1160
 
1161
            string sVal = ini.IniReadValue("default", "AutorefreshDebugData");
1162
            _debugDataAutorefresh = Convert.ToBoolean(sVal);
1163
            sVal = ini.IniReadValue("default", "AutorefreshNavCtrlData");
1164
            _navCtrlDataAutorefresh = Convert.ToBoolean(sVal);
1165
            sVal = ini.IniReadValue("default", "AutorefreshBLCtrlData");
1166
            _blctrlDataAutorefresh = Convert.ToBoolean(sVal);
1167
            sVal = ini.IniReadValue("default", "AutorefreshOSDData");
1168
            _OSDAutorefresh = Convert.ToBoolean(sVal);
1169
 
1170
            sVal = ini.IniReadValue("default", "IntervalDebugData");
1171
            debugInterval = (byte)Convert.ToInt16(sVal);
1172
            sVal = ini.IniReadValue("default", "IntervalNavCtrlData");
1173
            navctrlInterval = (byte)Convert.ToInt16(sVal);
1174
            sVal = ini.IniReadValue("default", "IntervalBLCtrlData");
1175
            blctrlInterval = (byte)Convert.ToInt16(sVal);
1176
            sVal = ini.IniReadValue("default", "IntervalOSDData");
1177
            OSDInterval = (byte)Convert.ToInt16(sVal);
1178
        }
1179
        void _writeIni()
1180
        {
1181
 
1182
            IniFile ini = new IniFile("MKLiveViewSettings.ini");
1183
            ini.path = filePath + "\\MKLiveViewSettings.ini";
1184
 
1185
            ini.IniWriteValue("default", "AutorefreshDebugData", _debugDataAutorefresh ? "true":"false");
1186
            ini.IniWriteValue("default", "AutorefreshNavCtrlData", _navCtrlDataAutorefresh ? "true":"false");
1187
            ini.IniWriteValue("default", "AutorefreshBLCtrlData", _blctrlDataAutorefresh ? "true":"false");
1188
            ini.IniWriteValue("default", "AutorefreshOSDData", _OSDAutorefresh ? "true":"false");
1189
 
1190
            ini.IniWriteValue("default", "IntervalDebugData", debugInterval.ToString());
1191
            ini.IniWriteValue("default", "IntervalNavCtrlData", navctrlInterval.ToString());
1192
            ini.IniWriteValue("default", "IntervalBLCtrlData", blctrlInterval.ToString());
1193
            ini.IniWriteValue("default", "IntervalOSDData", OSDInterval.ToString());
1194
        }
1195
 
2250 - 1196
        /// <summary>
1197
        /// initialize the 2 datatables for motor values
1198
        /// dtMotors1 - motor 1 - 4
1199
        /// dtMotors2 - motor 5 - 8
1200
        /// DataGridView dgvMotors1/2 are bound to dtMotors1/2 
1201
        /// </summary>
1202
        void _initDTMotors()
1203
        {
1204
            for(int i = 0; i < 4; i++)
1205
            {
1206
                if (dtMotors1.Rows.Count < 4)
1207
                    dtMotors1.Rows.Add((i + 1).ToString(), "NA", "NA");
1208
                else
1209
                {
1210
                    dtMotors1.Rows[i].SetField(1, "NA");
1211
                    dtMotors1.Rows[i].SetField(2, "NA");
1212
                }
1213
                if (dtMotors2.Rows.Count < 4)
1214
                    dtMotors2.Rows.Add((i + 5).ToString(), "NA", "NA");
1215
                else
1216
                {
1217
                    dtMotors2.Rows[i].SetField(1, "NA");
1218
                    dtMotors2.Rows[i].SetField(2, "NA");
1219
                }
1220
            }
1221
            dgvMotors1.Invoke((Action)(() => dgvMotors1.Refresh()));
1222
            dgvMotors2.Invoke((Action)(() => dgvMotors2.Refresh()));
1223
        }
1224
 
1225
        /// <summary>
1226
        /// Convert decimal degrees to degrees, minutes, seconds, milliseconds 
1227
        /// </summary>
1228
        /// <param name="coord">the degree value as double</param>
1229
        /// <returns>0° 0' 0,0"</returns>
1230
        string _convertDegree(double coord)
1231
        {
1232
            //double minutes = (degree - Math.Floor(degree)) * 60.0;
1233
            //double seconds = (minutes - Math.Floor(minutes)) * 60.0;
1234
            //double tenths = (seconds - Math.Floor(seconds)) * 10.0;
1235
            //// get rid of fractional part
1236
            //minutes = Math.Floor(minutes);
1237
            //seconds = Math.Floor(seconds);
1238
            //tenths = Math.Floor(tenths);
1239
 
1240
 
1241
            //int sec = (int)Math.Round(coord * 3600);
1242
            //int deg = sec / 3600;
1243
            //sec = Math.Abs(sec % 3600);
1244
            //int min = sec / 60;
1245
            //sec %= 60;
1246
 
1247
            var ts = TimeSpan.FromHours(Math.Abs(coord));
1248
            double deg = Math.Sign(coord) * Math.Floor(ts.TotalHours);
1249
            int min = ts.Minutes;
1250
            int sec = ts.Seconds;
1251
            int milli = ts.Milliseconds;
1252
 
1253
            return deg.ToString("0° ") + min.ToString("0") + "' " + sec.ToString("0") + "," + milli.ToString() + "\"";
1254
        }
2233 - 1255
        #endregion functions
1256
 
1257
        #region buttons
1258
        private void buttonReset_Click(object sender, EventArgs e)
1259
        {
1260
            _resetCtrl();
1261
        }
1262
        private void btnVersion_Click(object sender, EventArgs e)
1263
        {
1264
            _getVersion();
1265
        }
1266
        private void btnAnalogLabels_Click(object sender, EventArgs e)
1267
        {
1268
            _getAnalogLabels(0);
1269
        }
1270
        private void btnDbgData_Click(object sender, EventArgs e)
1271
        {
1272
            _readDebugData(false); //onetime reading of debug data --> subscription lasts 4sec - this means you will receive data for 4 seconds
1273
        }
1274
        private void btnSaveLabels_Click(object sender, EventArgs e)
1275
        {
1276
            switch (_iCtrlAct)
1277
            {
1278
                case 1:
1279
                    fileName = "FCLabelTexts.txt";
1280
                    break;
1281
                case 2:
1282
                    fileName = "NCLabelTexts.txt";
1283
                    break;
1284
                default:
1285
                    fileName = "NCLabelTexts.txt";
1286
                    break;
1287
            }
1288
            if (sAnalogLabel[0] != null)
1289
            {
1290
                File.WriteAllLines(filePath + "\\" + fileName, sAnalogLabel);
1291
                Console.WriteLine("Names saved to file");
1292
                _loadLabelFile();
1293
            }
1294
            else
1295
                Log(LogMsgType.Warning, "there's no data -> read first from fc/nc!");
1296
        }
1297
        private void btnLoadLabels_Click(object sender, EventArgs e)
1298
        {
1299
            _assignLabelNames();
1300
        }
1301
        private void btnReadLabelFile_Click(object sender, EventArgs e)
1302
        {
1303
            _loadLabelFile();
1304
        }
1305
        private void btnSwitchFC_Click(object sender, EventArgs e)
1306
        {
1307
            _switchToFC();
1308
        }
1309
        private void btnSwitchNC_Click(object sender, EventArgs e)
1310
        {
1311
            _switchToNC();
1312
        }
1313
        private void btnReadDbgCont_Click(object sender, EventArgs e)
1314
        {
1315
            _readCont(!bReadContinously);
1316
        }
1317
        private void btnReadBLCtrl_Click(object sender, EventArgs e)
1318
        {
1319
 
1320
            if (_iCtrlAct == 2) _readBLCtrl(false);
1321
            else Log(LogMsgType.Warning, "only available when connected to NC");
1322
        }
1323
        private void btnGetNaviData_Click(object sender, EventArgs e)
1324
        {
1325
            if (_iCtrlAct == 2) _readNavData(false);
1326
            else Log(LogMsgType.Warning, "only available when connected to NC");
1327
        }
1328
        private void btnConn_Click(object sender, EventArgs e)
1329
        {
1330
            simpleSerialPort.Connect(!simpleSerialPort.Port.IsOpen);
1331
        }
1332
        private void button3_Click(object sender, EventArgs e)
1333
        {
1334
            _getVersion(1);
1335
        }
1336
        private void button4_Click(object sender, EventArgs e)
1337
        {
1338
            _getVersion(2);
1339
        }
1340
        private void btnOSD_Click(object sender, EventArgs e)
1341
        {
1342
            if (iOSDPage > iOSDMax)
1343
                iOSDPage = 0;
1344
            _OSDMenue(iOSDPage);
1345
        }
1346
        private void btnOSDForward_Click(object sender, EventArgs e)
1347
        {
1348
            iOSDPage++;
1349
            if (iOSDPage > iOSDMax)
1350
                iOSDPage = 0;
1351
 
1352
            _OSDMenue(iOSDPage);
1353
        }
1354
        private void btnOSDBackward_Click(object sender, EventArgs e)
1355
        {
1356
            iOSDPage--;
1357
            if (iOSDPage < 0)
1358
                iOSDPage = iOSDMax;
1359
 
1360
            _OSDMenue(iOSDPage);
1361
        }
1362
        private void btnOSDAuto_Click(object sender, EventArgs e)
1363
        {
1364
            _OSDMenueAutoRefresh();
1365
        }
1366
        /// call the OSDMenue with Key 0x8
1367
        private void btnOSDLeave_Click(object sender, EventArgs e)
1368
        {
1369
            _OSDMenueAutoRefresh(8);
1370
        }
1371
        /// call the OSDMenue with Key 0x4
1372
        private void btnOSDEnter_Click(object sender, EventArgs e)
1373
        {
1374
            _OSDMenueAutoRefresh(4);
1375
        }
1376
        #endregion buttons
1377
    }
1378
    public class IniFile
1379
    {
1380
        public string path;
1381
 
1382
        [DllImport("kernel32")]
1383
        private static extern long WritePrivateProfileString(string section,
1384
          string key, string val, string filePath);
1385
 
1386
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
1387
        static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
1388
               uint nSize, string lpFileName);
1389
 
1390
        [DllImport("kernel32")]
1391
        private static extern int GetPrivateProfileString(string section,
1392
          string key, string def, StringBuilder retVal,
1393
          int size, string filePath);
1394
 
1395
        public IniFile(string INIPath)
1396
        {
1397
            path = INIPath;
1398
        }
1399
 
1400
        public void IniWriteValue(string Section, string Key, string Value)
1401
        {
1402
            WritePrivateProfileString(Section, Key, Value, this.path);
1403
        }
1404
 
1405
        public string IniReadValue(string Section, string Key)
1406
        {
1407
            StringBuilder temp = new StringBuilder(255);
1408
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
1409
            return temp.ToString();
1410
        }
1411
        //Ini_sections auslesen in String-Array
1412
        public string[] IniSectionNames()
1413
        {
1414
 
1415
            //  uint MAX_BUFFER = 32767;
1416
            uint MAX_BUFFER = 8388608;
1417
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
1418
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, this.path);
1419
            if (bytesReturned == 0)
1420
            {
1421
                Marshal.FreeCoTaskMem(pReturnedString);
1422
                return null;
1423
            }
1424
            string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
1425
            Marshal.FreeCoTaskMem(pReturnedString);
1426
            //use of Substring below removes terminating null for split
1427
            return local.Substring(0, local.Length - 1).Split('\0');
1428
 
1429
 
1430
        }
1431
    }
1432
    public static class ControlExtensions
1433
    {
1434
        /// <summary> 
1435
        /// Execute a threadsafe operation, when accessing a control via another thread 
1436
        /// action is a lamdaexpression
1437
        /// e.g. comboBox1.ExecuteThreadSafe(() => comboBox1.Enabled = true);
1438
        /// </summary>
1439
        /// <param name="control"> The control </param>
1440
        /// <param name="action"> The 'action' to perform </param>
1441
        public static void ExecuteThreadSafe(this Control control, Action action)
1442
        {
1443
            if (control.InvokeRequired)
1444
            {
1445
                control.BeginInvoke(action); //"BeginInvoke" is an async call -> threadsafety error when called to many times successively -> then take "Invoke"
1446
            }
1447
            else
1448
            {
1449
                action.Invoke();
1450
            }
1451
        }
1452
    }
1453
 
1454
}