Subversion Repositories Projects

Rev

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

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