runtime icon indicating copy to clipboard operation
runtime copied to clipboard

System.IO.Ports SerialPort.IsOpen on Linux (Raspbian) returns `true` when USB is not plugged

Open tester346 opened this issue 6 years ago • 8 comments

Hi!

I've been messing with connecting USB based card scanner to my raspberry pi and handling from C# app things like detecting port when user disconnects device and plugs it again

everything worked fine on Windows, but on Linux I noticed that my method

	public bool IsOpen()
	{
		return USB != null && USB.IsOpen;
	}

doesn't exactly work as intended. For some reason USB.IsOpen is returning True when my device is unplugged.

I found that on Linux devices are treated as files, so I came with this work around

	public bool IsOpen()
	{
		var result = USB != null && USB.IsOpen;

		// on windows everything works fine
		if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			return result;

		// if result was false, then it was correct even on linux, because the reason of it probably was that USB is null
		if (!result)
			return false;

		// if on Linux it was TRUE, then it was probably incorrectly reported by USB.IsOpen(), then we can ensure that file exists
		var exists = File.Exists(PortName);

		return exists;
	}

I don't think it is completed solution for this problem, but I'd just want to report it.

.NET Core 3.1

PRETTY_NAME="Raspbian GNU/Linux 10 (buster)"
NAME="Raspbian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=raspbian
ID_LIKE=debian

Thanks for reply!

tester346 avatar Jan 23 '20 14:01 tester346

Remarks The IsOpen property tracks whether the port is open for use by the caller, not whether the port is open by any application on the machine.

I would expect the device to disappear from /sysfs when disconnected and then disappear from list of ports. Does it not? cc: @krwq

wfurt avatar Jan 23 '20 19:01 wfurt

@tester346 does the device file disappear from /dev/ when you unplug? We rely on the OS to tell us if the file is open so we would likely need to do something special to get it to work correctly if we even can detect it.

krwq avatar Jan 26 '20 05:01 krwq

@krwq

Hi!

I'll provide code & screens, and flow:

I'm starting Raspberry Pi with 3rd device connected via usb connected

then I'm starting this simple console app which finds which port is used by 3rd party device (basing on response)

and then I'm displaying date in while (USB.IsOpen) loop.

The thing is, that this loop doesn't end even when I disconnect device and there is no file in /dev/

Before unplugging (as you can see on right screen shoot there's device called ttyUSB1 before

After unplugging (there's no file cuz USB is disconnected) after

And as we can see the program is still looping, but it shouldnt.

FULL Code without my custom method (code below, below):

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

    namespace usb_report
    {
        class Program
        {
            static void Main(string[] args)
            {
                var port = FindPortNameWhereDeviceIsConnected();

                if (string.IsNullOrEmpty(port))
                    throw new Exception("Cannot find device");

                Console.WriteLine($"Used port: {port}");

                var USB = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
                USB.ReadTimeout = 1000;
                USB.Open();
            
                while (USB.IsOpen)
                {
                    Console.WriteLine(DateTime.Now);
                    Thread.Sleep(5000);
                }

                Console.WriteLine("USB connection has ended");
            }

            public static string FindPortNameWhereDeviceIsConnected()
            {
                var ports = SerialPort.GetPortNames();

                foreach (var port in ports)
                {
                    try
                    {
                        var USB = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
                        USB.ReadTimeout = 1000;
                        USB.Open();
                        USB.WriteTimeout = 900;

                        USB.Write(new byte[] { 0x1b, 0 }, 0, 2);
                        Thread.Sleep(100);

                        var read = USB.ReadExisting();

                        if (read.Contains("1290"))
                        {
                            return port;
                        }
                        continue;
                    }
                    catch
                    {
                        continue;
                    }
                }

                return "";
            }
        }
    }

Custom check method:

When I use my own .IsOpen method which inside performs File.Exists then it works fine

My Method used here:

	public static bool IsOpen(SerialPort USB)
	{
		// this probably isnt going to work on Windows, it's just PoC
		return USB.IsOpen && File.Exists(USB.PortName); 
	}

Small change in Loop:

	while (IsOpen(USB))
	{
		Console.WriteLine(DateTime.Now);
		Thread.Sleep(5000);
	}

Output:

result

It stopped looping after I unplugged device

tester346 avatar Jan 27 '20 11:01 tester346

Perhaps possible solution could be that we probe for the file existence whenever the IsOpen is called and manually close the file handle, @wfurt?

krwq avatar Jan 27 '20 19:01 krwq

hmm, any info on that issue?

tester346 avatar Feb 14 '20 12:02 tester346

I'm wondering if we should throw @krwq if the device disappears when in use. When the class was designed long time ago, it was not possible to remove a serial port from the system on the fly. I'll try to do some more testing next week.

wfurt avatar Feb 14 '20 21:02 wfurt

Triage: @wfurt Have you had a chance to do the testing on this?

JeremyKuhne avatar Mar 05 '20 00:03 JeremyKuhne

What I think is happening here is that, when a file in Unix is removed while open by a process, the file name might be removed from the directory that pointed to that inode, but will still exist in the filesystem. It just can't be referenced by another process anymore, but you should still be able to write or read to that file just fine until the process closes it. (In this case it's not really being removed from the filesystem as it's likely to be a devtmpfs -- which is a virtual FS managed by the kernel, that creates and destroy device nodes as they're made available or are not needed anymore -- but the same principle applies.)

lpereira avatar Mar 05 '20 00:03 lpereira