1. 程式人生 > 程式設計 >.NET Core使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

.NET Core使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

1,前言

開發環境:在 Visual Studio 2017,.NET Core 2.x

串列埠通訊用於裝置之間,傳遞資料,物聯網裝置中廣泛使用串列埠方式連線通訊,物聯網通訊協議 :Modbus 協議 ASCII、RTU、TCP模式是應用層的協議,與通訊方式無關。

筆者現在實現的是 串列埠通訊,實現後,可以在上層加上 Modbus 協議,筆者的另一篇文章即是在串列埠上實現 Modbus 協議,計算中心向物聯網裝置傳送訊息,要求裝置響應,傳送裝置資訊、檢測狀態等。

本文是 串列埠通訊 的實現。

2,安裝虛擬串列埠軟體

由於開發在 Windows,也為了除錯方便,使用需要安裝虛擬串列埠軟體:Virtual Serial Port Driver

安裝完成後

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

新增串列埠

請新增 4-6 個串列埠,COM1,COM2,COM3,COM4 ... ...

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

關機重啟

好了,為了使串列埠生效,請關機重啟(不一定要關機,不過為了避免出現問題,還是關機重啟比較好)。

開機後,開啟 裝置管理器 ,檢視 裝置 - 埠(COM 和 LPT),出現如下圖所示,說明正常

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

原理

因為是虛擬串列埠,有些問題需要注意一下

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

A B(或者說服務端、客戶端)不能使用同一個串列埠,你在裝置管理器檢視串列埠時(上面也有圖),是不是看到

COM1 -> COM2

COM2 -> COM1

因為這是一個虛擬串列埠,所以只能是單方向的,所以 A、B 需要分別使用兩個串列埠進行通訊,而虛擬串列埠把 COM1 - COM2 連線起來了。我們不需要關心這個,這裡只是說明一下。

3,新建專案,加入flyfire.CustomSerialPort

新建一個 .NET Core 控制檯專案

名字可以隨便起,筆者用了SerialPortTest ,那我們都用這個吧

新增flyfire.CustomSerialPort

在專案中 新增 Nuget,搜尋flyfire.CustomSerialPort ,然後安裝

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

把類庫需要的 依賴庫新增到專案中,關於原因、新增方法,可以看筆者的另一篇文章https://www.cnblogs.com/whuanle/p/10499498.html#4

4,flyfire.CustomSerialPort 說明

CustomSerialPort 類,所有功能都集中在這裡面了,筆者將詳細說明此類下欄位、方法等的使用

protected SerialPortStream sp;

支援通訊串列埠通訊的類

public CustomSerialPort(string portName,int baudRate = 115200,Parity parity = Parity.None,int databits = 8,StopBits stopBits = StopBits.One);

用於初始化一個串列埠,使用此串列埠進行通訊

  • portName  串列埠名稱
  • baudRate  位元率,是指每秒傳送的位元(bit)數,預設115200bps,不清楚 -> 百度
  • parity    表示奇偶性校驗方式,列舉,None:沒有校驗為,Odd:奇校驗,Even:偶檢驗,Space:總為0,Mark:總為1
  • databits  設定資料位,這裡表示 8位
  • stopBits  停止位,One,One5,Twe方便表示1、1.5、2個停止位

因為串列埠裝置通訊是在 OSI 七層的傳輸層,所以對這些都有相應的規定。TCP/IP 相對於 串列埠 來說,不必要關注這些。

        public int ReceiveTimeout { get; set; }  //接收超時時間
        public bool ReceiveTimeoutEnable { get; set; }  
        public bool RtsEnable { get; set; }    //不詳
        public bool DtrEnable { get; set; }    //不詳
        public bool IsOpen { get; }        //檢測是否在使用
        public StopBits StopBits { get; set; }  //列舉,上面說明的
        public int DataBits { get; set; }    //上面說明了
        public Parity Parity { get; set; }    //列舉,上面說明了
        public int BaudRate { get; set; }
        public int BufSize { get; set; }
        public string PortName { get; set; }    //使用的串列埠名
     public event CustomSerialPortReceivedEventHandle ReceivedEvent;    //一個事件,可以把接收到訊息後需要觸發的時間繫結到此事件

        public static string ByteToHexStr(byte[] bytes);              //把位元流轉為字串
        public static string[] GetPortNames();
        public void Close();                              //關閉串列埠
        public void Dispose();
        public bool Open();                                //釋放串列埠
        public void Write(string text);                        //以字串的形式寫入串列埠
        public void Write(byte[] buffer);                       //以位元組流的方式寫入串列埠(推薦)
        public void WriteLine(string text);                      //寫入字串,應該是與Modbus ASCII有關,Ascii方式需要在資料後面加上換行符表示已經結束傳送
        protected void ReceiveTimeoutCheckFunc();
        protected void Sp_DataReceived(object sender,SerialDataReceivedEventArgs e);  //後臺執行緒處理,表示收到串列埠訊息後,觸發那些事件

以上,就是對 flyfire.CustomSerialPort 的說明,下面筆者說明怎麼使用。

5,開始使用flyfire.CustomSerialPort

新建一個類SerialSerice.cs

新建一個類SerialSerice.cs ,設計此類用於提供串列埠通訊服務

在SerialSerice.cs 引入

using flyfire.IO.Ports;
using RJCP.IO.Ports;
using System.Threading;

編寫以下程式碼(你可能覺得有些奇怪,原因後面說),先不管這些東西,也不要管為什麼這樣寫

namespace SerialPortTest
{
    /// <summary>
    ///  用於封裝需要的串列埠通訊
    /// </summary>
    public class SerialSerice
    {
        /// <summary>
        /// 獲取計算機的所有串列埠
        /// </summary>
        public void GetSerial()
        {
        //CustomSerialPort.GetPortNames() 靜態方法,獲取計算機的所有串列埠名稱
        //因為已經繼承,也可以使用 string[] vs = 串列埠通訊.GetPortNames();
            string[] vs = CustomSerialPort.GetPortNames();
            Console.WriteLine("你電腦的串列埠列表:");
            foreach (var i in vs)
            {
                Console.WriteLine(i);
            }
        }
    }

    public class 串列埠通訊 : CustomSerialPort
    {
        public 串列埠通訊(string portName,StopBits stopBits = StopBits.One)
            :base(portName,baudRate,parity,databits,stopBits)
        {

        }
    }
}

開始在Program.cs 中使用

     static void Main(string[] args)
        {
            SerialSerice serialSerice = new SerialSerice();
            serialSerice.GetSerial();
            Console.ReadKey();
        }

執行試試

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

6,實現把資料寫入串列埠

上面已經獲取到串列埠,要把資料寫入一個串列埠,就要初始化串列埠類,實現使用串列埠、向串列埠寫入不同型別、不同進位制的資料

為了簡單一些,我們使用預設配置。

把程式碼 Copy 到你的專案,筆者已經詳細列舉出步驟

namespace SerialPortTest
{
    /// <summary>
    ///  用於封裝需要的串列埠通訊
    /// </summary>
    public class SerialSerice
    {
        //實現串列埠通訊的物件
        串列埠通訊 串列埠;
        /// 客棧<summary>
        /// 獲取計算機的所有串列埠 步驟 1
        /// </summary>
        public void GetSerial()
        {
            string[] vs = 串列埠通訊.GetPortNames();
            Console.WriteLine("你電腦的串列埠列表(輸入名稱此埠,注意大小寫):");

            foreach (var i in vs)
            {
                Console.WriteLine(i);
            }
        }
        //初始化串列埠 步驟 2
        public void 初始化(string portname)
        {
            串列埠 = new 串列埠通訊(portname);
        串列埠.Open();
        }
        //向串列埠寫入資料 步驟 3
        public void 寫入(string str)
        {
            //方式 1
            串列埠.Write(str);
            Console.WriteLine("已經向串列埠輸入:" + str);
        Thread.Sleep(500);
            //方式 2、3
            byte[] b_字元 = Encoding.Default.GetBytes(str);
            byte[] b_16進位制 = new byte[b_字元.Length];

            //轉16進位制再發送
            Console.WriteLine("傳送的16進位制資料:");
            for (int i = 0; i < b_字元.Length; i++)
            {
                b_16進位制[i] = Convert.ToByte(b_字元[i].ToString(),16);
                Console.Write(b_16進位制[i] + " ");
            }
        Console.WriteLine();
            //方式 2、3 寫入串列埠
            串列埠.Write(b_字元);
        Thread.Sleep(500);
            串列埠.Write(b_16進位制);
        Thread.Sleep(500);
        }
    }

    public class 串列埠通訊 : CustomSerialPort
    {
        public 串列埠通訊(string portName,StopBits stopBits = StopBits.One)
            : base(portName,stopBits)
        {

        }
    }
}

服務已經配置好,接下來就是使用寫好的服務了。

class Program
    {
        static void Main(string[] args)
        {
            // 初始化串列埠通訊服務
            SerialSerice 串列埠功能 = new SerialSerice();

            //顯示串列埠列表、並讓使用者選擇串列埠
            串列埠功能.GetSerial();
            string portname= Console.ReadLine();

            //步驟 2 
            串列埠功能.初始化(portname);

            Console.WriteLine("輸入你想傳送給客戶端的內容,退出請輸入 exit");
            //因為示例了三種寫入方法,第三種方法需要轉換,非數字會報錯
            //實際上你可以傳送如何型別的資料,就看你怎麼寫步驟 3 的方法
            Console.WriteLine("只能輸入數字!8進位制、10進位制、16進位制均可,請勿輸入字串");
            while (true)
            {
                string str = Console.ReadLine();
                if (str == "exit")
                    break;

                //步驟 3
                串列埠功能.寫入(str);
            }

            Console.ReadKey();
        }

示例:

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

關於進位制轉換這些,可以找一些文章看,串列埠通訊對 byte、int16、int32、string 等型別間的轉換要求比較高。

7,實現監聽串列埠訊息、多裝置進行通訊

在開始前,看一下圖:

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

protected void Sp_DataReceived(object sender,SerialDataReceivedEventArgs e)
        {
            int canReadBytesLen = 0;
            if (ReceiveTimeoutEnable)
            {
                while (sp.BytesToRead > 0)
                {
                    canReadBytesLen = sp.BytesToRead;
                    if (receiveDatalen + canReadBytesLen > BufSize)
                    {
                        receiveDatalen = 0;
                        throw new Exception("Serial port receives buffer overflow!");
                    }
                    var receiveLen = sp.Read(recviceBuffer,receiveDatalen,canReadBytesLen);
                    if (receiveLen != canReadBytesLen)
                    {
                        receiveDatalen = 0;
                        throw new Exception("Serial port receives exception!");
                    }
                    //Array.Copy(recviceBuffer,receivedBytes,receiveLen);
                    receiveDatalen += receiveLen;
                    lastReceiveTick = Environment.TickCount;
                    if (!TimeoutCheckThreadIsWork)
                    {
                        TimeoutCheckThreadIsWork = true;
                        Thread thread = new Thread(ReceiveTimeoutCheckFunc)
                        {
                            Name = "ComReceiveTimeoutCheckThread"
                        };
                        thread.Start();
                    }
                }
            }
            else
            {
                if (ReceivedEvent != null)
                {
                    // 獲取位元組長度
                    int bytesNum = sp.BytesToRead;
                    if (bytesNum == 0)
                        return;
                    // 建立位元組陣列
                    byte[] resultBuffer = new byte[bytesNum];

                    int i = 0;
                    while (i < bytesNum)
                    {
                        // 讀取資料到緩衝區
                        int j = sp.Read(recviceBuffer,i,bytesNum - i);
                        i += j;
                    }
                    Array.Copy(recviceBuffer,resultBuffer,i);
                    ReceivedEvent(this,resultBuffer);
                    //System.Diagnostics.Debug.WriteLine("len " + i.ToString() + " " + ByteToHexStr(resultBuffer));
                }
                //Array.Clear (receivedBytes,receivedBytes.Length );
                receiveDatalen = 0;
            }
        }

上面是 flyfire.CustomSerialPort 的 屬性、欄位和方法,Sp_DataReceived() 這個方法是實現後臺監控資料,並觸發預設事件的方法,開闢新執行緒不斷迴圈接收資料。不過這裡的實現並不那麼好。

框架作者的部落格https://www.cnblogs.com/flyfire-cn/p/10434171.html

通過上面可以發現,這個監控方法是 protected 的,所以需要使用一個類繼承,才能使用此方法。

另外,事件委託為

public delegate void CustomSerialPortReceivedEventHandle(object sender,byte[] bytes)

基於以上,來做一個可以後臺接收資料並在控制檯輸出的程式碼。

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using flyfire.IO.Ports;
using RJCP.IO.Ports;

namespace SerialPortTest
{
    /// <summary>
    ///  用於封裝需要的串列埠通訊
    /// </summary>
    public class SerialSerice
    {
        //實現串列埠通訊的物件
        串列埠通訊 串列埠;
        /// <summary>
        /// 獲取計算機的所有串列埠 步驟 1
        /// </summary>
        public void GetSerial()
        {
            string[] vs = 串列埠通訊.GetPortNames();
            Console.WriteLine("你電腦的串列埠列表(輸入名稱此埠,注意大小寫):");

            foreach (var i in vs)
            {
                Console.WriteLine(i);
            }
        }
        //初始化串列埠 步驟 2
        public void 初始化(string portname)
        {
            串列埠 = new 串列埠通訊(portname);
            串列埠.Open();
        }
        //向串列埠寫入資料 步驟 3
        public void 寫入(string str)
        {
            //方式 1
            串列埠.Write(str);
            Console.WriteLine("已經向串列埠輸入:" + str);
            Thread.Sleep(500);
            //方式 2、3
            byte[] b_字元 = Encoding.Default.GetBytes(str);
            byte[] b_16進位制 = new byte[b_字元.Length];

            //轉16進位制再發送
            Console.WriteLine("傳送的16進位制資料:");
            for (int i = 0; i < b_字元.Length; i++)
            {
                b_16進位制[i] = Convert.ToByte(b_字元[i].ToString(),16);
                Console.Write(b_16進位制[i] + " ");
            }
            Console.WriteLine();
            //方式 2、3 寫入串列埠
            串列埠.Write(b_字元);
            Thread.Sleep(500);
            串列埠.Write(b_16進位制);
            Thread.Sleep(500);
        }
        public void 開啟後臺監聽()
        {
            //收到訊息時要觸發的事件
            串列埠.ReceivedEvent += 被觸發的事件_1;

            串列埠.開始後臺監控();

        }
        public static void 被觸發的事件_1(object sender,byte[] bytes)
        {
            Console.WriteLine("收到資料");
            foreach (var i in bytes)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine("");
        }

    }

    public class 串列埠通訊 : CustomSerialPort
    {
        public 串列埠通訊(string portName,stopBits)
        {

        }
        //無意義,只是因為父類的 Sp_DataReceived() 不是 public
        public void 開始後臺監控()
        {
            
            Sp_DataReceived(new object(),new SerialDataReceivedEventArgs(SerialData.Eof));
        }
    }
}
using System;

namespace SerialPortTest
{
    class Program
    {
        static voiMFNwQId Main(string[] args)
        {
            // 初始化串列埠通訊服務
            SerialSerice 串列埠功能 = new SerialSerice();

            //顯示串列埠列表、並讓使用者選擇串列埠
            串列埠功能.GetSerial();
            string portname= Console.ReadLine();

            //步驟 2 
            串列埠功能.初始化(portname);
            串列埠功能.開啟後臺監聽();
            Console.WriteLine("輸入你想傳送給客戶端的內容,退出請輸入 exit");
            //因為示例了三種寫入方法,第三種方法需要轉換,非數字會報錯
            //實際上你可以傳送如何型別的資料,就看你怎麼寫步驟 3www.cppcns.com 的方法
            Console.WriteLine("只能輸入數字!8進位制、10進位制、16進位制均可,請勿輸入字串");
            while (true)
            {
                string str = Console.ReadLine();
                if (str == "exit")
                    break;

                //步驟 3
                串列埠功能http://www.cppcns.com.寫入(str);
            }

            Console.ReadKey();
        }
    }
}

為了實現串列埠通訊,我們把這個專案複製到別的目錄,另外開啟執行。即同一份程式碼變成兩份,執行時就有兩個控制檯了。

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

注:你會發現,輸入一條訊息,會收到幾條資訊。那是因為筆者在寫入方法那部分,給出了三個寫入方式,刪除2個即可。

為了便於理解,筆者使用了中文對方法進行命名。

串列埠通訊已經已經實現了,如何實現 Modbus 協議,跟裝置(微控制器、開發板之類的小裝置)進行約定通訊呢~筆者的另一篇文章~

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

專案原始碼已經上傳到http://pan.whuanle.cn/?dir=uploads/dotnet-core-串列埠

8,Modbus 協議的實現例子

由於時間和篇幅問題,這裡簡單說一下 Modbus 和實現的示例。

Modbus 是一種通訊協議,有 ASCII、RTU、TCP等實現方式,廣泛應用於物聯網裝置、工業控制、自動化場景等。

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

協議的實現,由一臺主機、多個從機組成,我們把它想象成智慧家居吧,一臺電腦是主機,空調、電視機、冰箱等是從機。那麼多裝置,它們只能向主機發送資料,不能直接通訊,每臺裝置都有其地址。

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

傳輸的資料流格式如下

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

(以上兩張圖來自網際網路)

然後,我實現了Modbus協議,對要傳送的訊息進行檢驗、封裝、打包成幀、接收、處理髮送。

分為伺服器、客戶端。每個客戶端都有一個地址,下面示範,

我在伺服器使用了 02 04 00 01 25 26,

代表:客戶端地址02,功能碼:04(代表要裝置要幹嘛),要讀取裝置的溫溼度資料:00 01(00 02,00 03代表讀取其他資料),後面 25 26 有其他功能作用,不過筆者手裡沒有真實的裝置,所以沒對其進行實現,理解就行。

服務端向客戶端(02)傳送資料,功能是讀取暫存器(04),然後是讀取溫度資料還是溼度資料(00 01 代表兩個都讀取),25 26( 轉為10進製為 9510 ) 可以定義為 要客戶端發返回 9510 條記錄。

返回的2 4 0 1 25 26 BB 4B,後面兩個是 CRC 檢驗,由於資料傳輸可能傳送丟失或出錯,使用後面兩位由於檢驗資料是否正確接收。

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

上面是在控制檯輸入 16 進位制的數,下面是 直接 輸入 10 進位制的數。

.NETCore使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊

到此這篇關於.NET Core使用flyfire.CustomSerialPort實現Windows/Linux跨平臺串列埠通訊的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援我們。