. Net Core to develop serial communication under cross platform Linux

Posted by Easter Bunny on Thu, 27 Jan 2022 21:07:08 +0100

Developing serial communication under Linux with. Net Core

Functional requirements: send unlocking command to the lock control board.

Tip: after writing the article, the directory can be generated automatically. For how to generate it, please refer to the help document on the right

You need to install the corresponding on your Linux net core version, I installed 3.1.16

Under windows platform, you can use system IO. Ports. Serialport class for serial communication development. But it doesn't work under Linux. The prompt is lack of kernel dll. Learn from the previous articles and use NuGet package to load "SerialPortStream" Net Core cross platform serial communication
. Net Core version: 3.1.16
WorkerService project
Reference address:
1.https://www.cnblogs.com/flyfire-cn/p/10434171.html
2.https://www.cnblogs.com/flyfire-cn/p/10356991.html
3.https://www.cnblogs.com/whuanle/p/10499597.html
4.https://www.cnblogs.com/whuanle/p/10499498.html#t4

1, A series of preparations for using "SerialPortStream" under Linux

1.NuGet loading package:

2. Generate the OS file that the method called by the package depends on under Linux. The author of the library is described as follows:

2.1: I downloaded the ZIP file directly from git (address: https://github.com/jcurl/SerialPortStream )First, move the downloaded ZIP file to the Linux system.

2.2: run the command unzip - O - D / root / NETCORE / N2 3 SerialPortStream-release-2.3.1.0.zip serialportstream-release-2.3.1.0 Zip to / root / NETCORE / N2 Three times.

2.3: then enter the command into the directory serialunix: CD / root / NETCORE / N2 3/SerialPortStream-release-2.3.1.0/dll/serialunix

2.4: compile the corresponding OS file. Input/ build.sh

2.5: after successful compilation. At * * / root / NETCORE / N2 3 / serialportstream-release-2.3.1.0/dll/serialunix/bin/usr/local/lib64 * * (there may be problems during compilation. For example, GCC and CMAKE versions are relatively low and can be upgraded, or if they are not installed, they can be installed directly. For details, please refer to https://www.cnblogs.com/whuanle/p/10499498.html#t4


2.6.OK so far, you can copy these three files to the corresponding Visual Studio solution later.


And select three, then right-click and select attribute (R). Select Copy to output directory drop-down box as always copy

2, Write code

1. Initialize SerialPortStream object:

The code is as follows (example):

 /// <summary>
 ///Running the operating system
 /// </summary>
 static string OS = ConfigurationManager.AppSettings["OS"];

 public static SerialPortStream serialPortLockLinux  ;
 public override async Task StartAsync(CancellationToken cancellationToken)
        {
            if (OS == "Linux")
            {
                serialPortLockLinux = new SerialPortStream("/dev/ttyUSB0", 9600, 8, RJCP.IO.Ports.Parity.None, RJCP.IO.Ports.StopBits.One);
            }
            else
            {
                serialPortLockLinux = new SerialPortStream("COM5", 9600, 8, RJCP.IO.Ports.Parity.None, RJCP.IO.Ports.StopBits.One);
            }
            	//Add to the event in the appropriate place
 				serialPortLockLinux.DataReceived += new EventHandler<SerialDataReceivedEventArgs>(this.serialPortLockLinux_DataReceived);
       }
       

2. Data written to serial port

The code is as follows (example):

  private static int singleOpenLock(string Box, string Door, out string msg, string CheckCode = "11")
        {
			//First open the serial port
			serialPortLockLinux.Open();
			//Write hexadecimal data
			byte[] bcmd = new byte[5];

            //8A 01 00 11 9A


            bcmd[0] = 0x8A;

            bcmd[1] = Convert.ToByte(Box);//Control board number;

            bcmd[2] = Convert.ToByte(Door);//Door number

            bcmd[3] = 0x11;




            bcmd[4] = Convert.ToByte(bcmd[0] ^ bcmd[1] ^ bcmd[2] ^ bcmd[3]);


            string postCarbinet = BitConverter.ToString(bcmd);

            resultCarbinet = string.Empty;

            //write in
            serialPortLockLinux.Write(bcmd);
        }

3. Delegate function to receive returned data:

         private void serialPortLockLinux_DataReceived(object? sender, SerialDataReceivedEventArgs e)
        {

            try
            {
                System.Threading.Thread.Sleep(50);
                int ibtr = serialPortLockLinux.BytesToRead;
                byte[] bget = new byte[ibtr];
                serialPortLockLinux.Read(bget, 0, ibtr);
                

                //Read data
                resultCarbinet = resultCarbinet + BitConverter.ToString(bget);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                var ddd = ex.Message;
            }
        }

3, Generate release file

3.1 select the correct target runtime. And configuration

Copy to Linux, then enter the corresponding directory, and then run.


Enter ". / WorkerService1" in the Linux command window to run the program.

summary

1. Under Linux, you can view the connected serial port commands: ls /dev/tty * is generally / dev/ttyUSB0! [insert picture description here]( https://img-blog.csdnimg.cn/20210622155807535.png )The serial port name in the code is "/ dev/ttyUSB0", not ttyUSB0, and the first "/" cannot be less.

2. There is no running file under Linux exe and a series of suffixes.

Topics: ASP.NET C# Linux Back-end .NET