.net 核心的 RS232 库 [英] RS232 library for .net core

查看:25
本文介绍了.net 核心的 RS232 库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在 .Net Core 中开发应用程序,其中之一需要访问串行端口.

We are developing applications in .Net Core and one of them require to access a serial port.

当我了解到 System.IO.Ports 不会在 .Net Core 中实现时,我一直在寻找提供该功能的 nuget 库,但无法获得与 .net 核心兼容的库(VS Code 显示错误信息).

As I learned that System.IO.Ports won't be implemented in .Net Core, I was looking for a nuget library that supplies that functionality, but couldn't get one compatible with .net core (VS Code is showing an error message).

还有其他选择吗?

更新:我发现官方 SerialPort API 正在考虑用于移植到 .Net Core(请参阅 https://github.com/dotnet/corefx/issues/984)

UPDATE: I found that the official SerialPort API is being taken into consideration for porting to .Net Core (see https://github.com/dotnet/corefx/issues/984)

推荐答案

现在在 2021 年完全跨平台.

This is now fully cross platform in 2021.

只需使用命令行或您的 IDE 安装 NuGet:System.IO.Ports"

Simply NuGet install either using the command line or your IDE : "System.IO.Ports"

以下示例是一个 .NET 5 控制台模式程序,可在 Linux 和 Windows 上编译和运行.

The following example is a .NET 5 console mode program that compiles and works on both Linux and Windows.

using System;
using System.IO.Ports;

namespace PipelinesTest
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Reading a GPS Device on COM3");

      SerialPort _port = new SerialPort("COM3", 4800, Parity.None, 8, StopBits.One);

      _port.DataReceived += PortOnDataReceived;
      _port.Open();
      
      Console.WriteLine("Press Return to Exit");
      Console.ReadLine();

      _port.Close();
      _port.DataReceived -= PortOnDataReceived;
      
      Console.WriteLine("Ended");
    }

    private static void PortOnDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
      SerialPort port = sender as SerialPort;
      var line = port.ReadLine();
      Console.WriteLine(line);
    }
  }
}

注意:当我第一次回答这个问题时我应该提到,您需要更改COM3"在上面的构造函数中,类似于/dev/ttys0";或类似的Linux.您可能还必须在 Linux 机器上以 Root/SU 身份运行您的应用,不幸的是,这正是 Linux 多用户安全的本质.

NOTE: I should have mentioned when I first answered this, you'll need to change the "COM3" in the constructor above to something like "/dev/ttys0" or similar for Linux. You MIGHT also have to run your app as Root/SU on a Linux machine, this is just the nature of Linux's multi user security unfortunately.

这篇关于.net 核心的 RS232 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆