2025-10-11 18:25:59 +08:00

82 lines
2.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using XiaoZhiSharp.Kernels;
using OperatingSystem = XiaoZhiSharp.Kernels.OperatingSystem;
namespace XiaoZhiSharp.Utils.Com
{
public static class ComUtil
{
private static readonly string WinComPrefix = "COM";
private static readonly string LinuxUsbComPrefix = "/dev/ttyUSB";//USB串口
private static readonly string LinuxSysComPrefix = "/dev/ttyS";//PC上的串口一般是ttyS板子上Linux的串口一般叫做ttySAC
public static List<LinuxCom> LinuxComList { set; get; } = new List<LinuxCom>();
public static string[] GetLocalComs()
{
return SerialPort.GetPortNames();
}
public static string PortToString(int port)
{
string prefix = string.Empty;
OperatingSystemType plat = OperatingSystem.GetOperatingSystemType();
if (plat == OperatingSystemType.Windows)
{
prefix = WinComPrefix;
}
else if (plat == OperatingSystemType.Linux)
{
prefix = LinuxSysComPrefix;
LinuxCom linuxCom = LinuxComList.FirstOrDefault(l => l.LinuxPort == port);
if (linuxCom != null)
{
if (linuxCom.LinuxComType == LinuxComType.Usb)
{
prefix = LinuxUsbComPrefix;
}
else if (linuxCom.LinuxComType == LinuxComType.System)
{
prefix = LinuxSysComPrefix;
}
}
}
return string.Format("{0}{1}", prefix, port.ToString());
}
public static int PortToInt(string portString)
{
string prefix = string.Empty;
OperatingSystemType plat = OperatingSystem.GetOperatingSystemType();
if (plat == OperatingSystemType.Windows)
{
prefix = WinComPrefix;
}
else if (plat == OperatingSystemType.Linux)
{
prefix = LinuxSysComPrefix;
LinuxCom linuxCom = LinuxComList.FirstOrDefault(l => portString.Contains(l.LinuxPort.ToString()));
if (linuxCom != null)
{
if (linuxCom.LinuxComType == LinuxComType.Usb)
{
prefix = LinuxUsbComPrefix;
}
else if (linuxCom.LinuxComType == LinuxComType.System)
{
prefix = LinuxSysComPrefix;
}
}
}
if (prefix.Length <= 0)
{
throw new IndexOutOfRangeException("串口字符串无法转换");
}
return int.Parse(portString.Substring(prefix.Length));
}
}
}