-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGroundStation.cs
368 lines (315 loc) · 12 KB
/
GroundStation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using CefSharp.MinimalExample.WinForms;
using MavBoia;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using MavBoia.InfluxDB;
using MavlinkDataController;
using MavBoia.Forms;
using System.Linq;
using MavBoia.Utilities;
namespace SimpleExample
{
public partial class GroundStation : Form
{
//Mavlink parser responsible for parsing and deparsing mavlink packets
private Mavlink.MavlinkParser mavlinkParser = new Mavlink.MavlinkParser();
private byte SysIDLocal { get; set; } = 0xFF; // Default System ID for ground stations.
private byte CompIDLocal { get; set; } = (byte)Mavlink.MAV_COMPONENT.MAV_COMP_ID_MISSIONPLANNER;
private byte VehicleSysID { get; set; } = 0x01; // Default System ID for vehicles.
private byte VehicleCompID { get; set; } = (byte)Mavlink.MAV_COMPONENT.MAV_COMP_ID_ONBOARD_COMPUTER;
// Forms declaration
FormChart formGraficos;
FormMapa formMapa;
FormConfigurações formConfigurações;
BrowserForm formBrowser;
FormDados formDados;
FormRewind formRewind;
// Form state
private Button activatedButton;
private Form currentForm;
// Serial communication
private SerialPort serialPort;
private BackgroundWorker serialWorker;
private object serialLock = new object(); // lock to prevent thread collisions on serial port
// Network communication
InfluxDBCommunication influxCommunication;
private CancellationTokenSource networkCancellation;
private bool isNetworkRunning = false;
public static MavlinkDataController.DataController DataController; // Static to facilitate communication with GLG Chart. If you need to use pass the object instead of accessing the static field.
public GroundStation()
{
InitializeComponent();
DataController = new MavlinkDataController.DataController();
// Serial port initialization
serialPort = new SerialPort("COM8", 9600);
serialPort.ReadTimeout = 2000;
serialWorker = new BackgroundWorker();
serialWorker.WorkerSupportsCancellation = true;
serialWorker.DoWork += serialWorker_DoWork;
serialWorker.RunWorkerCompleted += serialWorker_RunWorkerCompleted;
// Network initialization
influxCommunication = new InfluxDBCommunication();
// Forms instantiation
formGraficos = new FormChart();
formDados = new FormDados(DataController);
formMapa = new FormMapa(DataController, true);
formConfigurações = new FormConfigurações();
formBrowser = new BrowserForm();
formRewind = new FormRewind(DataController);
MavBoiaConfigurations.OnSerialConfigurationUpdate += UpdateSerialConfiguration;
}
#region Form Initialization Defaults
private void GroundStation_Load(object sender, EventArgs e)
{
LoadForms();
}
// Ensure all forms are loaded and ready to receive data.
private void LoadForms()
{
List<Form> forms = new List<Form>() { formConfigurações, formDados, formMapa, formBrowser, formGraficos, formRewind};
foreach (Form form in forms)
{
form.TopLevel = false;
form.FormBorderStyle = FormBorderStyle.None;
form.Dock = DockStyle.Fill;
panelDesktop.Controls.Add(form);
form.Show(); // Calls load event
form.Hide(); // Keeps the form in background
}
}
#endregion
#region SerialCommunication
private void UpdateSerialConfiguration()
{
if (serialPort.IsOpen)
{
lock (serialLock)
{
serialPort.Close();
serialPort.PortName = MavBoiaConfigurations.SerialPort;
serialPort.BaudRate = MavBoiaConfigurations.BaudRate;
serialPort.Open();
}
}
else
{
serialPort.PortName = MavBoiaConfigurations.SerialPort;
serialPort.BaudRate = MavBoiaConfigurations.BaudRate;
}
}
private void buttonConnectRadio_Click(object sender, EventArgs e)
{
try
{
const string buttonOffText = "Conectar rádio";
const string buttonOnText = "Desconectar rádio";
// if the port is open close it
if (serialPort.IsOpen)
{
serialWorker.CancelAsync();
buttonConnectRadio.Text = buttonOffText;
return;
}
serialPort.PortName = MavBoiaConfigurations.SerialPort;
serialPort.BaudRate = MavBoiaConfigurations.BaudRate;
serialPort.Open();
serialWorker.RunWorkerAsync();
buttonConnectRadio.Text = buttonOnText;
}
catch (Exception exception)
{
MessageBox.Show($"{exception.Message}\n" + $"Verifique se a porta existe ou já está sendo usada por outro programa.");
}
}
private void serialWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!serialWorker.CancellationPending)
{
try
{
if (!serialPort.IsOpen) continue;
Mavlink.MavlinkMessage message;
lock (serialLock)
message = mavlinkParser.ReadPacket(serialPort.BaseStream);
if (message != null)
{
DataController.ProcessMavlinkMessage(message);
}
}
catch(UnauthorizedAccessException unauthorizedException)
{
buttonConnectRadio.BeginInvoke((Action)(() => { buttonConnectRadio.Text = "Conectar rádio"; }));
serialWorker.CancelAsync();
Console.WriteLine(unauthorizedException.Message);
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Thread.Sleep(1);
}
e.Cancel = true;
}
private void serialWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lock (serialLock)
serialPort.Close();
}
#endregion
#region Network
private async Task RunNetworkAsync(CancellationToken cancellationToken)
{
isNetworkRunning = true;
while (!cancellationToken.IsCancellationRequested)
{
try
{
AllSensorData data = await influxCommunication.GetAllDataAsync();
DataController.ProcessNetworkData(data);
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Thread.Sleep(1000);
}
isNetworkRunning = false;
}
private void buttonConnectNetwork_Click(object sender, EventArgs e)
{
if (isNetworkRunning)
{
networkCancellation?.Cancel();
buttonConnectNetwork.Text = "Conectar rede";
return;
}
networkCancellation = new CancellationTokenSource();
buttonConnectNetwork.Text = "Desconectar rede";
isNetworkRunning = true;
var task = Task.Run(async () => await RunNetworkAsync(networkCancellation.Token));
}
#endregion
#region Button Functions
private void ActivateButton(Button btn)
{
if (btn == null) return;
if(btn != activatedButton)
{
DeactivateButton(activatedButton);
activatedButton = btn;
btn.BackColor = Color.FromArgb(46, 51, 73);
}
}
private void DeactivateButton(Button btn)
{
if (btn == null) return;
btn.BackColor = Color.FromArgb(24, 30, 54);
}
#endregion
private void ShowForm(Form form)
{
if(currentForm != null)
{
currentForm.Hide();
}
currentForm = form;
panelDesktop.Tag = form;
form.BringToFront();
form.Show();
lblTitle.Text = form.Text;
}
private void buttonRastreio_Click(object sender, EventArgs e)
{
ActivateButton(sender as Button);
ShowForm(formBrowser);
}
private void buttonGraficos_Click(object sender, EventArgs e)
{
ActivateButton(sender as Button);
ShowForm(formGraficos);
}
private void buttonDados_Click(object sender, EventArgs e)
{
ActivateButton(sender as Button);
ShowForm(formDados);
}
private void buttonMapa_Click(object sender, EventArgs e)
{
ActivateButton(sender as Button);
ShowForm(formMapa);
}
private void buttonConfigurações_Click(object sender, EventArgs e)
{
ActivateButton(sender as Button);
ShowForm(formConfigurações);
}
private void buttonRewind_Click(object sender, EventArgs e)
{
ActivateButton(sender as Button);
ShowForm(formRewind);
}
protected override void OnClosed(EventArgs e)
{
this.serialPort?.Dispose();
this.influxCommunication?.Dispose();
base.OnClosed(e);
Application.Exit();
}
#region Deprecated
/// <summary>
/// Callback for all buttons in the sidebar. Sets the panelNav position and color, which is the thin blue bar that tracks the buttons.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGenericClickCallback(object sender, EventArgs e)
{
//Button button = (Button)sender;
//panelNav.Height = button.Height;
//panelNav.Top = button.Top;
//panelNav.Left = button.Left;
//panelNav.BringToFront();
//button.BackColor = Color.FromArgb(46, 51, 73);
//panelSecondaryFormLoader.Controls.Clear();
//panelSecondaryFormLoader.Controls.Add(formBrowser);
//panelSecondaryFormLoader.Show();
//panelTopLeft.Enabled = false;
//panelTopLeft.Visible = false;
//pictureBoxArariboia.Enabled = false;
//pictureBoxArariboia.Visible = false;
}
#endregion
private void WriteBufferConsole(byte[] buffer, string logMessage, bool UseHexMode = false)
{
if (logMessage != String.Empty)
Console.WriteLine(logMessage);
if (UseHexMode)
{
foreach (var item in buffer)
{
Console.WriteLine($"0x{item.ToString("X2")}");
}
}
else
{
foreach (var item in buffer)
{
Console.WriteLine($"{item}");
}
}
Console.WriteLine();
}
#region Resize Logic
private void GroundStation_Resize(object sender, EventArgs e)
{
}
#endregion
}
}