Snippets

B4T Games Epic Roller Coasters Telemetry Receiver

Created by Lennon R. Bisolo
class EpicRollerCoasters_TelemetryReceiver
{
    // Launch Options: -telemetry network
    // Launch Options: -telemetry network -port 7701
    // Launch Options: -telemetry network -ip 127.0.0.1 -port 7701

    // Default port: 7701
    private static int port = 7701;

    private static UdpClient client;
    private static IPEndPoint anyIP;

    public static string lastReceivedUDPPacket = "";

    static void Main(string[] args)
    {
        anyIP = new IPEndPoint(IPAddress.Any, 0);
        client = new UdpClient(port);

        Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
        receiveThread.IsBackground = true;
        receiveThread.Start();

        // Holds the MainThread while looking for data
        receiveThread.Join();
    }

    private static void ReceiveData()
    {
        while (true)
        {
            try
            {
                byte[] data = client.Receive(ref anyIP);

                string text = Encoding.UTF8.GetString(data);

                // Latest UDPPacket
                lastReceivedUDPPacket = text;
                //Debug.Log(">> " + lastReceivedUDPPacket);

                // UDPPacket output example:
                // S[027.559]Y[-004.332]P[165.854]R[-054.661]W[000.007]H[000.000]U[027.559]
                // S[027.694]Y[-004.398]P[165.538]R[044.135]W[-000.072]H[-000.071]U[027.694]

                float speed = ParseNumber("S", lastReceivedUDPPacket);
                float yaw = ParseNumber("Y", lastReceivedUDPPacket);
                float pitch = ParseNumber("P", lastReceivedUDPPacket);
                float roll = ParseNumber("R", lastReceivedUDPPacket);
                float heave = ParseNumber("H", lastReceivedUDPPacket);
                float sway = ParseNumber("W", lastReceivedUDPPacket);
                float surge = ParseNumber("U", lastReceivedUDPPacket);

                Console.WriteLine(">> Speed: {0}, Yaw: {1}, Pitch: {2}, Roll: {3}, Heave: {4}, Sway: {5}, Surge: {6}",
                    speed, yaw, pitch, roll, heave, sway, surge);
            }
            catch (Exception err)
            {
                Console.WriteLine("[UDPReceive] Error: " + err.ToString());
            }
        }
    }

    // Parse the packats
    private static float ParseNumber(string prefix, string data)
    {
        string numberRx = @"\-*\d{3}\.\d{3}";
        string dataBlockRx = @"\[" + numberRx + @"\]";

        string value = new Regex(prefix + dataBlockRx).Match(data).Value;
        float number = float.Parse(new Regex(numberRx).Match(value).Value, CultureInfo.InvariantCulture);

        return number;
    }
}

Comments (0)