SerialPort in mono in linux not responding to DataReceived event - linux

I am writing an app that uses the serial port exposed by the SerialPort class in mono. What I have written so far works perfect in windows, however in linux the DataReceived event handler is never entered, so I cannot receive any data form my device. I have declared the event handler as follows:
comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
Basically I am exploring good cross-platform options and this is a deal-breaker. Any advise on how to fix this or what is going on?
Edit-
I should also point out that I have tested the serial port and device on linux with other applications and all appears to be working.

Maybe it has changed lastly, but as far as I know, events are not currently implemented in Mono's serial port. You have to make another thread in any flavour to read data from serial port, which happens in blocking manner. Try it and tell if it worked.

On Antanas Veiverys blog you can find two possible ways to solve it.
(2012) By adjusting the mono source code.
http://antanas.veiverys.com/enabling-serialport-datareceived-event-in-mono/
(2013) By not touching the mono source but solving the issue in a derived class.
http://antanas.veiverys.com/mono-serialport-datareceived-event-workaround-using-a-derived-class/
(2014)
However, I encourage you to read Ben Voigts blog post where he ignores using the DataReceivedEvent and instead used the BaseStream async BeginRead/EndRead functions to read data from the serial port.
http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport#comment-840
Implementing and using the given code sample works on both Windows/Unix, so I have tested. And it is more elegant than using the blocking Read() function in a threaded fashion.

mono does not support Event for serialport.
It is shown on mono's website

I have the same problem with SerialPort.DataReceived. Konrad's advice.
using System.IO.Ports;
using System.Threading;
namespace Serial2
{
class MainClass
{
public static void Main(string[] args)
{
Thread writeThread = new Thread(new ThreadStart(WriteThread));
Thread readThread = new Thread(new ThreadStart(ReadThread));
readThread.Start();
Thread.Sleep(200); // TODO: Ugly.
writeThread.Start();
Console.ReadLine();
}
private static void WriteThread()
{ // get port names with dmesg | grep -i tty
SerialPort sp2 = new SerialPort("/dev/ttyS5", 115200, Parity.None, 8, StopBits.One);
sp2.Open();
if(sp2.IsOpen)
Console.WriteLine("WriteThread(), sp2 is open.");
else
Console.WriteLine("WriteThread(), sp2 is open.");
sp2.Write(" This string has been sent over an serial 0-modem cable.\n"); // \n Needed (buffering?).
sp2.Close();
}
private static void ReadThread()
{
SerialPort sp = new SerialPort("/dev/ttyS4", 115200, Parity.None, 8, StopBits.One);
sp.Open();
if(sp.IsOpen)
Console.WriteLine("ReadThread(), sp Opened.");
else
Console.WriteLine("ReadThread(), sp is not open.");
while(true)
{
Thread.Sleep(200);
if(sp.BytesToRead > 0)
{
Console.WriteLine(sp.ReadLine());
}
}
}
}
}

Related

Thread-based on Windows Phone 8

I have some application for iOS and android. And I need port it on Windows Phone 8. We have some abstract thread subsystem, and kernel using threads from this subsystem. All this is C++ code.
The first problem I encountered, that run thread on WP8 aka CreateThread. ThreadPool is not a solution for me because application use thread-based parallelism, not a task-based.
My question is how to start thread on WP8? I thied use .NET Thread class, but it doesn't compiling. May be a do something wrong. Please help me by this.
You should be able to use threads in your Windows Phone application, using the System.Threading.Thread class. Creating a thread is straightforward, pass the method you want to execute to the constructor of the thread, then start it:
public void StartThread()
{
var thread = new System.Threading.Thread(DoSomething);
thread.Start();
}
private void DoSomething()
{
// Do stuff
}
you can initialise thread with a method and then start it like
var asd = new System.Threading.Thread(method);
asd.Start();
void method()
{
// Put your Logic Here .....
}

Spring MessageTemplate Issue

I'm facing a problem after the migration from Spring 2.5, Flex 3.5, BlazeDS 3 and Java 6 to Spring 3.1, Flex 4.5, BlazeDS 4 and Java 7. I've declared a ClientFeed in order to send a sort of "alarm" messages to the flex client. There are three methods those alarms are sent. The first one is via snmp traps, a thread is started and wait for any trap, as one is received an alarm will be sent. The second method is via a polling mechanism, at the beginning of the web application a thread is started and will poll after a constant amount of time the alarms and send them to the client. The third method is the explicit poll command from the user, this will call a specific function on the dedicated service. This function uses then the same algorithm used in the second methods to perform a poll and shall send those alarms to the client.
The problem is that after the migration the first two methods are working without a problem, but the third one doesn't. I suspect there is a relation with the threads. Is there any known issue between messagetemplate and the threads with the new frameworks ?
Here is a snapshot of the used client feed:
#Component
public class ClientFeed {
private MessageTemplate messageTemplate;
#Autowired
public void setTemplate(MessageTemplate messageTemplate) {
this.messageTemplate = messageTemplate;
}
public void sendAlarmUpdate(final Alarm myAlarm) {
if (messageTemplate != null) {
System.out.println("Debug Thread: " + Thread.currentThread().getName());
messageTemplate.send(new AsyncMessageCreator() {
public AsyncMessage createMessage() {
AsyncMessage msg = messageTemplate.createMessageForDestination("flexClientFeed");
msg.setHeader("DSSubtopic", "Alarm");
msg.setBody(myAlarm);
return msg;
}
});
}
}
}
By the three methods I reach this piece of code and the displayed thread name are respectively: "Thread-14", "Thread-24" and "http-bio-80-exec-10".
I solved the problem by creating a local thread on the server to perform the job. Therewith the client feed is called via this new created thread instead of the http-thread.

Is there some kind of equivalent to .NET's BackgroundWorker in Vala?

I'm trying to learn Vala so I'm making a small GUI application. My main language before has been C# so things are going pretty well.
However, I've hit the wall now. I need to connect to an external network server (using GIO) which doesn't answer my client immediately. This makes the GUI freeze up while the program is connecting and doing its thing.
In C# I would probably use a BackgroundWorker in this case. I can't seem to find anything like it for Vala though.
Basically, I have a MainWindow.vala where I have hooked up a signal for clicking a certain button to a method that is creating a new instance of ProcessingDialog.vala. This shows a dialog over the MainWindow that I want the user to see while the program is doing the work (connecting to the server, communicating).
What are my alternatives to make this scenario work?
GIO offers async methods, see an async client for example: https://live.gnome.org/Vala/GIONetworkingSample
If you are not aware of async methods in Vala, try looking at the tutorial: https://live.gnome.org/Vala/Tutorial#Asynchronous_Methods
lethalman's answer above probably makes the most sense, an async request is really going to be your best bet if you're doing a network call. In other cases, you can use Vala's built in thread support to accomplish a background task. It looks like soon enough, there will be a better library available, but this is what's stable.
// Create the function to perform the task
public void thread_function() {
stdout.printf("I am doing something!\n");
}
public int main( string[] args ) {
// Create the thread to start that function
unowned Thread<void*> my_thread = Thread.create<void*>(thread_function, true);
// Some time toward the end of your application, reclaim the thread
my_thread.join();
return 1;
}
Remember to compile with the "--thread" option.

BluetoothChat synchronized onResume Activity lifecycle method, why?

I'm studying right now the bluetooth Android API, and I ran into the BluetoothChat example.
http://developer.android.com/resources/samples/BluetoothChat/index.html
It contains many errors, first of all the simple fact that it uses API 11 but manifest does not force this minimum API.
Other interesting thing is the use of synchronized keyword on Activity lifecycle methods, like on onResume:
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
Why this keyword is used there? Is there any reasonable explanation, or simply the one who wrote the code didn't know that onResume will be called always by the same thread? Or I miss something?
Thank you in advance!
This seems to be a pretty old question, but here's what I think may be going on:
My guess is that it wants to be careful about when "dialogs" return. The BluetoothChat example uses dialogs (as well as an overlay dialog-like activity) for enabling Bluetooth, enabling discovery, and initiating pairing/connections.
I don't know this for sure but I suspect there was a bug where different threads were returning to the main Activity and caused confusion as to how to handle onResume.
What they probably should have done is synchronize a block on an object and used flags to determine the state. That way the intention, state and functionality are more clear -- and the app knows what it should do in onResume;
something like this maybe:
//class fields
private Object myLockObj = new Object();
private boolean isPausedForPairing = false;
public void onResume()
{
super.onResume();
synchronized (myLockObj)
{
if (isPausedForPairing)
{
//handle a "pairing" onResume
}
}
}
However, due to it being an example app, they may have decided to go with something more simple. Example apps don't always follow convention because the idea is to demonstrate the particular code needed for the example. Sometimes following convention might add a lot of "distracting" code. Whether or not you agree with that is up to you though.

j2me network connection

I have read in many places that network connection in a j2me app should be done in a separate thread. Is this a necessity or a good to have?
I am asking this because I could not find anywhere written that this must be done in a separate thread. Also, when I wrote a simple app to fetch an image over a network and display it on screen (without using a thread) it did not work. When I changed the same to use a separate thread it worked. I am not sure whether it worked just because I changed it to a separate thread, as I had done many other changes to the code also.
Can someone please confirm?
Edit:
If running in a separate thread is not a necessity, can someone please tell me why the below simple piece of code does not work?
It comes to a stage where the emulator asks "Is it ok to connect to net". Irrespective of whether I press an "yes" or a "no" the screen does not change.
public class Moo extends MIDlet {
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Display display = Display.getDisplay(this);
MyCanvas myCanvas = new MyCanvas();
display.setCurrent(myCanvas);
myCanvas.repaint();
}
class MyCanvas extends Canvas {
protected void paint(Graphics graphics) {
try {
Image bgImage = Image.createImage(getWidth(), getHeight());
HttpConnection httpConnection = (HttpConnection) Connector
.open("https://stackoverflow.com/content/img/so/logo.png");
Image image = Image.createImage(httpConnection
.openInputStream());
bgImage.getGraphics().drawImage(image, 0, 0, 0);
httpConnection.close();
graphics.drawImage(bgImage, 0, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Edit: I got my answer for the code here.
Edit: I spawned off a separate question of this here.
The problem is that you are trying to do work within the thread that is responsible for running the UI. If you do not use a separate thread, then that UI thread is waiting while you do your work and can't process any of your other UI updates! so yes you really should not do any significant work in event handlers since you need to return control quickly there.
I agree with Sean, but it is not required to have your network connection in a separate thread, just best practice. I think that it's probably coincidental that the connection worked properly after moving it to a separate thread. Either way though, if you want to provide any visual feedback to the user while the connection is happening (which you probably do considering the disparity of lag that users can experience on a mobile network), you should have the networked processing in a separate thread.
It is not mandatory that you do network connections in a new thread,however practically you'll find that it almost always a good idea to do so since network activities could block and leave your app in an unresponsive state.
This is an old article but it speaks about some of the issues involved in networking and user experience.

Resources