Subversion Repositories Projects

Rev

Rev 2363 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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