In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the relevant knowledge of "how to use CustomSerialPort () of .net Core". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use CustomSerialPort () of .net Core" can help you solve the problem.
Abstract
In the process of using SerialPort to parse the serial port protocol, we often encounter the problem that the receiving event of receiving single frame protocol data serial port is triggered many times and the protocol analysis is troublesome. In view of this situation, the open source cross-platform serial port class library SerialPortStrem is further encapsulated, and a mechanism of receiving timeout response events is implemented, which simplifies the use of serial communication.
Introduction
Recently, I wrote a blog entitled ".net core Cross-platform Application Research-Serial Port", which has been well received by some people. It introduces the experience and solutions of trampling in the process of cross-platform application research, which can not be supported by using SerialPort class library under linux under dotnet core.
Because there are many articles about the use of SerialPort class library on the Internet, the use of serial port class library is mentioned in this article. But in practical use, students who have used the SerialPort class library may have encountered the problem that when receiving data, because the trigger of the data receiving event is uncertain, very often, a frame of communication protocol data will be triggered many times, resulting in a troublesome problem for the program to deal with protocol data.
In order to simplify the use of serial communication class library, combined with my own relevant experience, the author encapsulates a self-defined and enhanced cross-platform serial port class library to solve the problem of multiple triggers of one frame of protocol data.
Selection of basic Class Library
Due to the consideration of cross-platform applications, the SerialPort class library does not support the linux system (the experience of stepping on the pit has been introduced in the previous article), so the author chose the SerialPortStream class library for encapsulation.
This class library supports windows system and Linux system, but when it runs under Linux system, it needs to compile the target platform support library and configure the relevant environment.
The relevant compilation and configuration instructions have been introduced in https://github.com/jcurl/SerialPortStream, and you can also refer to my work ". Net core Cross-platform Application Research-Serial Port"
The implementation of Class Library to create Cross-platform Class Library
To support cross-platform, we use Visual Studio 2017 to create a class library based on .NET Standard.
NET Standard is an API specification, and each specific version defines the base class libraries that must be implemented.
The .NET Core is a managed framework optimized for building console, cloud, ASP.NET Core, and UWP applications.
Every managed implementation, such as .NET Core, .NET Framework, or Xamarin, must follow the. NET Standard implementation base class library (BCL).
Detailed instructions on NET Standard and cross-platform are here:
/ / www.yisu.com/article/234699.htm
The author is no longer verbose.
Implementation mechanism / condition
Usually in serial communication, after sending data, it will be used for a period of time to wait for the receiver to reply, so there must be a certain time interval between the two data transmissions. For example, the ModbusRTU protocol stipulates that it is necessary to wait for an interval of more than 4 bytes between two data packets.
In the single-chip microcomputer and embedded system with high real-time performance, in order to deal with the independence of serial port reception and protocol, the data frame reception timeout is usually used to deal with the reception of data frames. The timeout interval between two communications is calculated according to the rate of serial communication, and twice the timeout interval is taken as the timeout parameter. Each byte received is put into the buffer and timed. When the receiving time of the last byte exceeds the timeout time, the received data is returned and the cache is cleared, and a complete reception is completed (the DMA receiving mode is not discussed here).
Cross-platform implementation of .net core
In the custom serial port class, subscribe to the basic serial port class data receiving event, read out the currently available buffer data to the custom buffer after each receiving event is triggered, and mark the last receiving time Tick as the current system Tick. Determines whether the receive timeout processing thread is turned on, and if not, a receive timeout processing thread is opened.
In the receiving timeout processing thread, the judgment is made at a small time interval, and if the interval between the last receiving time and the current time is less than the set value (default 128ms), a cyclic check is performed after sleeping for a period of time (default 16ms). If the interval time is greater than the set value, the external receiving subscription event is triggered, the received data is sent out, and the timeout processing thread is exited.
There should be a flow chart here. Ha ha, too lazy to draw, let's make up for it by ourselves. ^ _ ^
In windows or linux systems, due to the multi-task processing characteristics of the system, the real-time performance of the system is poor. Usually, the scheduled tasks below the time interval of 50ms will be unreliable to a large extent (the execution time of tasks may exceed the time between calls).
Therefore, the default timeout interval is set to 128ms. It can also be adjusted according to the actual use, but the minimum interval should not be lower than 64ms.
Note: this is for personal experience and understanding. If you disagree, please ignore it directly.
Main code
Serial port receives event code:
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) {/ / get byte length int bytesNum = sp.BytesToRead If (bytesNum = = 0) return; / / create byte array 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; } } 接收超时处理线程代码: /// /// 超时返回数据处理线程方法 /// protected void ReceiveTimeoutCheckFunc() { while (TimeoutCheckThreadIsWork) { if (Environment.TickCount - lastReceiveTick >ReceiveTimeout) {if (ReceivedEvent! = null) {byte [] returnBytes = new byte [receiveDatalen]; Array.Copy (recviceBuffer, 0, returnBytes, 0, receiveDatalen); ReceivedEvent (this, returnBytes) } / / Array.Clear (receivedBytes,0,receivedBytes.Length); receiveDatalen = 0; TimeoutCheckThreadIsWork = false;} else Thread.Sleep (16);}} create .net core console program
To verify that our class library works properly, we create a .net core console program that uses the class library.
Why choose dotnet core, the reason is very simple, cross-platform. This program needs to be tested under windows and linux systems respectively.
Display system information (system ID, program ID, etc.)
Enumerate the serial port resources available to the system
Select serial port
Open / close serial port
Serial port test (on / off / off)
Static void Main (string [] args) {SetLibPath (); ShowWelcome (); GetPortNames (); ShowPortNames (); if (serailports.Length = = 0) {Console.WriteLine ($"Press any key to exit"); Console.ReadKey (); return } # if RunIsService RunService (); # endif bool quit = false; while (! quit) {Console.WriteLine ("\ r\ nPlease Input command Key\ r\ n"); Console.WriteLine ("p:Show SerialPort List"); Console.WriteLine ($"t:Test Uart:\" {selectedComPort}\ "") Console.WriteLine ($"o:Open Uart:\" {selectedComPort}\ "); Console.WriteLine ($" c:Close Uart:\ "{selectedComPort}\"); Console.WriteLine ("n:select next serial port"); Console.WriteLine ("q:exit app"); Console.WriteLine () Var key = Console.ReadKey (). KeyChar; Console.WriteLine (); switch (key) {case (Char) 27: case'qq: case'QQ: quit = true; break Case's clients: ShowWelcome (); break; case'packs: ShowPortNames (); break; case'nails: SelectSerialPort () Break; case'tasking: TestUart (selectedComPort); break; case'welling: TestWinUart (selectedComPort); break Case'oods: OpenUart (selectedComPort); break; case'cages: CloseUart (); break;}
The author uses the class library to refer to the class library project directly. If you need to use it, you can right-click on the project dependency in solution Explorer.
In the NuGet package manager, search SerialPort or flyfire to find and install this class library.
Class library address
Class Library address: https://www.nuget.org/packages/flyfire.CustomSerialPort
Cross-platform test Windows test output interface
Ubuntu test output interface
This is the end of the introduction to "how to use CustomSerialPort () of .net Core". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.