-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvStripsConnector.cs
564 lines (486 loc) · 22 KB
/
vStripsConnector.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
using System;
using System.Collections.Generic;
using vatsys;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
namespace vStripsPlugin
{
internal class vStripsConnector
{
public const string DEFAULT_RUNWAYS = "00:00";
private IPEndPoint vStripsHost;
private UdpClient vStripsSocket;
private const int VSTRIPS_PORT = 60301;
private const string MIN_VSTRIPS_PLUGIN_VERSION = "1.18";
private CancellationTokenSource cancellationToken;
private ConcurrentDictionary<string, int> vStripsAssignedHeadings = new ConcurrentDictionary<string, int>();
private List<string> vStripsSentATCCallsigns = new List<string>();
private bool connected = false;
private bool setRunways = false;
public static event EventHandler<PacketReceivedEventArgs> PacketReceived;
public static IPAddress HostIP = IPAddress.Loopback;
public static string runways = DEFAULT_RUNWAYS;
private static string qnh="";
public static Airspace2.Airport Airport = null;
private static vStripsConnector Instance;
private vStripsConnector()
{
vStripsHost = new IPEndPoint(HostIP, VSTRIPS_PORT);
vStripsSocket = new UdpClient();
cancellationToken = new CancellationTokenSource();
}
public static string Runways
{
get { return runways; }
set { runways = value; Instance.setRunways = true; Instance.SendRunways(); }
}
private void Network_OnlineATCChanged(object sender, Network.ATCUpdateEventArgs e)
{
if (Instance?.connected == true)
{
if (e.UpdatedATC == null)
SyncATCLists();
else
{
bool exists = Network.GetOnlineATCs.Contains(e.UpdatedATC);
bool sent = vStripsSentATCCallsigns.Contains(e.UpdatedATC.Callsign);
if (exists)
SendATCOnline(e.UpdatedATC);
else if (!exists && sent)
SendATCOffline(e.UpdatedATC.Callsign);
}
}
}
private void SyncATCLists()
{
var online = Network.GetOnlineATCs;
if (Instance?.connected == true)
{
foreach (var atc in online.Where(a => !vStripsSentATCCallsigns.Contains(a.Callsign)))
{
SendATCOnline(atc);
vStripsSentATCCallsigns.Add(atc.Callsign);
}
foreach (var atc in vStripsSentATCCallsigns.Except(online.Select(a => a.Callsign)))
SendATCOffline(atc);
}
}
private void Network_PrimaryFrequencyChanged(object sender, EventArgs e)
{
SendControllerInfo();
}
public static void Restart()
{
Instance?.Stop();
Instance = null;
Start();
}
public static void Start()
{
Instance = new vStripsConnector();
Instance?.Connect();
}
private void Stop()
{
Instance?.Disconnect();
Instance?.vStripsAssignedHeadings.Clear();
Instance?.vStripsSentATCCallsigns.Clear();
}
private void Connect()
{
vStripsSocket.Connect(vStripsHost);
Task.Run(() => ReceiveData());
Task.Run(() => PollForConnection());
}
private void Disconnect()
{
connected = false;
cancellationToken.Cancel();
vStripsSocket.Close();
vStripsSocket.Dispose();
}
private void PollForConnection()
{
while (!connected && !cancellationToken.IsCancellationRequested)
{
SendVersion();
Thread.Sleep(1000);
}
}
private void SendVersion()
{
SendData("h" + MIN_VSTRIPS_PLUGIN_VERSION);
}
private void OnConnected()
{
Network.PrimaryFrequencyChanged += Network_PrimaryFrequencyChanged;
Network.OnlineATCChanged += Network_OnlineATCChanged;
MET.Instance.ProductsChanged += MET_ProductChanged;
SyncATCLists();
connected = true;
SendQnh();
}
public static void UpdateFDR(FDP2.FDR fdr)
{
if(Instance?.connected == true)
Instance.SendAircraftMetadata(fdr);
}
public static void RemoveFDR(FDP2.FDR fdr)
{
if (Instance?.connected == true)
{
Instance.SendDeleteAircraft(fdr);
Instance.vStripsAssignedHeadings.TryRemove(fdr.Callsign, out _);
}
}
public static void SelectStrip(String callsign)
{
if (Instance?.connected == true)
Instance.SendData(">" + callsign);
}
/*
* Called on MET change event
* If a VATSIM METAR received and it matches the ICAO of our Airfield, store in the qnh var
* Then if online, update online
*
*/
public void MET_ProductChanged(object sender, MET.ProductsChangedEventArgs e)
{
if (e.ProductRequest.Icao == Airport?.ICAOName)
{
try
{
var products = MET.Instance.Products[e.ProductRequest];
var prod = products.FirstOrDefault();
switch (prod)
{
case MET.VATSIM_METAR vatmet:
qnh = vatmet.QNH;
if (Instance?.connected == true)
SendQnh();
break;
default:
break;
}
} catch (Exception ex) {
// When an Airfield is cleared from the AIS window
// var products = MET.Instance.Products[e.ProductRequest];
// generates an Indec Not found exception
}
}
}
/*
* Request a VATSIM METAR
* Called on reciept of Airfield code from vatSys
*/
private void getMetar(string ICAO)
{
if (Network.IsConnected)
{
if (qnh == "" || Airport.ICAOName != ICAO) { // Only call if no QNH or Aifield changed
MET.ProductRequest myreq = new MET.ProductRequest(MET.ProductType.VATSIM_METAR, ICAO, true);
MET.Instance.RequestProduct(myreq);
}
SendQnh();
}
}
private void SendControllerInfo()
{
if (!Network.IsConnected)
return;
SendVersion();
//CALLSIGN:NAME:FREQ
string pack = $"U{Network.Me.Callsign}:{Network.Me.RealName}:{ConvertFreqArrayToString(Network.Me.Frequencies)}";
Instance?.SendData(pack);
string trans = $"T{RDP.TRANSITION_ALTITUDE}";
Instance?.SendData(trans);
}
/*
* Construct the QNH string for the vStrips selected airport and send
*/
private void SendQnh()
{
if (Instance?.connected == true && qnh != "" && Airport?.ICAOName != null)
Instance?.SendData($"Q{Airport.ICAOName} Q{qnh}");
}
private void SendATCOnline(NetworkATC atc)
{
if (Instance?.connected==true)
{
Instance?.SendData($"C{atc.Callsign}:{atc.RealName}:{(ConvertFreqArrayToString(atc.Frequencies))}");
}
}
private void SendATCOffline(string callsign)
{
if (Instance?.connected == true)
Instance?.SendData($"c{callsign}");
}
private void SendDeleteAircraft(FDP2.FDR fdr)
{
if (Instance?.connected == true)
Instance?.SendData($"D{fdr.Callsign}");
}
private void SendRemarks(FDP2.FDR fdr)
{
string rmks = $"P{fdr.Callsign}:{fdr.Remarks}";
if (Instance?.connected == true)
Instance?.SendData(rmks);
}
private void SendRunways() // modified JMG to force runways to none and add send QNH
{
Instance?.SendData($"R00:00");
//SendData($"R{Runways}"); //Old
}
/**
* Construct Aircraft data
*
* string[] strArray = msg.Split(':');
this.callsign = strArray[0];
this.upDown = this.callsign[0];
this.callsign = this.callsign.Substring(1);
this.origin = strArray[1];
this.dest = strArray[2];
this.squawk = string.IsNullOrEmpty(strArray[3]) ? (string)null : strArray[3];
this.sentSquawk = string.IsNullOrEmpty(strArray[4]) ? (string)null : strArray[4];
this.groundState = strArray[5][0];
this.altitude = int.Parse(strArray[6]);
this.heading = int.Parse(strArray[7]);
this.gone = int.Parse(strArray[8]);
this.toGo = int.Parse(strArray[9]);
this.aircraftType = strArray[10];
this.sidName = string.IsNullOrEmpty(strArray[11]) ? (string)null : strArray[11];
this.runway = string.IsNullOrEmpty(strArray[12]) ? (string)null : strArray[12];
this.fpRules = strArray[13][0] == 'V' ? FltRules.VFR : FltRules.IFR;
this.rfl = int.Parse(strArray[14]);
this.estDepTime = strArray[15];
this.spd = strArray[16];
this.groundspeed = int.Parse(strArray[17]);
this.route = strArray[18];
this.distanceFromMe = int.Parse(strArray[19]);
this.commsType = strArray[20][0];
try
{
this.lat = double.Parse(strArray[21]);
this.lon = double.Parse(strArray[22]);
}
catch
{
}
if (!(Presenter.CurrentAirfield == "EGLL") && !(Presenter.CurrentAirfield == "EGCC"))
return;
this.scratchpad = strArray[23];
*
*/
private void SendAircraftMetadata(FDP2.FDR fdr)
{
if (fdr == null)
return;
if (fdr.PredictedPosition.Location == null)
return;
RDP.RadarTrack radTrack = fdr.CoupledTrack;
if (radTrack == null)
radTrack = RDP.RadarTracks.FirstOrDefault(r => r.ASMGCSCoupledFDR == fdr);
string gone = "0";
string togo = "0";
string tome = "0";
if(fdr.ParsedRoute?.Count > 0)
{
gone = Conversions.CalculateDistance(fdr.ParsedRoute.First().Intersection.LatLong, fdr.PredictedPosition.Location).ToString("0");
togo = Conversions.CalculateDistance(fdr.ParsedRoute.Last().Intersection.LatLong, fdr.PredictedPosition.Location).ToString("0");
tome = Conversions.CalculateDistance(Airport == null ? Network.Me.Position : Airport.LatLong, fdr.PredictedPosition.Location).ToString("0");
}
string upDown = "U";
if(radTrack?.OnGround == true || fdr.ATD == DateTime.MaxValue)
upDown = "D";
string gndState = " ";
if(fdr.DepAirport == Airport?.ICAOName && fdr.State == FDP2.FDR.FDRStates.STATE_COORDINATED)
{
gndState = "T";
}
int ahdg = 0;
vStripsAssignedHeadings.TryGetValue(fdr.Callsign, out ahdg);
string meta = string.Join(":",
upDown + fdr.Callsign,
fdr.DepAirport,
fdr.DesAirport,
fdr.AssignedSSRCode == -1 ? "" : Convert.ToString(fdr.AssignedSSRCode, 8),
radTrack != null ? Convert.ToString(radTrack.ActualAircraft.TransponderCode, 8): "",
gndState,
fdr.CFLUpper <= FDP2.FDR.LEVEL_VSA ? 0 : fdr.CFLUpper,
ahdg,
gone,
togo,
fdr.AircraftType + "/" + fdr.AircraftWake,
(fdr.DepAirport == Airport?.ICAOName ? fdr.SIDSTARString:""), // modified JMG - Inhibit STAR population for airborne
fdr.RunwayString,
fdr.FlightRules,
fdr.RFL,
fdr.ETD.ToString("HHmm"),
0,
fdr.PredictedPosition.Groundspeed.ToString("0"),
fdr.Route,
tome,
fdr.TextOnly ? "T" : fdr.ReceiveOnly ? "R" : "V",
fdr.PredictedPosition.Location.Latitude,
fdr.PredictedPosition.Location.Longitude,
fdr.LabelOpData);
Instance?.SendData("M" + meta);
SendRemarks(fdr);
}
private void SendData(string packet)
{
var data = Encoding.ASCII.GetBytes(packet);
Instance?.vStripsSocket.SendAsync(data, data.Length);
}
private void ReceiveData()
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
byte[] data = vStripsSocket.Receive(ref vStripsHost);
string packet = Encoding.ASCII.GetString(data);
ProcessData(packet);
}
catch (SocketException)
{
Thread.Sleep(1000);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private void ProcessData(string packet)
{
if (packet.Length == 0)
return;
string msg = packet.Substring(1);
string[] msg_fields = msg.Split(':');
FDP2.FDR fdr = null;
if (msg_fields.Length > 0)
{
fdr = FDP2.GetFDRs.FirstOrDefault(f => f.Callsign == msg_fields[0]);
}
switch (packet[0])
{
case 'U':
if (!connected)
OnConnected();
SendControllerInfo();
break;
case 'r': // Runway request
if (Airport?.ICAOName != msg)// || setRunways == false) // Commented out as part of runway supression
{
getMetar(msg); // Call before we update 'Airport'
Airport = Airspace2.GetAirport(msg);
setRunways = false;
//vStripsPlugin.ShowSetupWindow(); // Commented out to stop popup JMG
}
else
//SendRunways();
Airport = Airspace2.GetAirport(msg);
break;
case 'S': // State
if (msg_fields.Length > 1 && fdr != null)
{
switch (msg_fields[1])
{
case "TAXI":
MMI.EstFDR(fdr);
break;
}
}
break;
/*
* JMG
* vStrips doesn't send Arrival Runway, so we use Dep runway in vStrips for Arrival runway allocation.
* We need to keep an eye out when Route changes received that have a Dep runway and reassign to Arr runway.
*
*/
case 'R': // Route
if (msg_fields.Length > 3 && fdr != null)
{
if (fdr.DepAirport == msg_fields[1] && fdr.DesAirport == msg_fields[2])
{
string rte = msg_fields[3];
string[] rte_fields = rte.Split(' '); // parse route on space
if (rte_fields[0].Contains('/') ) // If the first field has a slash, it's a Dep runway assignment.
{
string[] start_fields = rte_fields[0].Split('/');
String NewRwy = start_fields[1]; // get the runway
if (fdr.CoupledTrack?.OnGround == false) // if we're airborne apply the runway to Arrivals
{
FDP2.SetArrivalRunway(fdr, Airspace2.GetRunway(fdr.DesAirport, NewRwy));
}
else // Apply the Route change, or Dep runway change
{
string temprwy = "";
if (fdr.DepartureRunway != null)
temprwy = fdr.DepartureRunway.ToString();
if (temprwy != NewRwy) // if the Dep runway has changed
{
FDP2.SetDepartureRunway(fdr, Airspace2.GetRunway(fdr.DepAirport, NewRwy));
}
else // Not a runway change, so update the route
{
FDP2.ModifyRoute(fdr, rte);
}
}
}
} else
FDP2.ModifyFDR(fdr, fdr.Callsign, fdr.FlightRules, msg_fields[1], msg_fields[2], msg_fields[3], fdr.Remarks, fdr.AircraftCount.ToString(), fdr.AircraftType, fdr.AircraftWake, fdr.AircraftEquip, fdr.AircraftSurvEquip, fdr.TAS.ToString(), fdr.RFL.ToString(), fdr.ETD.ToString("HHmm"), fdr.EET.ToString("HHmm"));
}
break;
case 'H': // Heading
if (msg_fields.Length > 1 && fdr != null)
{
vStripsAssignedHeadings.AddOrUpdate(fdr.Callsign, int.Parse(msg_fields[1]), (s, i) => int.Parse(msg_fields[1]));
if (!string.IsNullOrEmpty(msg_fields[1]) && msg_fields[1] != "0")
FDP2.SetGlobalOps(fdr, $"H{msg_fields[1]}");
if (msg_fields.Length > 2 && msg_fields[2] != "0")
FDP2.SetCFL(fdr, FDP2.FDR.LEVEL_NONE, int.Parse(msg_fields[2]), false);
}
break;
case '>': // Select Callsign
// Edited JMG to ensure when strip is selected in vStrips, track is selected in vatSys
if(fdr != null)
{
var currentSelection = MMI.SelectedTrack; // Deselect old
if(MMI.SelectedTrack != null)
MMI.SelectOrDeselectTrack(currentSelection);
var trk = MMI.FindTrack(fdr);
if (trk != null)
{
MMI.SelectOrDeselectTrack(trk);
}
}
break;
}
PacketReceived?.Invoke(this, new PacketReceivedEventArgs(packet));
Console.WriteLine(packet);
}
private static string ConvertFreqArrayToString(int[] vatsysFreqArray)
{
return vatsysFreqArray[0].ToString().Substring(0, 5);
}
private static string ConvertToFreqString(uint vatsysFreq)
{
return vatsysFreq.ToString().Substring(0, 5);
}
public class PacketReceivedEventArgs : EventArgs
{
public readonly string Packet;
public PacketReceivedEventArgs(string packet)
{
Packet = packet;
}
}
}
}