Mono SerialPort with infiniteTimeout on Read - c#

I have a device that responds async, on event that occurs on the device it sends a status over serial to the host.
So as mono does not have DataReceived event implemented i created a thread "PollRun" in which i have:
void PollRun(object param)
{
byte rcvResponse = 0x00;
_serialPort.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout;
while (true)
{
rcvResponse = _serialPort.ReadByte();
// SOME handle code...
}
}
The poll run works ok until some point... poll run is a separate thread in the application, but what it happens when i run this application after some inactivity time from the user (eg. no key press on the console app in the main thread....) it stops to work, like if the readByte blocks the whole application
Also no ctrl-c signal helps... I have to manually kill the process.
I'm using ubuntu 11.10 with mono 2.10.5
Is there any known issue with using infinite timeout ? What other way would you do this kind of reading where i must wait for event always?
Thank you!

Related

C# TCPListener stops listening after idle phase

I'm trying to figure out why my clients sometimes cannot connect to the Server after the listener was running some time without any client tried to connect.
The only way to fix it, is to restart the TCP listener - the server.
There are no issues if I start the server and some people connect, do stuff and disconnect later.
I have a simple while loop to accept the incoming socket connections:
while (IsOn)
{
try
{
if (!tcpListener.Pending())
{
Thread.Sleep(100);
continue;
}
Socket socket = tcpListener.AcceptSocket();
if (socket != null)
{
TcpClient client = new TcpClient();
client.Client = socket;
IncommingClientConnection(client); // Nonblocking Code
}
}catch(Exception e)
{
NetLog.Exception(e, "An error occured while user connected!");
}
}
The last time the error occured was after around 8 hours of idle time. Sometimes it happens earlier.
I tried to debug this issue but the listener thread was still running and it seems like it hangs on
tcpListener.AcceptSocket()
.
I've read that this could be fixed by setting up a Windows Service but this would be a lot of work for now. But isn't there any other way to force the Listener to stay opened?
Any suggestion is highly appreciated, thanks!
I figured out what the error was. It is so ridiculous because why should a freezed thread has something to do with "Console.WriteLine()"?!
The Problem was, that the Console Window on Windows Server 2016 somehow changes to input mode. The thread then blocks on "Console.WriteLine" and waits for the user to press Enter on Console Window?! I tried some scenarios. Even If I did not touch the Remove-Desktop for some time this issue occured.
Solution: Switch from Console Application to Windows Application and track output in the integrated Console-View of your IDE.
I hope this helps someone...

Android (C#) -- Service for incoming udp-broadcasts

I'm pretty new to Android programming that's why I need your advice.
Current Situation:
I built an Android application (C#) aswell as a regular Server application (C++) which runs on a Raspberry Pi. Both programs communicate via UDP. At the moment that the Server application receives a signal it sends out a broadcast message which the Android application is listening for. Everything works just fine to the moment that the Android device falls asleep/goes idle which leads to my question.
Question:
How can I accomplish that the Android applications' listener still works, when the device falls asleep? I do not expect any solutions but any kind of advice so I don't waste time with wrong approaches.
Research:
- I read about and tried services that will keep running in the background but the service also stopped as the device went to sleep.
- I read about Broadcast Receivers which allow the application/service to get further information of the system.
- I read about WAKELOCK which allows me to keep the CPU alive, but for my purpose it should be up 'all the time' and that would drain to much energy.
Code that I would like to run in the background:
public void AsyncReceive()
{
// ...
Task.Run(() =>
{
while (this.isActive)
{
byte[] buffer = new byte[1];
DatagramPacket incoming = new DatagramPacket(buffer,
buffer.Length);
try
{
sock.Receive(incoming);
}
catch (...)
{
// Exception handling goes here...
}
// Communicate with the Android application
this.FireBroadCastReceivedEvent();
}
});
}
Edit
I also need to notice the application about incoming messages (#the 'FireBroadCastReceivedEvent()' part of the code). What would be a good way to do that?
I think you must read this link : https://developer.android.com/training/run-background-service/index.html
Hope you find what are you looking for.

TClientSocket in Delphi persistent connection

I have an application written in Delphi using TClientSocket that is sending data to another application written in C#. For many reasons, the C# application is slow to respond, blocking my Delphi application and not respecting the time-out I have set.
My Delphi application reads responses like this:
Sock.Socket.ReceiveText
This causes the application to wait for a response. But if I do this instead, the application waits and respects the time-out:
while not receiveData do
begin
if Sock.Socket.ReceiveLength > 0 then
begin
receiveData := True;
end;
Inc(Cont);
Sleep(100);
if (Cont > 10) then
raise Exception.Create('Timeout');
end;
My Delphi app sends two requests. The first one times out, but C# is still processing it. My Delphi app then sends the second request, and this time C# sends the response for the first request.
Will the second request receive data for the first request? Or, when I timeout in Delphi, will they cross information?
Once your Delphi code times out, it forgets about the first request, but your C# code does not know that. Since you are not dropping the connection, the second request will indeed receive the response data for the first request. By implementing timeout logic and then ignoring the cause of the timeout, you are getting your two apps out of sync with each other. So, either use a longer timeout (or no timeout at all), or else drop the connection if a timeout occurs.
As for your Delphi app freezing, that should only happen if you are using the TClientSocket component in blocking mode and performing your reading in the context of the main UI thread. You should not be using blocking mode in the main UI thread. Either:
Use TClientSocket in non-blocking mode, do all of your reading in the OnRead event only, and do not read more than ReceiveLength indicates.
Use TClientSocket in blocking mode, and do all of your reading in a worker thread, and then signal the main UI thread only when there is data available for it to process (better would be to process the data in the worker thread, and only sync with the main thread when making UI updates).

release COM port after killing process

I have a C# application that uses D-Link GSM Modem to send/receive SMS messages.
Now for some reason the D-Link USB gets disconnected and reconnected automatically after some time (random). When it re-connects it opens up the D-Link Connection Manager which reserves the COM4.
Now when my application run and tries to send SMS it fails, because it doesn't find any available (already in use my D-Link Manager).
when i tried as at application load if the D-Link Process is there I'm killing it using process.kill(). That kills the application but still the COM4 remains inaccessible.
Is there a way to kill the process and release the COM port also programmatically ?
Killing a process doesn't give it a chance to clean up. It is easy for COM ports to get hung up if clients terminate abnormally.
Try Process.CloseMainWindow. Hopefully, the process will respond by shutting down normally and closing the COM port. You would have to give it some time to shut down, though, for which you could use Process.WaitForExit.
The SerialPort class implements IDisposable for exactly this reason: to clean up unmanaged resources (like the port itself) when the port variable goes out of scope.
using (var serialPort = new SerialPort())
{
// Set the read/write timeouts
serialPort.ReadTimeout = 500;
serialPort.WriteTimeout = 500;
serialPort.Open();
// do something
}
It won't always get cleaned up when you kill the process, but this way, you're giving it a fighting chance.
one should blame poorly designed operating system for not being capable to clean the resources of the process after killing it

How can I react to windows waking from sleep mode in a wpf application?

I have a simple messaging wpf application that listens to a wcf duplex service to receive messages. I have coded it so that if the network fails (or I disconnect the LAN cable) it reconnects to the service which works well.
My problem is, when Windows goes into sleep mode it fails to try to reconnect. I suspect this is because my timer for polling the network is put to sleep and therefore the polling stops.
So, is there a way to react to a "Windows has woken up" event or similar?
I finally found what i wanted, a simple, managed code way to react to the system resume event...
Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume)
{
//Do Some processing here
}
}
The (major) benefit of this approach over p/invoke is that ir works across OS's (I need no extra handling for Windows XP & Vista) and, of course, it's rather more consice!
Have you seen http://www.codeproject.com/KB/system/OSEvents.aspx ?
It is coded in C++, but I believe it uses only Win32API, so using P/Invoke you should be able to use the code in your application. :)

Categories

Resources