Subversion Repositories Projects

Rev

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

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