Learn Serial Port StatusInfo on vb.net

1

I try to establish communication between two computers connected by serial port (COM).

To open the port I do it like this:

Dim puerto As IO.Ports.SerialPort = Nothing
Me.puerto = New IO.Ports.SerialPort
Me.puerto.PortName = Me.cmbPuertoCOM.Text
Me.puerto.BaudRate = 9600
Me.puerto.Parity = IO.Ports.Parity.None
Me.puerto.DataBits = 8
Me.puerto.StopBits = 1
If Me.comEAN.IsOpen Then
   Me.comEAN.Close()
Else
   Me.comEAN.Open()
EndIf

The problem comes when there are times when it tells me that I can not open the port and I see that it is not really open by any other process. This has happened to me even after running the program after turning on the computer.

In PowerShell with the command:

Get-WMIObject Win32_SerialPort

It tells me that the StatusInfo is 2 and what I've searched for is that it's Unknown (Unknown). If I go to the Device Manager and disable and re-enable the port, when I re-run the PowerShell code it tells me that the StatusInfo is 3. I have updated the COM port driver but it remains the same. In fact there are times without turning off the computer even if I open the port and can run the program, if a time passes and I'm not doing anything on the computer there are times that it happens again.

For what it's worth, to close the port I put:

Me.puerto.Close()
Me.puerto.Dispose()

I would like to know if there is a way to disable and re-enable the port from code, or to know the StatusInfo of the port since that program is executed with another one that also connects to another COM port of the same computer and that does work well.

The error I get when trying to open the port is this:

    
asked by Maria 25.05.2017 в 15:15
source

1 answer

1

I give you an example of how to consult the StatusInfo by code:

Dim Scope As New ManagementScope("\.\ROOT\cimv2")
Dim Consulta As New ObjectQuery("SELECT * FROM Win32_SerialPort Where DeviceID='COM1'") ' cambialo por el puerto que necesites
Dim Searcher As New ManagementObjectSearcher(Scope, Consulta)
Dim queryCollection As ManagementObjectCollection = Searcher.Get
'Obtenemos el valor del primer resultado
Dim status As Integer = queryCollection.Cast(Of ManagementObject).First()("StatusInfo")
Console.WriteLine("StatusInfo : {0}", status)

You must add a reference to System.Management in your project, as well as Imports System.Management

Edit

After several tests, the solution is to change the name of the port in the device manager. I suspect that the port that was being used in some way was mapped by some other device, causing the detected problem.

    
answered by 25.05.2017 / 15:47
source