1  /  1  页   1 跳转 查看:1140

Mono C# Serial Port problem

Mono C# Serial Port problem

HI, currently I am porting a windows app to linux using Mono. I have some
difficulties to get the serial port work. here is the code(based on mono
website):

public static void Main(string[] args)
    {
        SerialPortTest myTest = new SerialPortTest();
        myTest.Test();
             
    }

    private SerialPort mySerial;

    // Constructor
    public SerialPortTest()
    {
    }

    public void Test()
    {
        Console.WriteLine("Begin");
        if (mySerial != null)
            if (mySerial.IsOpen)
                mySerial.Close();

        mySerial = new System.IO.Ports.SerialPort("COM3", 9600, Parity.Even,
7, StopBits.One);
        mySerial.Open();
        mySerial.DtrEnable = true;
        mySerial.RtsEnable = true;
        mySerial.Handshake = System.IO.Ports.Handshake.None;
        mySerial.ReadTimeout = 400;
        Thread t = new Thread(new ThreadStart(DataReceived));

        t.Start();
        string tmp = "5D.1";
     
        SendData(tmp);

        // Should output some information about your modem firmware
        //Console.WriteLine("Baaa");
      // Console.WriteLine(ReadData());
    }

    public void DataReceived()
    {
        while (true)
        {
            byte tmpByte = 255;
            string rxString = "";
            //int tot = mySerial.BytesToRead;
            tmpByte = (byte)mySerial.ReadByte();
           
            while (tmpByte != 255)
            {
                rxString += ((char)tmpByte);
                mpByte = (byte)mySerial.ReadByte();
            }
              if (!string.IsNullOrEmpty(rxString))
                  Console.WriteLine(rxString);
        }
        //return rxString;
    }

I ran this under windows using .netframwork run time, it is fine but under
mono I always got this exception:


Unhandled Exception: System.NullReferenceException: Object reference not set
to an instance of an object
  at (wrapper managed-to-native)
System.IO.Ports.WinSerialStream:ClearCommError
(int,System.IO.Ports.CommStat&)
  at System.IO.Ports.WinSerialStream.get_BytesToRead () [0x00000]
  at System.IO.Ports.SerialPort.get_BytesToRead () [0x00000]
  at (wrapper remoting-invoke-with-check)
System.IO.Ports.SerialPortet_BytesToRead ()
  at SerialPortTest.DataReceived () [0x00000]




I have also tried BytesToRead, Read, ReadByte, all of them are working fine
under windows using .net2.0 framwork. But once I use the mono runtime, the
nightmare begins.

Any help will be really apprecaited!

Thanks 

========================================================

In Linux to use a device the user who requires access should have the
permission to use it.
So you must verify that the user starts the application is registered in the
group owner of ttysN.
To find out the group owner of the device by a shell run the command below:


=========================================================

I haven't tried it under linux yet. What I meant is when I ran the
exeutable, if I use "mono test.exe" through windows xp's command line, it
will generate this error. However, if ran this exe directly (use "test.exe"
only on the command line without mono), it worked fine.

Any ideas?

========================================================


Hi,

We also have problems with the serial port under OSX.  We had to re-implement most of the serial port unsing posix call.


Can you actually get any data out of the port ?

Shawn Schaerer
Director of Research and Development
Cogmation Robotics Inc
www.cogmation.com

=================================================

Shwn: Do you have this reimlemenation of serial n OsX on the net? is
it free software?

==================================================================


Hi,

No we do not have it on the web, but we are willing to put it up and or submit it to the mono-project.






Shawn Schaerer
Director of Research and Development
Cogmation Robotics Inc
www.cogmation.com

==================================================

Ok, it will be really useeful for us because we are working on porting
our program to OSX without success.

Please, let me know when you publish it

Thanks




Thanks




Thanks
ls-al / dev / ttyS *
Sinoprise Network Studio
        ----专注.NET技术
 

回复: Mono C# Serial Port problem

Would it be possible to turn this new implementation into something that
would fix the existing System.IO.Serial implementation?

We do not really use serial devices so we barely touch this code, most
of the code in that namespace has been written and later fixed by people
that have had a particular problem that they absolutely had to have


fixed.

===============================================================


Hi,

We could turn this into a new implementation.  The serial port is a major component robotics.


The issue with our code is that we call the Mono posix libraries, this is not cross platform.


Is this a problem ?  If not we can work on the new serial port implementation.


In any case we will put it up on our site in the next couple of days


Shawn Schaerer
Director of Research and Development
Cogmation Robotics Inc
http://www.cogmation.com








On 20-May-08, at 4:04 PM, Miguel de Icaza wrote:

======================================================

Shawn,

I don't know whether it's helpful, but the RXTX implementation of the
JavaComm API is available on a huge range of platforms - and it runs
under Mono after IKVMC'ing it.

Since the portability of the native code is your issue you may want to
take a look at what they have.  The .NET underlying native code
requirements can't be much different from Java's - there's not much
imagination to be applied to serial ports.  If you could reuse it with
or without modifications, you'd have a well tested, portable, base.

Jim
Sinoprise Network Studio
        ----专注.NET技术
 

回复: Mono C# Serial Port problem

Hello,


>
> The issue with our code is that we call the Mono posix libraries, this
> is not cross platform.


Our implementation uses the Win32 api in windows and posix calls with a C helper layer in Unix platforms.

Observe that we never tested it with Mac.

Since you are using the Mono.Posix library in Mac, it's likely possible
to use the same functionality using our C helper layer (it resides in
mono/support/serial.c). Probably we need to apply a pair of corrections
there, however.

Carlos.


==============================================================


Thanks.,

I will look in to it and see if we canfix the osx version.  Most likely it is a tty setting that has not beenset,  in OSX Unix there are a couple of settings that need to be set orthe port does not work.

Shawn Schaerer
Director of Research and Development
Cogmation Robotics Inc
www.cogmation.com

========================================================

I'm actually having the same problem. I'm using ubuntu 8.04.

===========================================================================


Hi,

I hope to have our OSX implementation up in the next couple of days.  This implementation should work under linux too!!


I am also looking at the serial.c  source and will try to get that to work under OSX  as well.


I will send the link ASAP.

Shawn Schaerer
Director of Research and Development
Cogmation Robotics Inc
www.cogmation.com


==========================================================

Would you mind filling a bug with the precise information?

Thanks,

===============================================================================

I have the same problem.
I compile the code located at
http://www.mono-project.com/HowToSystemIOPorts.
When I run it I get this:

Unhandled Exception: System.TimeoutException: The operation has timed-out.
  at System.IO.Ports.SerialPortStream.Read (System.Byte[] buffer, Int32
offset, Int32 count) [0x00000]
  at System.IO.Ports.SerialPort.read_byte () [0x00000]
  at System.IO.Ports.SerialPort.ReadByte () [0x00000]
  at (wrapper remoting-invoke-with-check)
System.IO.Ports.SerialPort:ReadByte ()
  at SerialPortTest.ReadData () [0x00006] in
/home/paceyiv/programmazione/momo/SerialPortTest/SerialPortTest/Main.cs:44
  at SerialPortTest.Test () [0x00062] in
/home/paceyiv/programmazione/momo/SerialPortTest/SerialPortTest/Main.cs:36
  at SerialPortTest.Main (System.String[] args) [0x00006] in
/home/paceyiv/programmazione/momo/SerialPortTest/SerialPortTest/Main.cs:14

I've got Ubuntu 8.04, Kernel Linux 2.6.25
Carlos.




==============================================================================
Hi,

I'm a little scared that you all want to fiddle with SerialPort
implementation. The Win32 and Linux versions work well and are
reasonably stable (there are some little fixes waiting in svn for
inclusion in next mono release - but you have very little chance of
actually bumping into the bugs they pertain to). And I can say they
ARE stable because I have code that communicates with more than 10
classes of COM-attached devices, using various transmission modes,
deployed on hundreds of machines. Believe me when I say the code is
well tested.

I cannot vouch for the OSX version, as we have not Apple machines. But
please do not needlessly throw away good, tested code because of some
anecdotal evidence.

BTW: the post that started this thread contains invalid code: it
creates the SerialPort in one thread and uses it in other. You cannot
do this.
And for the last post: it throws TimeoutException. Indicating that a
timeout occured. Do you actually have anything hooked up to the port
that should respond? Are you sure you got the connection parameters
right? Because the tomeout might just occur because nothing is there


to reply.



===============================================================================

Uhm...

Now I try the code below. It works on Microsoft Visual Studio, but not in
mono on Ubuntu.
It compile it, but when I try to run it I get this error:

Unhandled Exception: System.NotImplementedException: The requested feature
is not implemented.
  at System.IO.Ports.SerialPort.set_ReceivedBytesThreshold (Int32 value)
[0x00012] in
/build/buildd/mono-1.2.6+dfsg/mcs/class/System/System.IO.Ports/SerialPort.cs:410
  at (wrapper remoting-invoke-with-check)
System.IO.Ports.SerialPort:set_ReceivedBytesThreshold (int)
  at ConsoleApplication1.Program.Main (System.String[] args) [0x0004f] in
/home/paceyiv/programmazione/mono/Microsoft/Microsoft/Main.cs:29

So I comment the line!
I think don't work the SerialDataReceivedEventHandler. I can write code to
read the byte from serial and the device respond, but the Serial Data
Received Event newer works on mono.

What's wrong?

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static System.IO.Ports.SerialPort rs232;
       
        static string dati;

        static void Main(string[] args)
        {
            // Setup RS-232
                        rs232 = new SerialPort("/dev/ttyUSB0", 9600);
                        // for Win
            //rs232 = new SerialPort("COM3", 9600);
            rs232.BaudRate = 9600;
            rs232.Parity = Parity.None;
            rs232.DataBits = 8;
            rs232.StopBits = StopBits.One;
            rs232.Handshake = Handshake.None;
                       
                        //rs232.ReadTimeout = 2000;
                        //rs232.ReadBufferSize = 1024;
            //rs232.ReceivedBytesThreshold = 1; // This don't work in mono!
            rs232.DataReceived +=
                new SerialDataReceivedEventHandler(rs232_DataReceived); //
This don't work in mono!

            // Open SerialPort
                        try
                        {
                                rs232.Open();
                                // Do I really need this?
                                //rs232.DiscardInBuffer();
                                //rs232.DiscardOutBuffer();
                               
                                // Dealy for my specific device
                                Thread.Sleep(1500);
                        }
                        catch (System.IO.IOException ioe)
                        {
                                Console.Write(ioe.Message);
                                Environment.Exit(1);
                        }

                        // survive to Microsoft  :)
                        //CheckForIllegalCrossThreadCalls = false;
                       
                        // Send command to read some date from the device
            rs232.WriteLine("A");

            string m;
            bool continua = true;
            while (continua)
            {
                m = Console.ReadLine();
                if (m=="q")
                {
                    continua = false;
                }
            }

        }

        static void rs232_DataReceived(object sender,
SerialDataReceivedEventArgs e)
        {
            dati += rs232.ReadExisting();
            if (dati.Contains("$"))
            {
                Console.WriteLine(dati);
            }
        }
    }

===========================================================================

The RecievedEvent is not implemented (check the exception...). If you
need to monitor the serial port for incoming data, create a separate
thread for handling the port and use the blocking Read methods.
Remember not to use the port outside the thread that has created it.

Please note that MSDN states that the SerialPort class is not
thread-safe, then happily ignores this and keeps tossing it between
threads in every example.
}

Sinoprise Network Studio
        ----专注.NET技术
 
1  /  1  页   1 跳转

版权所有 Sinoprise Network Studio   Sitemap

Powered by Discuz!NT 2.0.1214    Copyright © 2001-2009 Comsenz Inc.
Processed in 0.125 second(s) , 5 queries. 京ICP备05062328号
返顶部