-
Notifications
You must be signed in to change notification settings - Fork 20
/
DataSender.cs
79 lines (64 loc) · 2.55 KB
/
DataSender.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
using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using fs2ff.Models;
namespace fs2ff
{
public class DataSender : IDisposable
{
private const int Port = 49002;
private const string SimId = "MSFS";
private IPEndPoint? _endPoint;
private Socket? _socket;
public void Connect(IPAddress? ip)
{
Disconnect();
ip ??= IPAddress.Broadcast;
_endPoint = new IPEndPoint(ip, Port);
_socket = new Socket(_endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
{
EnableBroadcast = ip.Equals(IPAddress.Broadcast)
};
}
public void Disconnect() => _socket?.Dispose();
public void Dispose() => _socket?.Dispose();
public async Task Send(Attitude a)
{
var data = string.Format(CultureInfo.InvariantCulture,
"XATT{0},{1:0.#},{2:0.#},{3:0.#},,,,,,,,,", // Garmin Pilot requires 13 fields
SimId, a.TrueHeading, -a.Pitch, -a.Bank);
await Send(data).ConfigureAwait(false);
}
public async Task Send(Position p)
{
var data = string.Format(CultureInfo.InvariantCulture,
"XGPS{0},{1:0.#####},{2:0.#####},{3:0.#},{4:0.###},{5:0.#}",
SimId, p.Longitude, p.Latitude, p.Altitude, p.GroundTrack, p.GroundSpeed);
await Send(data).ConfigureAwait(false);
}
public async Task Send(Traffic t, uint id)
{
var data = string.Format(CultureInfo.InvariantCulture,
"XTRAFFIC{0},{1},{2:0.#####},{3:0.#####},{4:0.#},{5:0.#},{6},{7:0.###},{8:0.#},{9}",
SimId, id, t.Latitude, t.Longitude, t.Altitude, t.VerticalSpeed, t.OnGround ? 0 : 1,
t.TrueHeading, t.GroundVelocity, TryGetFlightNumber(t) ?? t.TailNumber);
await Send(data).ConfigureAwait(false);
}
private async Task Send(string data)
{
if (_endPoint != null && _socket != null)
{
await _socket
.SendToAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(data)), SocketFlags.None, _endPoint)
.ConfigureAwait(false);
}
}
private static string? TryGetFlightNumber(Traffic t) =>
!string.IsNullOrEmpty(t.Airline) && !string.IsNullOrEmpty(t.FlightNumber)
? $"{t.Airline} {t.FlightNumber}"
: null;
}
}