.NET?Core使用flyfire.CustomSerialPort實(shí)現(xiàn)Windows/Linux跨平臺(tái)串口通訊
1,前言
開(kāi)發(fā)環(huán)境:在 Visual Studio 2017,.NET Core 2.x
串口通訊用于設(shè)備之間,傳遞數(shù)據(jù),物聯(lián)網(wǎng)設(shè)備中廣泛使用串口方式連接通訊,物聯(lián)網(wǎng)通訊協(xié)議 :Modbus 協(xié)議 ASCII、RTU、TCP模式是應(yīng)用層的協(xié)議,與通訊方式無(wú)關(guān)。
筆者現(xiàn)在實(shí)現(xiàn)的是 串口通信,實(shí)現(xiàn)后,可以在上層加上 Modbus 協(xié)議,筆者的另一篇文章即是在串口上實(shí)現(xiàn) Modbus 協(xié)議,計(jì)算中心向物聯(lián)網(wǎng)設(shè)備發(fā)送消息,要求設(shè)備響應(yīng),傳送設(shè)備信息、檢測(cè)狀態(tài)等。
本文是 串口通訊 的實(shí)現(xiàn)。
2,安裝虛擬串口軟件
由于開(kāi)發(fā)在 Windows,也為了調(diào)試方便,使用需要安裝虛擬串口軟件:Virtual Serial Port Driver
安裝完成后
添加串口
請(qǐng)?zhí)砑?4-6 個(gè)串口,COM1,COM2,COM3,COM4 ... ...
關(guān)機(jī)重啟
好了,為了使串口生效,請(qǐng)關(guān)機(jī)重啟(不一定要關(guān)機(jī),不過(guò)為了避免出現(xiàn)問(wèn)題,還是關(guān)機(jī)重啟比較好)。
開(kāi)機(jī)后,打開(kāi) 設(shè)備管理器 ,查看 設(shè)備 - 端口(COM 和 LPT),出現(xiàn)如下圖所示,說(shuō)明正常
原理
因?yàn)槭翘摂M串口,有些問(wèn)題需要注意一下
A B(或者說(shuō)服務(wù)端、客戶端)不能使用同一個(gè)串口,你在設(shè)備管理器查看串口時(shí)(上面也有圖),是不是看到
COM1 -> COM2
COM2 -> COM1
因?yàn)檫@是一個(gè)虛擬串口,所以只能是單方向的,所以 A、B 需要分別使用兩個(gè)串口進(jìn)行通訊,而虛擬串口把 COM1 - COM2 連接起來(lái)了。我們不需要關(guān)心這個(gè),這里只是說(shuō)明一下。
3,新建項(xiàng)目,加入flyfire.CustomSerialPort
新建一個(gè) .NET Core 控制臺(tái)項(xiàng)目
名字可以隨便起,筆者用了SerialPortTest ,那我們都用這個(gè)吧
添加flyfire.CustomSerialPort
在項(xiàng)目中 添加 Nuget,搜索flyfire.CustomSerialPort ,然后安裝
把類庫(kù)需要的 Linux 依賴庫(kù)添加到項(xiàng)目中,關(guān)于原因、添加方法,可以看筆者的另一篇文章http://www.dbjr.com.cn/article/234717.htm
4,flyfire.CustomSerialPort 說(shuō)明
CustomSerialPort 類,所有功能都集中在這里面了,筆者將詳細(xì)說(shuō)明此類下字段、方法等的使用
protected SerialPortStream sp;
支持通訊串口通訊的類
public CustomSerialPort(string portName, int baudRate = 115200, Parity parity = Parity.None, int databits = 8, StopBits stopBits = StopBits.One);
用于初始化一個(gè)串口,使用此串口進(jìn)行通訊
- portName 串口名稱
- baudRate 比特率,是指每秒傳送的比特(bit)數(shù),默認(rèn)115200bps,不清楚 -> 百度
- parity 表示奇偶性校驗(yàn)方式,枚舉,None:沒(méi)有校驗(yàn)為,Odd:奇校驗(yàn),Even:偶檢驗(yàn),Space:總為0,Mark:總為1
- databits 設(shè)置數(shù)據(jù)位,這里表示 8位
- stopBits 停止位,One,One5,Twe方便表示1、1.5、2個(gè)停止位
因?yàn)榇谠O(shè)備通訊是在 OSI 七層的傳輸層,所以對(duì)這些都有相應(yīng)的規(guī)定。TCP/IP 相對(duì)于 串口 來(lái)說(shuō),不必要關(guān)注這些。
public int ReceiveTimeout { get; set; } //接收超時(shí)時(shí)間 public bool ReceiveTimeoutEnable { get; set; } public bool RtsEnable { get; set; } //不詳 public bool DtrEnable { get; set; } //不詳 public bool IsOpen { get; } //檢測(cè)是否在使用 public StopBits StopBits { get; set; } //枚舉,上面說(shuō)明的 public int DataBits { get; set; } //上面說(shuō)明了 public Parity Parity { get; set; } //枚舉,上面說(shuō)明了 public int BaudRate { get; set; } public int BufSize { get; set; } public string PortName { get; set; } //使用的串口名
public event CustomSerialPortReceivedEventHandle ReceivedEvent; //一個(gè)事件,可以把接收到消息后需要觸發(fā)的時(shí)間綁定到此事件 public static string ByteToHexStr(byte[] bytes); //把比特流轉(zhuǎn)為字符串 public static string[] GetPortNames(); public void Close(); //關(guān)閉串口 public void Dispose(); public bool Open(); //釋放串口 public void Write(string text); //以字符串的形式寫(xiě)入串口 public void Write(byte[] buffer); //以字節(jié)流的方式寫(xiě)入串口(推薦) public void WriteLine(string text); //寫(xiě)入字符串,應(yīng)該是與Modbus ASCII有關(guān),Ascii方式需要在數(shù)據(jù)后面加上換行符表示已經(jīng)結(jié)束傳送 protected void ReceiveTimeoutCheckFunc(); protected void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e); //后臺(tái)線程處理,表示收到串口消息后,觸發(fā)那些事件
以上,就是對(duì) flyfire.CustomSerialPort 的說(shuō)明,下面筆者說(shuō)明怎么使用。
5,開(kāi)始使用flyfire.CustomSerialPort
新建一個(gè)類SerialSerice.cs
新建一個(gè)類SerialSerice.cs ,設(shè)計(jì)此類用于提供串口通訊服務(wù)。
在SerialSerice.cs 引入
using flyfire.IO.Ports; using RJCP.IO.Ports; using System.Threading;
編寫(xiě)以下代碼(你可能覺(jué)得有些奇怪,原因后面說(shuō)),先不管這些東西,也不要管為什么這樣寫(xiě)
namespace SerialPortTest { /// <summary> /// 用于封裝需要的串口通訊 /// </summary> public class SerialSerice { /// <summary> /// 獲取計(jì)算機(jī)的所有串口 /// </summary> public void GetSerial() { //CustomSerialPort.GetPortNames() 靜態(tài)方法,獲取計(jì)算機(jī)的所有串口名稱 //因?yàn)橐呀?jīng)繼承,也可以使用 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) { } } }
開(kāi)始在Program.cs 中使用
static void Main(string[] args) { SerialSerice serialSerice = new SerialSerice(); serialSerice.GetSerial(); Console.ReadKey(); }
運(yùn)行試試
6,實(shí)現(xiàn)把數(shù)據(jù)寫(xiě)入串口
上面已經(jīng)獲取到串口,要把數(shù)據(jù)寫(xiě)入一個(gè)串口,就要初始化串口類,實(shí)現(xiàn)使用串口、向串口寫(xiě)入不同類型、不同進(jìn)制的數(shù)據(jù)
為了簡(jiǎn)單一些,我們使用默認(rèn)配置。
把代碼 Copy 到你的項(xiàng)目,筆者已經(jīng)詳細(xì)列舉出步驟
namespace SerialPortTest { /// <summary> /// 用于封裝需要的串口通訊 /// </summary> public class SerialSerice { //實(shí)現(xiàn)串口通訊的對(duì)象 串口通訊 串口; /// <summary> /// 獲取計(jì)算機(jī)的所有串口 步驟 1 /// </summary> public void GetSerial() { string[] vs = 串口通訊.GetPortNames(); Console.WriteLine("你電腦的串口列表(輸入名稱此端口,注意大小寫(xiě)):"); foreach (var i in vs) { Console.WriteLine(i); } } //初始化串口 步驟 2 public void 初始化(string portname) { 串口 = new 串口通訊(portname); 串口.Open(); } //向串口寫(xiě)入數(shù)據(jù) 步驟 3 public void 寫(xiě)入(string str) { //方式 1 串口.Write(str); Console.WriteLine("已經(jīng)向串口輸入:" + str); Thread.Sleep(500); //方式 2、3 byte[] b_字符 = Encoding.Default.GetBytes(str); byte[] b_16進(jìn)制 = new byte[b_字符.Length]; //轉(zhuǎn)16進(jìn)制再發(fā)送 Console.WriteLine("發(fā)送的16進(jìn)制數(shù)據(jù):"); for (int i = 0; i < b_字符.Length; i++) { b_16進(jìn)制[i] = Convert.ToByte(b_字符[i].ToString(), 16); Console.Write(b_16進(jìn)制[i] + " "); } Console.WriteLine(); //方式 2、3 寫(xiě)入串口 串口.Write(b_字符); Thread.Sleep(500); 串口.Write(b_16進(jìn)制); 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) { } } }
服務(wù)已經(jīng)配置好,接下來(lái)就是使用寫(xiě)好的服務(wù)了。
class Program { static void Main(string[] args) { // 初始化串口通訊服務(wù) SerialSerice 串口功能 = new SerialSerice(); //顯示串口列表、并讓用戶選擇串口 串口功能.GetSerial(); string portname= Console.ReadLine(); //步驟 2 串口功能.初始化(portname); Console.WriteLine("輸入你想發(fā)送給客戶端的內(nèi)容,退出請(qǐng)輸入 exit"); //因?yàn)槭纠巳N寫(xiě)入方法,第三種方法需要轉(zhuǎn)換,非數(shù)字會(huì)報(bào)錯(cuò) //實(shí)際上你可以發(fā)送如何類型的數(shù)據(jù),就看你怎么寫(xiě)步驟 3 的方法 Console.WriteLine("只能輸入數(shù)字!8進(jìn)制、10進(jìn)制、16進(jìn)制均可,請(qǐng)勿輸入字符串"); while (true) { string str = Console.ReadLine(); if (str == "exit") break; //步驟 3 串口功能.寫(xiě)入(str); } Console.ReadKey(); }
示例:
關(guān)于進(jìn)制轉(zhuǎn)換這些,可以找一些文章看,串口通訊對(duì) byte、int16、int32、string 等類型間的轉(zhuǎn)換要求比較高。
7,實(shí)現(xiàn)監(jiān)聽(tīng)串口消息、多設(shè)備進(jìn)行通訊
在開(kāi)始前,看一下圖:
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) { // 獲取字節(jié)長(zhǎng)度 int bytesNum = sp.BytesToRead; if (bytesNum == 0) return; // 創(chuàng)建字節(jié)數(shù)組 byte[] resultBuffer = new byte[bytesNum]; int i = 0; while (i < bytesNum) { // 讀取數(shù)據(jù)到緩沖區(qū) 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() 這個(gè)方法是實(shí)現(xiàn)后臺(tái)監(jiān)控?cái)?shù)據(jù),并觸發(fā)預(yù)設(shè)事件的方法,開(kāi)辟新線程不斷循環(huán)接收數(shù)據(jù)。不過(guò)這里的實(shí)現(xiàn)并不那么好。
框架作者的博客http://www.dbjr.com.cn/article/234712.htm
通過(guò)上面可以發(fā)現(xiàn),這個(gè)監(jiān)控方法是 protected 的,所以需要使用一個(gè)類繼承,才能使用此方法。
另外,事件委托為
public delegate void CustomSerialPortReceivedEventHandle(object sender, byte[] bytes)
基于以上,來(lái)做一個(gè)可以后臺(tái)接收數(shù)據(jù)并在控制臺(tái)輸出的代碼。
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 { //實(shí)現(xiàn)串口通訊的對(duì)象 串口通訊 串口; /// <summary> /// 獲取計(jì)算機(jī)的所有串口 步驟 1 /// </summary> public void GetSerial() { string[] vs = 串口通訊.GetPortNames(); Console.WriteLine("你電腦的串口列表(輸入名稱此端口,注意大小寫(xiě)):"); foreach (var i in vs) { Console.WriteLine(i); } } //初始化串口 步驟 2 public void 初始化(string portname) { 串口 = new 串口通訊(portname); 串口.Open(); } //向串口寫(xiě)入數(shù)據(jù) 步驟 3 public void 寫(xiě)入(string str) { //方式 1 串口.Write(str); Console.WriteLine("已經(jīng)向串口輸入:" + str); Thread.Sleep(500); //方式 2、3 byte[] b_字符 = Encoding.Default.GetBytes(str); byte[] b_16進(jìn)制 = new byte[b_字符.Length]; //轉(zhuǎn)16進(jìn)制再發(fā)送 Console.WriteLine("發(fā)送的16進(jìn)制數(shù)據(jù):"); for (int i = 0; i < b_字符.Length; i++) { b_16進(jìn)制[i] = Convert.ToByte(b_字符[i].ToString(), 16); Console.Write(b_16進(jìn)制[i] + " "); } Console.WriteLine(); //方式 2、3 寫(xiě)入串口 串口.Write(b_字符); Thread.Sleep(500); 串口.Write(b_16進(jìn)制); Thread.Sleep(500); } public void 開(kāi)啟后臺(tái)監(jiān)聽(tīng)() { //收到消息時(shí)要觸發(fā)的事件 串口.ReceivedEvent += 被觸發(fā)的事件_1; 串口.開(kāi)始后臺(tái)監(jiān)控(); } public static void 被觸發(fā)的事件_1(object sender, byte[] bytes) { Console.WriteLine("收到數(shù)據(jù)"); 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) { } //無(wú)意義,只是因?yàn)楦割惖?Sp_DataReceived() 不是 public public void 開(kāi)始后臺(tái)監(jiān)控() { Sp_DataReceived(new object(), new SerialDataReceivedEventArgs(SerialData.Eof)); } } }
using System; namespace SerialPortTest { class Program { static void Main(string[] args) { // 初始化串口通訊服務(wù) SerialSerice 串口功能 = new SerialSerice(); //顯示串口列表、并讓用戶選擇串口 串口功能.GetSerial(); string portname= Console.ReadLine(); //步驟 2 串口功能.初始化(portname); 串口功能.開(kāi)啟后臺(tái)監(jiān)聽(tīng)(); Console.WriteLine("輸入你想發(fā)送給客戶端的內(nèi)容,退出請(qǐng)輸入 exit"); //因?yàn)槭纠巳N寫(xiě)入方法,第三種方法需要轉(zhuǎn)換,非數(shù)字會(huì)報(bào)錯(cuò) //實(shí)際上你可以發(fā)送如何類型的數(shù)據(jù),就看你怎么寫(xiě)步驟 3 的方法 Console.WriteLine("只能輸入數(shù)字!8進(jìn)制、10進(jìn)制、16進(jìn)制均可,請(qǐng)勿輸入字符串"); while (true) { string str = Console.ReadLine(); if (str == "exit") break; //步驟 3 串口功能.寫(xiě)入(str); } Console.ReadKey(); } } }
為了實(shí)現(xiàn)串口通訊,我們把這個(gè)項(xiàng)目復(fù)制到別的目錄,另外打開(kāi)運(yùn)行。即同一份代碼變成兩份,運(yùn)行時(shí)就有兩個(gè)控制臺(tái)了。
注:你會(huì)發(fā)現(xiàn),輸入一條消息,會(huì)收到幾條信息。那是因?yàn)楣P者在寫(xiě)入方法那部分,給出了三個(gè)寫(xiě)入方式,刪除2個(gè)即可。
為了便于理解,筆者使用了中文對(duì)方法進(jìn)行命名。
串口通訊已經(jīng)已經(jīng)實(shí)現(xiàn)了,如何實(shí)現(xiàn) Modbus 協(xié)議,跟設(shè)備(單片機(jī)、開(kāi)發(fā)板之類的小設(shè)備)進(jìn)行約定通訊呢~筆者的另一篇文章~
項(xiàng)目源碼已經(jīng)上傳到http://pan.whuanle.cn/?dir=uploads/dotnet-core-串口
8,Modbus 協(xié)議的實(shí)現(xiàn)例子
由于時(shí)間和篇幅問(wèn)題,這里簡(jiǎn)單說(shuō)一下 Modbus 和實(shí)現(xiàn)的示例。
Modbus 是一種通信協(xié)議,有 ASCII、RTU、TCP等實(shí)現(xiàn)方式,廣泛應(yīng)用于物聯(lián)網(wǎng)設(shè)備、工業(yè)控制、自動(dòng)化場(chǎng)景等。
協(xié)議的實(shí)現(xiàn),由一臺(tái)主機(jī)、多個(gè)從機(jī)組成,我們把它想象成智能家居吧,一臺(tái)電腦是主機(jī),空調(diào)、電視機(jī)、冰箱等是從機(jī)。那么多設(shè)備,它們只能向主機(jī)發(fā)送數(shù)據(jù),不能直接通訊,每臺(tái)設(shè)備都有其地址。
傳輸?shù)臄?shù)據(jù)流格式如下
(以上兩張圖來(lái)自互聯(lián)網(wǎng))
然后,我實(shí)現(xiàn)了Modbus協(xié)議,對(duì)要發(fā)送的消息進(jìn)行檢驗(yàn)、封裝、打包成幀、接收、處理發(fā)送。
分為服務(wù)器、客戶端。每個(gè)客戶端都有一個(gè)地址,下面示范,
我在服務(wù)器使用了 02 04 00 01 25 26,
代表:客戶端地址02,功能碼:04(代表要設(shè)備要干嘛),要讀取設(shè)備的溫濕度數(shù)據(jù):00 01(00 02,00 03代表讀取其他數(shù)據(jù)),后面 25 26 有其他功能作用,不過(guò)筆者手里沒(méi)有真實(shí)的設(shè)備,所以沒(méi)對(duì)其進(jìn)行實(shí)現(xiàn),理解就行。
服務(wù)端向客戶端(02)發(fā)送數(shù)據(jù),功能是讀取寄存器(04),然后是讀取溫度數(shù)據(jù)還是濕度數(shù)據(jù)(00 01 代表兩個(gè)都讀取),25 26( 轉(zhuǎn)為10進(jìn)制為 9510 ) 可以定義為 要客戶端發(fā)返回 9510 條記錄。
返回的2 4 0 1 25 26 BB 4B,后面兩個(gè)是 CRC 檢驗(yàn),由于數(shù)據(jù)傳輸可能發(fā)送丟失或出錯(cuò),使用后面兩位由于檢驗(yàn)數(shù)據(jù)是否正確接收。
上面是在控制臺(tái)輸入 16 進(jìn)制的數(shù),下面是 直接 輸入 10 進(jìn)制的數(shù)。
到此這篇關(guān)于.NET Core使用flyfire.CustomSerialPort實(shí)現(xiàn)Windows/Linux跨平臺(tái)串口通訊的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET?MVC模式中應(yīng)用程序結(jié)構(gòu)詳解
本文詳細(xì)講解了ASP.NET?MVC模式中的應(yīng)用程序結(jié)構(gòu),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03詳解ABP框架中的數(shù)據(jù)過(guò)濾器與數(shù)據(jù)傳輸對(duì)象的使用
ABP框架是一個(gè)基于ASP.NET的Web開(kāi)發(fā)框架,這里我們來(lái)詳解ABP框架中的數(shù)據(jù)過(guò)濾器與數(shù)據(jù)傳輸對(duì)象的使用,需要的朋友可以參考下2016-06-06SQL Server 2005 RTM 安裝錯(cuò)誤 :The SQL Server System Configuratio
SQL Server 2005 RTM 安裝錯(cuò)誤 :The SQL Server System Configuration Checker cannot be executed due to...2007-02-02ASP.NET在VS2022中使用Dispose釋放資源實(shí)例
這篇文章介紹了ASP.NET在VS2022中使用Dispose釋放資源實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-11-11asp.net平臺(tái)下C#實(shí)現(xiàn)Socket通信
這篇文章介紹了asp.net平臺(tái)下C#實(shí)現(xiàn)Socket通信的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01