Why is the SerialPort SerialDataReceivedEventHandler not being called on Mac application?

WaterDragonWaterDragon USMember
edited January 2017 in Xamarin.iOS

Maybe this is strictly a problem with Mac OSX and C#, but the SerialDataReceivedEventHandler is not functioning as advertised. I have a Serial connection that is definitely working properly. I was able to create a SerialPort object and read data from it with a console application. Here is the code below for the event handler. Whenever the event handler is called, it should display "HANDLER CALLED" on the Console. It does not.

class MainClass
{
    public static void Main()
    {
        SerialPort usb = new SerialPort();
        usb.PortName = "/dev/tty.usbmodem1421";
        usb.BaudRate = 9600;
        usb.Parity = Parity.None;
        usb.DataBits = 8;
        usb.StopBits = StopBits.One;

        usb.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        usb.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();

        Console.ReadKey();
        usb.Close();
    }

    private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        Console.WriteLine("HANDLER CALLED");
        SerialPort usb = (SerialPort)sender;
        Console.WriteLine(usb.ReadLine());
    }
}

Answers

  • AndrewFraserAndrewFraser GBMember ✭✭

    I have not tried it but it might be worth explicitly setting the ReceivedBytesThreshold value ?

    Andy

  • WaterDragonWaterDragon USMember

    Unfortunately, that does not work either. I get an error with this line of code:

    usb.ReceivedBytesThreshold = 1;

    The error reads "Mono TODO: Not implemented. When I run the code, the System.NotImplementedException is thrown.

  • WaterDragonWaterDragon USMember

    It appears that this is a problem with Xamarin, C#, and Mac OSX. I am running OS 10.12.3, and I also had this problem on the previous version of the operating system. I was able to run my exact code on a Windows machine, and the handler was called without any issues. Maybe I am missing a setting, and if so, guidance would be much appreciated.

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    As you've noticed, the SerialPort implementation is not complete in mono:

    https://github.com/mono/mono/blob/master/mcs/class/System/System.IO.Ports/SerialPort.cs

    Which explains at least some of the behavior you've seen.

    See - http://www.mono-project.com/archived/howtosystemioports/#limitations

    If you want to drop down to the native APIs, it looks like there are two APIs on macOS that let you work with serial ports:

    • The standard unix style file ones
    • IOKit via IOServiceMatching

    Both of them will involve getting your hands dirty, as neither is simple nor straightforward.

Sign In or Register to comment.