c# SerialPort suddenly stops receiving data and unable to reopen - c#

I have a curious problem that i cant make sense of.
Here the facts:
.net 5 Project published as arm32 linux self contained
Running on a Raspberry pi Compute module
in one case that we cant provoke at the moment, the serial port stops receiving data and sent data seems not to reach the target.
the described process runs 24/7 for month without error.
as a attempt to solve this we implemented a watchdog that tries to reinstanciate the SerialPort in this case. But it doesnt solve the problem. a connection to the Serial port can only be regained by restarting the process.
The serial port fir all properties looks open and alive, just with the caveat that data issnt received and sent.
i have no more idead how this problem happens and how to prevent it.

Related

NDde server stops getting OnAdvise callbacks after a while

I am using NDde (http://ndde.codeplex.com/) library to set up a server that receives real-time data through a TCP socket and exposes it through DDE protocol.
It certainly works well, but after a random time (between 2 and 20 minutes) it stops updating the data on DDE clients.
Once it stops responding, I can see int the logs that the TCP data is pushed as expected, and my NDde server calls the Advise method properly. No exceptions are thrown at all.
The problem seems to be in the callback, debugging the library source code seems that ProcessCallback method is not being called anymore.
My system setup is a Windows Server 2012 64 bits
I got the same problem and can't find any solution to fix it. However, for a workaround, I will listen to the update event, and when it is stopped, I will re-initialize the Client object and it should work again.
Not a best solution but it resolves for my problem. Any solution that helps on the root one, will be still really appreciate.

What happens to a socket on suspend/resume in windows

I have a c# .net4 application that listens on a socket using BeginReceiveFrom and EndRecieveFrom. All works as expected until I put the machine to sleep and then resume.
At that point EndReceieveFrom executes and throws an exception (Cannot access a disposed object). It appears that the socket is disposed when the machine is suspended but I'm not sure how to handle this.
Do I presume that all sockets have been disposed and recreate them all from scratch? I'm having problems tracking down the exact issue as remote debugging also breaks on suspend/resume.
What happens during suspend/resume very much depends on your hardware and networking setup. If your network card is not disabled during suspend, and the suspend is brief, open connections will survive suspend/resume without any problem (open TCP connections can time out on the other end of course).
However, if your network adapter is disabled during the sleep, or it is a USB adapter that gets disabled because it is connected to a disabled hub, or your computer gets a new IP address from DHCP, or your wireless adapter gets reconnected to a different access point, etc., then all current connections are going to be dropped, listening sockets wil no longer be valid, etc.
This is not specific to sleep/resume. Network interfaces can come up and go down at any time, and your code must handle it. You can easily simulate this with a USB network adapter, e.g. yank it out of your computer and your code must handle it.
I've had similar issues with suspend/resume and sockets (under .NET 4 and Windows 8, but I suspect not limited to these).
Specifically, I had a client socket application which only received data. Reading was done via BeginReceive with a call-back. Code in the call-back handled typical failure cases (e.g. remote server closes connection either gracefully or not).
When the client machine went to sleep (and this probably applies to the newer Windows 8 Fast Start mode too which is really just a kind of sleep/hibernate) the server would close the connection after a few seconds. When the client woke up however the async read call-back was not getting called (which I would expect to occur as it should get called when the socket has an error condition/is closed in addition to when there is data). I explicitly added code on a timer to the client to periodically check for this condition and recover, however even here (and using a combination of Poll, Available and Connected to check if the connection was up) the socket on the client side STILL appeared to be connected, so the recovery code never ran. I think if I had tried sending data then I would have received an error, but as I said this was strictly one-way.
The solution I ended up using was to detect the resume from sleep condition and close and re-establish my socket connections when this occurred. There are quite a few ways of detecting resume; in my case I was writing a Windows Service, so I could simply override the ServiceBase.OnPowerEvent method.

Getting error only first time I communicate with my SerialPort later on its working fine

I have a USB device (e.g. barcode scanner etc.)
I communicate with it using SerialPort (which is found nicely from toolbox of VS2008)
My problem is:
After starting my PC when starting my application for the first time it is hanging up or stuck up or going into not responding mode when it tries to sending a string to the serial port.
To come out of it I just remove the USB cable from the USB port of my PC.
As soon as I remove the cable I getting below error message:
If I press the Continue button plug the removed USB cable back in my application working fine.
Note: I am getting this error only when I start my app first time after starting or restarting my PC. Afterwards it's working fine as I wanted.
Note: Another thing to consider is that if I put my code in try and catch
I catch the exception only when I remove the USB cable from my PC.
Edit:
After restarting my PC, if I do
plug out and then plug in the USB cable from the USB Port of the PC, and then
I start my App then it's working fine
It seems to me that the control is going inside an infinite loop when i try sending a string to the serial port at the very first time after starting of the PC.
See the details of my code over here
The 90% odds here are that you are trying to work around a common deadlock scenario with SerialPort. It is common to get triggered when you use Invoke() in your DataReceived event handler. If you then use Close() in your main thread while the port is busy receiving data then a deadlock is common. Close cannot complete until the DataReceived event handler completed running, Invoke() cannot complete because the main thread is stuck in the Close call. Jerking out the connector works because the ThreadExceptionDialog pumps messages, allowing the Invoke to complete.
A simple workaround is to use BeginInvoke() instead. Just not calling Close is fine too, Windows takes care of it when your program terminates. Some sort of controlled shutdown of your app so that you don't lose anything sent by the serialport device is best.
You must close the serial port in the FormClose event. Because, port is once open your application and close the port on the application end

SerialPort.GetPortNames() behavior

In my C# 2008 application, I use the SerialPort.GetPortNames() function to retrieve the list of currently available ports. What I have noticed is, when ever I plug in a USB device, it's port number i s shown in the list on my Application and when I unplug it and refresh the list, the port number is no longer there.
One phase of the application involves reading/writing data from/to the device continuously. Now, my expectation is, If I unplug the device during the operation and get the current Port list using SerialPort.GetPortNames(), the Port Name will not be there and I can use that to make the decision that the device has been unplugged.
To my surprise, the Port name is still found despite having it removed
Why is the program behaving like this? The port name isn't listed when in no-communication mode. Does it have something to do with the device being removed when it's communicating?
You have to be talking about SerialPort.GetPortNames(), "GetPortList" doesn't make sense. The function iterates values in the registry, written there by your USB emulator device driver. You can have a look-see with Regedit.exe, navigate to HKLM\Hardware\DeviceMap\SerialComm. Unplug it, press F5, if the COM port is still there then SerialPort doesn't know any better than the port still being present.
There is no prescribed behavior as to how a serial port device driver should behave when the port suddenly vanishes. Serial ports are very primitive, they date back to an era where "bug" meant a moth gumming up the teletype. There is no hardware support at all for Plug and Play, removing a port with the power turned on is equivalent to unplugging the disk drive while Windows is swapping to the paging file.
Most device drivers return an error code, it generates an uncatchable exception that crashes your program. The subject of this feedback article. Apparently your device driver doesn't do that, which ought to be preferable over bombing your program. Encouraging btw, most USB emulator device drivers are utter junk.
The ultimate workaround is simple: put a little tag on the plug "don't disconnect while in use!" It's kinda of a problem with USB, most people look at it and go "hmm, what can I do with it?". And arrive at the only answer and unplug it. After a couple of kabooms, they'll learn to not do that anymore.
I'm assuming you mean System.IO.Ports.SerialPort.GetPortNames(), because i could not find a GetPortList() function anywhere. MSDN says: "If the registry contains stale or otherwise incorrect data then the GetPortNames method will return incorrect data", so that's probably where the problem lies. I guess Windows doesn't update the registry if the port is still being 'used', just like you can't delete a file when a program has a handle on it.
If you want to test if the device is removed, you can do so with a Window API call (http://www.pinvoke.net/default.aspx/user32/RegisterDeviceNotification.html). Hope that helps!
It is correct that GetPortNames() reads the ports from the Registry key
HKLM\Hardware\DeviceMap\SerialComm
This is automagically updated by Windows every time a port is opened or closed.
But nevertheless it has happened to me that there is a non-existent Port listed in the Registry, and also returned from GetPortNames(). When I try to open this port I get "The Port XYZ does not exist".
What is that ???
I now found out the reason:
This happens always after using PortMon from www.sysinternals.com.
This tool is buggy and lets the dead port hanging around in the Registry if the port is closed while it is monitored.
In this case the only remedy is to reboot the computer.
As others have mentioned, it's very driver-specific. There does not appear to be a way to check with the .Net API whether a port returned by GetPortNames() actually exists and is valid.
As for why the ports behave like this, I have found that some USB-to-serial drivers cause the application to crash when the port is unplugged suddenly.
Other drivers, often those that do not crash, will keep the port in the list until your application closes it, then it disappears. Trying to read from or write to the stale port will (usually) cause timeouts or errors. Presumably, in order not to crash the application, the driver needs to keep the stale port around while it is still open in the application.
If you plug in the port again, some drivers are even be able to reconnect it to your application, others will not recognize the port until your application closes the stale port. This reconnecting behaviour can be somewhat dangerous if the port disappeared because the device rebooted, because then it will suddenly be in a different state than your application expects without an obvious indication that it has reset. At least if you get errors from the port you know that something happened.
I've also found that if I forget to close the port, it won't disappear from the list until the garbage collector gets around to disposing the SerialPort object.

Serial port stops receiving data after certain amount of time on Windows 10

Since couple of months I am a developer of quite big vehicle weight measurement system. System is designed as distributed software (based on .NET) and has many components which communicate using RabbitMQ. This information is just for an general overview.
Our real devices communicates with System Local Services using TCP Sockets and Serial Ports available in Windows. We did not have any communication issues so far, but recently we installed our software on industrial terminal with Windows 10 Professional installed on it.
I face big issues with scale communication using Serial Port. Scale is designed to send data frame containing the value, over and over again, indefinitely, through Serial Port (RS232). My program receives the data and everything is working as expected (one way communication, I do not send anything to scale). The problem is, after approx. 1 hour, data stops to be received by program - no value updates appear. If I close and reopen an application, everything gets working again and after ~1 hour same happens.
Once, when communication was stuck, I've unplugged the RS232 cable and plugged in again after 1-2 minutes - application started receiving data again - no restart was required. I've even ended up with some dirty hack like following:
if same frame is being received by program for n minutes, close and reopen port connection - unfortunately still no luck (I know this is bad approach anyway). All power saving settings were disabled in Windows. The program runs on other machines without a hassle. Problem occurs on this one particular industrial terminal (with touch screen) only. Have you maybe faced similar issues? I am missing further ideas and I am getting frustrated...
Thanks in advance!

Categories

Resources