.NET Core 跨平臺 串口通信 ,Windows/Linux 串口通信,flyfire.CustomSerialPort 的使用

 目錄

1,前言

2,安裝虛擬串口軟件

3,新建項目,加入 flyfire.CustomSerialPort

4,flyfire.CustomSerialPort 說明

5,開始使用 flyfire.CustomSerialPort

6,實現把數據寫入串口

7,實現監聽串口消息、多設備進行通信

8,Modbus 協議的實現例子

1,前言

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

串口通信用於設備之間,傳遞數據,物聯網設備中普遍使用串口方式鏈接通信,物聯網通信協議 :Modbus 協議 ASCII、RTU、TCP模式是應用層的協議,與通信方式無關。數組

筆者如今實現的是 串口通訊,實現後,能夠在上層加上 Modbus 協議,筆者的另外一篇文章便是在串口上實現 Modbus 協議,計算中心向物聯網設備發送消息,要求設備響應,傳送設備信息、檢測狀態等。服務器

本文是 串口通信 的實現。框架

2,安裝虛擬串口軟件

因爲開發在 Windows,也爲了調試方便,使用須要安裝虛擬串口軟件:  Virtual Serial Port Driveride

安裝完成後

添加串口

請添加 4-6 個串口,COM1,COM2,COM3,COM4 ... ...this

關機重啓

好了,爲了使串口生效,請關機重啓(不必定要關機,不過爲了不出現問題,仍是關機重啓比較好)。spa

開機後,打開 設備管理器 ,查看 設備 - 端口(COM 和 LPT),出現以下圖所示,說明正常線程

 原理

由於是虛擬串口,有些問題須要注意一下設計

A B(或者說服務端、客戶端)不能使用同一個串口,你在設備管理器查看串口時(上面也有圖),是否是看到3d

COM1 -> COM2

COM2 -> COM1

由於這是一個虛擬串口,因此只能是單方向的,因此 A、B 須要分別使用兩個串口進行通信,而虛擬串口把 COM1 - COM2 鏈接起來了。咱們不須要關心這個,這裏只是說明一下。

3,新建項目,加入 flyfire.CustomSerialPort

新建一個 .NET Core 控制檯項目

名字能夠隨便起,筆者用了 SerialPortTest ,那咱們都用這個吧

添加 flyfire.CustomSerialPort

在項目中 添加 Nuget,搜索 flyfire.CustomSerialPort ,而後安裝

把類庫須要的 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.五、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, int baudRate = 115200, Parity parity = Parity.None, int databits = 8, 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();
        }

運行試試

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); //方式 二、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();
//方式 二、3 寫入串口 串口.Write(b_字符);
        Thread.Sleep(500); 串口.Write(b_16進制);
        Thread.Sleep(500); } }
public class 串口通信 : CustomSerialPort { public 串口通信(string portName, int baudRate = 115200, Parity parity = Parity.None, int databits = 8, StopBits stopBits = StopBits.One) : base(portName, baudRate, parity, databits, 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();
        }

示例:

 

關於進制轉換這些,能夠找一些文章看,串口通信對 byte、int1六、int3二、string 等類型間的轉換要求比較高。

7,實現監聽串口消息、多設備進行通信

在開始前,看一下圖:

點擊展開代碼

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, 0, receivedBytes, receiveDatalen, 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, 0, resultBuffer, 0, i);
                    ReceivedEvent(this, resultBuffer);
                    //System.Diagnostics.Debug.WriteLine("len " + i.ToString() + " " + ByteToHexStr(resultBuffer));
                }
                //Array.Clear (receivedBytes,0,receivedBytes.Length );
                receiveDatalen = 0;
            }
        }
後臺接收消息的實現

上面是 flyfire.CustomSerialPort 的 屬性、字段和方法,Sp_DataReceived() 這個方法是實現後臺監控數據,並觸發預設事件的方法,開闢新線程不斷循環接收數據。不過這裏的實現並不那麼好。

框架做者的博客 http://www.javashuo.com/article/p-nuxutmyp-kk.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);
            //方式 二、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();
            //方式 二、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, int baudRate = 115200, Parity parity = Parity.None, int databits = 8, StopBits stopBits = StopBits.One)
            : base(portName, baudRate, parity, databits, stopBits)
        {

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

namespace SerialPortTest
{
    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();
        }
    }
}

 

爲了實現串口通信,咱們把這個項目複製到別的目錄,另外打開運行。即同一份代碼變成兩份,運行時就有兩個控制檯了。

 

 

 

注:你會發現,輸入一條消息,會收到幾條信息。那是由於筆者在寫入方法那部分,給出了三個寫入方式,刪除2個便可。

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

串口通信已經已經實現了,如何實現 Modbus 協議,跟設備(單片機、開發板之類的小設備)進行約定通信呢~筆者的另外一篇文章~

 

項目源碼已經上傳到 http://pan.whuanle.cn/?dir=uploads/dotnet-core-串口

8,Modbus 協議的實現例子

因爲時間和篇幅問題,這裏簡單說一下 Modbus 和實現的示例。

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

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

傳輸的數據流格式以下

(以上兩張圖來自互聯網)

而後,我實現了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 檢驗,因爲數據傳輸可能發送丟失或出錯,使用後面兩位因爲檢驗數據是否正確接收。

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

剛剛實習工做~願一切順利~~~

水平有限,文章有錯請評論指出~謝謝啦~

相關文章
相關標籤/搜索