c# - 串行端口 - 如何设置字符?

标签 c# character-encoding serial-port usb ascii

考虑:

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

好的,所以使用端口扫描器我发现 USB 设备需要这些设置来促进导入。我可以按如下方式重新创建其中的大部分内容:

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);

但是,生成的代码是这些:

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

如何更改 X 限制和每个字符代码,以便它有机会工作?

帖子 SerialPort 0x1A character reading problem 是迄今为止我找到的最接近的东西,但我不明白。

最佳答案

您可以在 C# 中向 serialPort 添加扩展 - 请参阅 Xon/Xoff values in NET2.0 SerialPort class .

对于您可以更改的其他字段:

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

代码:

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);
}

关于c# - 串行端口 - 如何设置字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073963/

相关文章:

c# - catch 关键字如何确定抛出的异常类型?

c# - 将自定义依赖项解析器与 Unity 和 Web API Controller 一起使用时出错

c# - 计算 URI 编码字符串中的实际字符

java - UTF-8编码和http参数

c++ - 为什么C++ std::string 可以支持日语、法语的字符?

python - 无法使用Interceptty或slsnif嗅探通过串口发送的数据

python - pyserial - 如何连续读取和解析

c# - 锁定对象字典以减少 C# 中的延迟?

java - 设置默认 Java 字符编码

windows - XP Embedded 启动时串行端口计数仪发出咔嗒声