4

Consider:

Baud rate 19200
RTS on
DTR on
Data bits=8, Stop bits=1, Parity=None
Set chars: Eof=0x00, Error=0x2A, Break=0x2A, Event=0x00, Xon=0x11, Xoff=0x13
Handflow: ControlHandShake=(DTR_CONTROL), FlowReplace=(TRANSMIT_TOGGLE, RTS_CONTROL),
XonLimit=0, XoffLimit=4096

OK, so using a port scanner I've found that a USB device needs these settings to facilitate an import. I can recreate most of these as follows:

port = new SerialPort("COM4");
port.DtrEnable = true;
port.RtsEnable = true;
port.Handshake = Handshake.None;                                  
port.BaudRate = 19200;
port.StopBits = StopBits.One;
port.Parity = Parity.None;
port.DataBits = 8;    

port.Open();

byte[] a = new byte[2] { 0x0 , 0x1 };
port.Write(a, 0, 1);
port.Write(a, 0, 1);
port.Write("mem");
port.Write("mem");

string output = port.ReadExisting();

System.Diagnostics.Debug.WriteLine("Found: " + output);

However, the codes produced are these:

Set chars: Eof=0x1A, Error=0x00, Break=0x00, Event=0x1A, Xon=0x11, Xoff=0x13
XonLimit=1024, XoffLimit=1024

How do I change the X limits, and each of the character codes so that this has a chance of working?

The post SerialPort 0x1A character reading problem is the closest thing I've found so far, but I don't understand it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • You are focusing on the wrong problem. There's no way that ReadExisting() is going to return anything, serial ports are far too slow. Use a blocking call like ReadLine() or use the DataReceived event. The stuff you write looks weird too. – Hans Passant Jan 31 '12 at 04:09
  • I am mimicking another application of which I do not have access to the source code. These are the commands it sends before initiating a data read. Is this wrong somehow? Is there a way to get a usb device to dump all of it's contents into a string? –  Jan 31 '12 at 16:34

2 Answers2

4

You can add an extension to the serialPort in C# - see Xon/Xoff values in NET2.0 SerialPort class.

For the other fields you can change:

dcbType.GetField("XonChar"); // "XonChar", "XoffChar", "ErrorChar", "EofChar", "EvtChar"

Code:

using System;
using System.ComponentModel;
using System.IO.Ports;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;

class Program
{
    static void Main(string[] args)
    {
        using (var port = new SerialPort("COM1"))
        {
            port.Open();
            port.SetXonXoffChars(0x12, 0x14);
        }
    }
}

internal static class SerialPortExtensions
{
    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    public static void SetXonXoffChars(this SerialPort port, byte xon, byte xoff)
    {
        if (port == null)
            throw new NullReferenceException();
        if (port.BaseStream == null)
            throw new InvalidOperationException("Cannot change X chars until after the port has been opened.");

        try
        {
            // Get the base stream and its type which is System.IO.Ports.SerialStream
            object baseStream = port.BaseStream;
            Type baseStreamType = baseStream.GetType();

            // Get the Win32 file handle for the port
            SafeFileHandle portFileHandle = (SafeFileHandle)baseStreamType.GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(baseStream);

            // Get the value of the private DCB field (a value type)
            FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance);
            object dcbValue = dcbFieldInfo.GetValue(baseStream);

            // The type of dcb is Microsoft.Win32.UnsafeNativeMethods.DCB which is an internal type. We can only access it through reflection.
            Type dcbType = dcbValue.GetType();
            dcbType.GetField("XonChar").SetValue(dcbValue, xon);
            dcbType.GetField("XoffChar").SetValue(dcbValue, xoff);

            // We need to call SetCommState but because dcbValue is a private type, we don't have enough
            //  information to create a p/Invoke declaration for it. We have to do the marshalling manually.

            // Create unmanaged memory to copy DCB into
            IntPtr hGlobal = Marshal.AllocHGlobal(Marshal.SizeOf(dcbValue));
            try
            {
                // Copy their DCB value to unmanaged memory
                Marshal.StructureToPtr(dcbValue, hGlobal, false);

                // Call SetCommState
                if (!SetCommState(portFileHandle, hGlobal))
                    throw new Win32Exception(Marshal.GetLastWin32Error());

                // Update the BaseStream.dcb field if SetCommState succeeded
                dcbFieldInfo.SetValue(baseStream, dcbValue);
            }
            finally
            {
                if (hGlobal != IntPtr.Zero)
                    Marshal.FreeHGlobal(hGlobal);
            }
        }
        catch (SecurityException) { throw; }
        catch (OutOfMemoryException) { throw; }
        catch (Win32Exception) { throw; }
        catch (Exception ex)
        {
            throw new ApplicationException("SetXonXoffChars has failed due to incorrect assumptions about System.IO.Ports.SerialStream which is an internal type.", ex);
        }
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool SetCommState(SafeFileHandle hFile, IntPtr lpDCB);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Davut Engin
  • 811
  • 8
  • 9
1

Those settings can be configured by the Win32 SetCommState function.

Unfortunately, .NET doesn't provide a nice set of properties to configure them, nor does it give you access to the HANDLE, so you can't use p/invoke to adjust the settings for a .NET SerialPort class.

Instead, you'll have to ditch the entire System.IO.Ports.SerialPort class and do everything using the Win32 APIs:

  • CreateFile
  • GetCommState
  • SetCommState
  • WriteFile(Ex)
  • ReadFile(Ex)
  • WaitCommEvent

I recommend that you not use C# for that, the Win32 API is much easier to use from C++, and with C++/CLI, you can write classes that interface nicely with a C# GUI. It's a fair amount of work, the upside is that the Win32 serial port functions are far more powerful than what the .NET libraries give you access to. I hope to someday be allowed to publish the C++/CLI serial port class I've made.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720