Send int and string by Serial C #

0

I am developing a simulator for Asseto Corsa. I have an API that takes me the telemetry from the shared memory of the game, but I need to send some of that data by serial (USB) to capture them with an Arduino and process them. I have the API code (which is attached below) and the Arduino code is not a problem, the problem is how to send the data I need (ints and strings) through the serial port. I have seen that there is a library (SerialPort) but it is programmed in C ++, and everything I have found about C #, has not worked for me, since the Arduino does not receive anything.

using AssettoCorsaSharedMemory;
using System;
using System.IO.Ports;
using System.Threading;


namespace ConsoleApplication1
{

public class Program
{

static bool _continue;
static SerialPort _serialPort;

public static void Main(string[] args)
{
    AssettoCorsa ac = new AssettoCorsa();
    ac.StaticInfoInterval = 5000; // Get StaticInfo updates ever 5 seconds
    ac.StaticInfoUpdated += ac_StaticInfoUpdated; // Add event listener for StaticInfo
    ac.PhysicsUpdated += ac_PhysicsUpdated; //  Add event listener for Physics
    ac.Start(); // Connect to shared memory and start interval timers 

    Console.ReadKey();

    string name;
    string message;
    StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
    Thread readThread = new Thread(Read);

    // Create a new SerialPort object with default settings.
    _serialPort = new SerialPort();

    // Allow the user to set the appropriate properties.
    _serialPort.PortName = SetPortName(_serialPort.PortName);
    _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
    _serialPort.Parity = SetPortParity(_serialPort.Parity);
    _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
    _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
    _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

    // Set the read/write timeouts
    _serialPort.ReadTimeout = 500;
    _serialPort.WriteTimeout = 500;

    _serialPort.Open();
    _continue = true;
    readThread.Start();

    Console.Write("Name: ");
    name = Console.ReadLine();

    Console.WriteLine("Type QUIT to exit");

    while (_continue)
    {
        message = Console.ReadLine();

        if (stringComparer.Equals("quit", message))
        {
            _continue = false;
        }
        else
        {
            _serialPort.WriteLine(
                String.Format("<{0}>: {1}", name, message));
        }
    }

    readThread.Join();
    _serialPort.Close();

}

public static void Read()
{
    while (_continue)
    {
        try
        {
            string message = _serialPort.ReadLine();
            Console.WriteLine(message);
        }
        catch (TimeoutException) { }
    }
}
public static string SetPortName(string defaultPortName)
{
    string portName;

    Console.WriteLine("Available Ports:");
    foreach (string s in SerialPort.GetPortNames())
    {
        Console.WriteLine("   {0}", s);
    }

    Console.Write("Enter COM port value (Default: {0}): ", defaultPortName);
    portName = Console.ReadLine();

    if (portName == "" || !(portName.ToLower()).StartsWith("com"))
    {
        portName = defaultPortName;
    }
    return portName;
}
public static int SetPortBaudRate(int defaultPortBaudRate)
{
    string baudRate;

    Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
    baudRate = Console.ReadLine();

    if (baudRate == "")
    {
        baudRate = defaultPortBaudRate.ToString();
    }

    return int.Parse(baudRate);
}
public static Parity SetPortParity(Parity defaultPortParity)
{
    string parity;

    Console.WriteLine("Available Parity options:");
    foreach (string s in Enum.GetNames(typeof(Parity)))
    {
        Console.WriteLine("   {0}", s);
    }

    Console.Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString(), true);
    parity = Console.ReadLine();

    if (parity == "")
    {
        parity = defaultPortParity.ToString();
    }

    return (Parity)Enum.Parse(typeof(Parity), parity, true);
}
public static int SetPortDataBits(int defaultPortDataBits)
{
    string dataBits;

    Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
    dataBits = Console.ReadLine();

    if (dataBits == "")
    {
        dataBits = defaultPortDataBits.ToString();
    }

    return int.Parse(dataBits.ToUpperInvariant());
}
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
    string stopBits;

    Console.WriteLine("Available StopBits options:");
    foreach (string s in Enum.GetNames(typeof(StopBits)))
    {
        Console.WriteLine("   {0}", s);
    }

    Console.Write("Enter StopBits value (None is not supported and \n" +
     "raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
    stopBits = Console.ReadLine();

    if (stopBits == "")
    {
        stopBits = defaultPortStopBits.ToString();
    }

    return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
    string handshake;

    Console.WriteLine("Available Handshake options:");
    foreach (string s in Enum.GetNames(typeof(Handshake)))
    {
        Console.WriteLine("   {0}", s);
    }

    Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
    handshake = Console.ReadLine();

    if (handshake == "")
    {
        handshake = defaultPortHandshake.ToString();
    }

    return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
}

static void ac_StaticInfoUpdated(object sender, StaticInfoEventArgs e)
{
  /*Console.WriteLine("StaticInfo");
    Console.WriteLine("  Car Model: " + e.StaticInfo.CarModel);
    Console.WriteLine("  Track:     " + e.StaticInfo.Track);
    Console.WriteLine("  Max RPM:   " + e.StaticInfo.MaxRpm);*/
}
static void ac_PhysicsUpdated(object sender, PhysicsEventArgs e)
{
    String gea = "N";
    switch (e.Physics.Gear)
    {
        case 0:
            gea = "R";
            break;
        case 1:
            gea = "N";
            break;
        case 2:
            gea = "1";
            break;
        case 3:
            gea = "2";
            break;
        case 4:
            gea = "3";
            break;
        case 5:
            gea = "4";
            break;
        case 6:
            gea = "5";
            break;
        case 7:
            gea = "6";
            break;
    }

    Console.WriteLine("  Rpms  " + e.Physics.Rpms + "   Gear  " + gea);

    string str = Convert.ToString(e.Physics.Rpms);
    _serialPort.Write(str);

}
}
    
asked by Victor Casado 08.05.2018 в 12:19
source

0 answers