SafeDispatch/MotoTrbo_GW/TelemetryReceiveThread.cs
2024-02-22 18:43:59 +02:00

85 lines
3.3 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
using SafeMobileLib;
using System.Threading;
namespace MotoTrbo_GW
{
class TelemetryReceiveThread
{
private static UdpClient udpClient;
private UdpMulticast udpMulticast;
private Int32 telemetryPort = 0;
private String mIP;
private Int32 mPort;
public TelemetryReceiveThread(Int32 port, String multicastID, String multicastPort)
{
telemetryPort = port;
mIP = multicastID;
mPort = Int32.Parse(multicastPort);
}
public void handleConnection()
{
SafeMobileLib.Utils.WriteLine("TelemetryReceiveThread initialized on port " + telemetryPort);
udpClient = null;
try
{
udpClient = new UdpClient();
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, telemetryPort));
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("TelemetryReceiveThread handleConnection exception: " + ex.ToString());
}
try
{
udpMulticast = new UdpMulticast(mIP, mPort);
SafeMobileLib.Utils.WriteLine("TelemetryReceiveThread successfully registered to multicast group");
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("TelemetryReceiveThread exception while joining the multicast group: " + ex.ToString());
}
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receivedBytes = udpClient.Receive(ref remoteIpEndPoint);
char[] separator = { '.' };
string[] su = remoteIpEndPoint.Address.ToString().Split(separator);
uint radioID = (Convert.ToUInt32(su[1])) * 256 * 256 + (Convert.ToUInt32(su[2])) * 256 + Convert.ToUInt32(su[3]);
string suid = radioID.ToString();
int seqNo = receivedBytes[0] * 256 + receivedBytes[1];
String seqID = TelemetryConfirm.getFromConfirmationQueue(seqNo);
SafeMobileLib.Utils.WriteLine("TelemetryReceiveThread received data from radio " + radioID + ", with seq ID " + seqID);
Utils.printBytesArray(receivedBytes, ConsoleType.TELEMETRY);
//put information on message bus
string sequenceID = "";
Byte[] toSendMulticast = Utils.createMulticastMessage(233, suid, receivedBytes, out sequenceID);
udpMulticast.Send(toSendMulticast, toSendMulticast.Length);
SafeMobileLib.Utils.WriteLine("TelemetryReceiveThread successfully sent data to message bus");
Thread.Sleep(100);
}
catch (Exception e)
{
SafeMobileLib.Utils.WriteLine("##### TelemetryThread Exception #########\n" + e.ToString());
}
}
}
}
}