GPS serial port searcher - c#

I try to search my serial port of my GPS on my tablet (Windows CE).
I know that this is on "COM 3" but I want the program to find this by itself. I mean run in a loop (for) on all ports and search for this.
My question is which "if" I need to write to tell the program "this is my GPS port".
Thank you all.

Gps as i know works with a physical or virtual serial com port (ie com via usb). Since only one application can open a com port at a time there should be no program using gps while searching for the gps-port.
You already gave the answer "loop (for) on all ports and serche for".
Note the example below is an untested scetch how it could work. Feel free to update this wiki page to fix possible errors and add missing functionality.
public string FindGpsPort()
{
foreach(string portname in System.IO.Ports.SerialPort.GetPortNames())
{
// using to make shure that the testport is closed after test
using (SerialPort testport = new SerialPort(){PortName = portname})
{
// maybe neccessary to set baudrate, parity, ... of com port
testport.Open();
// to do if error or exception this is not the
// gps port or some software already uses the gps-port
// to do: read some data from port and verify if it is GPS-Data
// if valid return portname ;
}
}
// All com ports tried but not found. throw exception or return error code
return null;
}

Related

FTDI FTD2xx_NET detects unknown device. CyclePort fails

I want to detect a connected usb device (FT232R USB UART, Virtual com port driver). This usually worked fine, but due to an windows update my device is detected as FTDI_DEVICE_UNKNOWN. Strange behaviour is, that when I first plug in my device and then start the software, everything works fine. If I first start the software and then plug in the device, it it not detected. I tried to use CyclePort to reconnect the device, but this fails with status FT_OTHER_ERROR. The device is detected and displayed in both cases in the windows device manager. Drivers were already updated and also installed manually.
Any ideas as to what is causing this?
Here is my code:
List<string> pcdSerials = new List<string>();
FTDI ftdi = new FTDI();
UInt32 ftdiDeviceCount = 0;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
ftStatus = ftdi.GetNumberOfDevices(ref ftdiDeviceCount);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
return pcdSerials;
}
FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
ftStatus = ftdi.GetDeviceList(ftdiDeviceList);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
return pcdSerials;
}
foreach (var info in ftdiDeviceList)
{
if (info.Type == FTDI.FT_DEVICE.FT_DEVICE_UNKNOWN)
{
if (ftdiDeviceList.Count() == 1)
{
// The effect of this function is the same as disconnecting then reconnecting the device from USB.
// Possible use of this function is in situations where a fatal error has occurred and it is difficult, or not possible, to recover without unplugging and replugging the USB cable. This function can also be used after re-programming the EEPROM to force the FTDI device to read the new EEPROM contents which previously required a physical disconnect-reconnect.
ftStatus = ftdi.CyclePort();
if (ftStatus == FTDI.FT_STATUS.FT_OK)
{
// Port has been cycled. Close the handle.
ftStatus = ftdi.Close();
}
else
{
// FT_CyclePort FAILED!
}
break;
}
}
if (info.Description != "FT232R USB UART")
continue;
if (info.Type != FTDI.FT_DEVICE.FT_DEVICE_232R)
continue;
pcdSerials.Add(info.SerialNumber);
}
return pcdSerials;
This NOT an answer, but a comment. Being new to Stack overflow it wouldn't let me simply add a comment to your question, or I don;t know what I am doing. :)
I am having what sounds like the same issue. I wrote a wrapper class over 10 years ago that has worked fine until the new FTDI driver 2.12.36.1 was updated on client's computers. FTDI released driver version 2.12.36.2 on 6/17/2021 and I was hoping that it would resolve the issue but it did not.
What I have found is that calling FT_CreateDeviceInfoList does return the correct number of devices connected. Then I call FT_GetDeviceInfoDetail to obtain the device type, description, and FTDI serial number. The device type comes back as value 0x03 which is FT_Device_Unknown and the description and serial number appear to come back empty. I use the FTDI serial number to open the device by its serial number. Without a valid serial number, I cannot open the device. I have used this method as outlined as the preferred method by FTDI for years with no issues until now.
Hopefully someone else can chime in with an answer as I have a lot of customers who are unable to connect to my product with their PCs.
I am going to reach out to FTDI support to see if they can shed some light on this problem. I will post back here if I hear something back.
I came across the same problem just recently. If you run FT_prog you can replicate this by removing the dongle and putting it back. FT_prog takes a second or so to recognise the device again.
I put the checking code in a loop with a 1 second wait and it now finds the dongle on the second attempt reliably.

How to check if a Serial port is disconnected in c#

I want to check if a Serial port is disconnected or not after clicking a button in C# WinForms.
Eg:
private void btn_Click()
{
if("code to check device disconnected")
{
Do this;
}
else
{
Do this;
}}
PS: Is there any way to check that the device is disconnected when the application is running.
SerialPinchanged, ErrorRecieved, DataRecieved don't help.
Thank you in advance
It depends on the specifications of the target device connected to the COM port.
For example, if RTS/CTS or DTR/DSR are cross-connected, or if the device equivalent to a modem has a DCD or RI valid signal line, and the CTS/DSR/DCD/RI signal line shows valid connection information. , There may be a case where there is a command/response specification for health check or keep alive.
As an alternative, if the COM port is a USB Serial converter, you can check whether or not the device with the corresponding VID and PID exists, but make sure that the device is actually connected at the end of the converter. There is no guarantee.
It is simple logic that whenever SerialPort is disconnected, serialPort.IsOpen turns to false.
private void btn_Click()
{
if(!SerialPort.IsOpen)//If SerialPort is not open
{
Do this;
}
else//Else if SerialPort is open
{
Do this;
}
}

C# can fail to open STMicro virtual COM port

I have an issue with opening an STMicro USB virtual COM port.
When I plug the device into my PC, the COM port appears as it should, and the Windows Device Manager indicates it is working properly.
I have a C# program on the PC which selects and opens this port.
However, in about 1 in 10 attempts, the PC program sticks on the port.open() command, and after about half a minute, returns with the error "The semaphore timeout period has expired".
I have written a tiny C# program that does nothing more than open the port. This still gives the behaviour noted.
public partial class Form1 : Form
{
SerialPort port = new SerialPort();
string portName = "COM1"; // Give it a default to start with
public Form1()
{
InitializeComponent();
// Populate the COM port selector combobox with available port names
cmbPortSelect.Items.Clear();
string[] activePorts = SerialPort.GetPortNames();
foreach (string availablePort in activePorts)
{
cmbPortSelect.Items.Add(availablePort);
}
// Declare the serial port
port = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
port.ReadTimeout = 100;
}
private void cmbPortSelect_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbPortSelect.SelectedIndex != -1)
{ // It will get set to -1 (i.e. no selection) in the catch below - we don’t want this selected item change to do anything
if (port.IsOpen) port.Close();
port.PortName = (string)cmbPortSelect.SelectedItem;
System.Threading.Thread.Sleep(50);
try
{
port.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
cmbPortSelect.SelectedIndex = -1; // Clear the selected item box
}
}
}
}
If instead of using my C# program to open the port, I use the communications program PuTTY, it works every time.
In addition, if I plug in a device with an FDTI USB virtual COM port, it also works every time.
I'm using Windows 7, with the STMicro VCP drivers ver 1.3.1, but the same behaviour occurs with Windows 10 and the generic Microsoft drivers, which STMicro recommend we use.
There is a version 1.5.1 drivers for Windows 7, but when I installed them, it reported that they had installed correctly, but the Device Manager still reported ver 1.3.1.
Has anyone noted any similar behaviour?
That is seemed to be a timing issue. Try to increase your delay from 50 to, say, 200 ms and check the difference. As the doc says: The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly., sadly, there is no actual time specified.

Why GetPortNames method returns nothing?

I am trying to send an SMS from computer to cell phone.
The first step: get all com ports to use it.
I used this code, but no benefit:
private void Form1_Load(object sender, EventArgs e)
{
string[] Ports = SerialPort.GetPortNames();
foreach (string prt in Ports)
{
comboBox1.Items.Add(prt);
}
}
It returns nothing. What can I do?
I just ran the following code on my PC and it returns "COM1":
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
foreach(string port in ports)
{
Console.WriteLine(port);
}
Console.ReadLine();
So, it's either permissions or you don't have any Serial ports. Or perhaps your registry is corrupt?
Note:
The port names are obtained from the system registry (for example,
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM). If the registry
contains stale or otherwise incorrect data then the GetPortNames
method will return incorrect data.
Ref: SerialPort.GetPortNames
I had the same issue at first. Then realized that I didn't connect any device to my PC which identify themselves as a serial port (either via USB or any other physical port). It displayed accurately when I connected a device (a USB based PIC programmer in my case). Please check if your device is properly detected.

In C# how could I listen to a COM (Serial) Port that is already open?

I am using a program that talks to my COMM port, but I have made another program that I want to "sniff" the comm port messages and perform it's own actions against those messages in addition. Is this possible in .NET c#?
There are third party libraries/tools/products that expose the traffic f you are interested.
Here is one I used for serial port emulation - but I think it provides something you can use:
http://com0com.sourceforge.net/
If you have control over the first program that talks to you COMM port, why not change the program to pass data received from the port to the 2nd program of yours via remoting or any other type of IPC. Better still if you can write a proxy program that connected to the COMM port, and have 2 of the other program talk to this proxy to get the communication done.
Another idea is, if you need to sniff only incoming data, you can get a Y-cable (splitter) and connect to 2 COMM port, each program connects to each COMM port. But you need to make sure the 2nd program is not trying to transmit. In some cases you might need a splitter which only connects the RX pin for the 2nd output. Let me know if you need the diagram.
If you don't have 2 COMM, you can easily get a USB-Serial Converter for less than USD10.
It is possible to sniff traffic from the serial port
However there doesnt seem to be a "COMPortSniffer" Control
A valid technique used by sysinternals is presented there
It seems to rely on Win32 programming however, I dont think such a thing is possible directly with C#
the code project (http://www.codeproject.com/Articles/75770/Basic-serial-port-listening-application) that has a great tutorial on this.
It shows how to read data coming in from a serial port, and from that you should be able to read the data.
A short snippet:
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
// Send data to whom ever interested
if (NewSerialDataRecieved != null)
NewSerialDataRecieved(this, new SerialDataEventArgs(data));
}

Categories

Resources