在C#串口通信中,一发一收的场景,如何处理不同功能码的帧数据比较合理,代码结构好

在 C# 串口通信的一发一收场景里,处理不同功能码的帧数据可采用以下合理的代码结构,它能让代码更具可读性、可维护性和可扩展性。

实现思路

  1. 定义帧结构:创建一个类来表示通信帧,其中包含功能码、数据等信息。
  2. 功能码处理逻辑 :使用字典或者switch语句来根据不同的功能码执行相应的处理逻辑。
  3. 数据接收与解析:在串口接收事件中解析接收到的数据,并根据功能码调用对应的处理方法。
cs 复制代码
using System;
using System.Collections.Generic;
using System.IO.Ports;

// 定义通信帧类
public class CommunicationFrame
{
    public byte FunctionCode { get; set; }
    public byte[] Data { get; set; }

    public CommunicationFrame(byte functionCode, byte[] data)
    {
        FunctionCode = functionCode;
        Data = data;
    }
}

// 定义串口通信类
public class SerialCommunication
{
    private SerialPort serialPort;
    private readonly Dictionary<byte, Action<CommunicationFrame>> frameHandlers = new Dictionary<byte, Action<CommunicationFrame>>();

    public SerialCommunication(string portName, int baudRate)
    {
        serialPort = new SerialPort(portName, baudRate);
        serialPort.DataReceived += SerialPort_DataReceived;
    }

    // 注册功能码处理方法
    public void RegisterHandler(byte functionCode, Action<CommunicationFrame> handler)
    {
        if (!frameHandlers.ContainsKey(functionCode))
        {
            frameHandlers.Add(functionCode, handler);
        }
    }

    // 打开串口
    public void Open()
    {
        if (!serialPort.IsOpen)
        {
            serialPort.Open();
        }
    }

    // 关闭串口
    public void Close()
    {
        if (serialPort.IsOpen)
        {
            serialPort.Close();
        }
    }

    // 发送数据
    public void Send(CommunicationFrame frame)
    {
        if (serialPort.IsOpen)
        {
            byte[] dataToSend = new byte[1 + frame.Data.Length];
            dataToSend[0] = frame.FunctionCode;
            Array.Copy(frame.Data, 0, dataToSend, 1, frame.Data.Length);
            serialPort.Write(dataToSend, 0, dataToSend.Length);
        }
    }

    // 数据接收处理
    private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            if (serialPort.BytesToRead > 0)
            {
                byte functionCode = (byte)serialPort.ReadByte();
                int dataLength = serialPort.BytesToRead;
                byte[] data = new byte[dataLength];
                serialPort.Read(data, 0, dataLength);

                CommunicationFrame frame = new CommunicationFrame(functionCode, data);
                if (frameHandlers.TryGetValue(functionCode, out var handler))
                {
                    handler(frame);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error receiving data: {ex.Message}");
        }
    }
}

class Program
{
    static void Main()
    {
        SerialCommunication serialComm = new SerialCommunication("COM1", 9600);

        // 注册功能码处理方法
        serialComm.RegisterHandler(1, HandleFunctionCode1);
        serialComm.RegisterHandler(2, HandleFunctionCode2);

        serialComm.Open();

        // 发送示例数据
        byte[] data = { 0x01, 0x02, 0x03 };
        CommunicationFrame frameToSend = new CommunicationFrame(1, data);
        serialComm.Send(frameToSend);

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
        serialComm.Close();
    }

    // 处理功能码 1 的方法
    static void HandleFunctionCode1(CommunicationFrame frame)
    {
        Console.WriteLine($"Received frame with function code 1. Data length: {frame.Data.Length}");
    }

    // 处理功能码 2 的方法
    static void HandleFunctionCode2(CommunicationFrame frame)
    {
        Console.WriteLine($"Received frame with function code 2. Data length: {frame.Data.Length}");
    }
}
    
相关推荐
草莓熊Lotso6 小时前
C++11 核心特性实战:列表初始化 + 右值引用与移动语义(附完整代码)
java·服务器·开发语言·汇编·c++·人工智能·经验分享
前端小白在前进7 小时前
⭐力扣刷题:螺旋矩阵
算法·leetcode·矩阵
老赵聊算法、大模型备案12 小时前
北京市生成式人工智能服务已备案信息公告(2025年12月11日)
人工智能·算法·安全·aigc
CoderYanger13 小时前
C.滑动窗口-求子数组个数-越长越合法——2799. 统计完全子数组的数目
java·c语言·开发语言·数据结构·算法·leetcode·职场和发展
C++业余爱好者13 小时前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
厕所博士13 小时前
红黑树原理前置理解—— 2-3 树
算法·2-3树·红黑树原理理解前置
想用offer打牌13 小时前
RocketMQ如何防止消息丢失?
java·后端·架构·开源·rocketmq
皮卡龙13 小时前
Java常用的JSON
java·开发语言·spring boot·json
萌>__<新14 小时前
力扣打卡每日一题————除自身外所有元素的乘积
数据结构·算法
利刃大大14 小时前
【JavaSE】十三、枚举类Enum && Lambda表达式 && 列表排序常见写法
java·开发语言·枚举·lambda·排序