文章来源:https://www.toymoban.com/news/detail-506175.html
文章来源地址https://www.toymoban.com/news/detail-506175.html
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Packaging;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Match = System.Text.RegularExpressions.Match;
namespace FT_Tools
{
class MySerialPort
{
public static bool getRegexPara(MyAPI.MyDel Log, string pattern, string response, ref string value)
{
// response = "OK(1234)"; // 假设这是您的AT命令响应
//string pattern = @"\((\d+)\)"; // 正则表达式模式,用于匹配一对括号中的数字
Match match = Regex.Match(response, pattern); // 使用正则表达式匹配响应
if (match.Success)
{
value = match.Groups[1].Value; // 获取匹配结果中的数字
Log("value="+value);
return true;
}
else
{
Log("No matches found");
return false;
}
}
public static bool atGetValue(MyAPI.MyDel Log,string atCmd, string pattern, ref string value,long timeout=5000)
{
if (atCmd == null||atCmd.Equals("")) { Log("Send Cmd is empty"); return false; }
if (!atCmd.EndsWith("\r\n")) { atCmd += "\r\n"; } //没加回车换行 就加上。
string response = SendReceiveStr(Log,atCmd, timeout);
if (atCmd == null || atCmd.Equals("")) { Log("Response is empty"); return false; }
if (!getRegexPara(Log,pattern,response, ref value)) { Log("Regex parse response is empty"); return false; }
return true;
}
private static string SendReceiveStr(MyAPI.MyDel Log, string atCmd, long timeout = 5000)
{
if (!SendString(Log,atCmd)) { return ""; }
return ReceiveStr(Log,timeout);
}
private static string ReceiveStr(MyAPI.MyDel Log, long timeout = 5000)
{
Stopwatch sw = new Stopwatch();//计时
sw.Start();
try
{
while (sw.ElapsedMilliseconds < timeout)
{
string response = serialPort.ReadExisting();
if (response!=null && !response.Equals("")) { Log("response:" + response); return response; }
}
}
finally { sw.Stop(); }
Log("Response time out " + timeout+"s");
return null;
}
public static Boolean SendString(MyAPI.MyDel Log, string str)
{
if (!serialPort.IsOpen)
{
Log("The serial port is not opened, and automatically try to open the serial port!");
if (!uartOpenF28P(Log)) { return false; }
}
serialPort.DiscardOutBuffer();
serialPort.DiscardInBuffer();//清空缓冲
serialPort.Write(str);//向串口发送一包
Log("send:" + str);
return true ;
}
//private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
//{
// Thread.Sleep(10);
// if (serialPort.BytesToRead > 0)
// {
// response = serialPort.ReadExisting();
// }
//}
public static bool uartOpenF28P(MyAPI.MyDel Log)
{
try
{
string portName = GetComName(Log, "ASR Modem Device (COM");//
if (portName == null) { return false; }
serialPort.PortName = portName;
serialPort.BaudRate = 115200;
//serialPort.Parity = Parity.None; // 校验位
//serialPort.StopBits = StopBits.One; // 停止位
//serialPort.DataBits = 8; // 数据位
//serialPort.Handshake = Handshake.None; // 握手协议
//serialPort.DataReceived += SerialPort_DataReceived;//添加事件注册
//serialPort.ReadTimeout = 32;
//serialPort.Encoding = System.Text.Encoding.GetEncoding("UTF-8");//根据实际情况选择UTF-8还是GB2312
serialPort.Close(); //先关再开
serialPort.Open();
Log("Serial port has been opened " + serialPort.PortName + " " + serialPort.BaudRate);
return true;
}
catch (Exception e)
{
Log("The serial port has been occupied! " + serialPort.PortName + e.ToString() + "\r\n\r\n"); //+" " + e.ToString()
}
return false;
}
public static SerialPort serialPort = new SerialPort();
//通用 根据前缀获取串口,只获取第一个。
public static string GetComName(MyAPI.MyDel Log, string prefix)
{
string[] strArr = GetHarewareInfo(HardwareEnum.Win32_PnPEntity, "Name");
foreach (string s in strArr)
{
if (s.Contains("(COM"))
{
Log(s);
if (s.Contains(prefix.Trim()))
{
//Log("COM:"+ Regex.Match(s, @"\(COM(?<port>\d+)\)").Groups["port"].Value);
return "COM" + Regex.Match(s, @"\(COM(?<port>\d+)").Groups["port"].Value;
}
}
}
Log("错误,串口未找到,请检查是否安装驱动,是否插线,是否上电,检查配置文件中限定的串口前缀:" + prefix);
return null;
}
public static string Crc16(string hex)
{
byte[] buf=hexConvertToByteArray(hex);
return String.Format("{0:X4}", Crc16(buf, (ushort)buf.Length));//CRCH,CRCL
}
public static ushort Crc16(byte[] buf, ushort length)
{
ushort i;
ushort j;
ushort c;
ushort crc = 0xFFFF;
for (i = 0; i < length; i++)
{
c = (ushort)(buf[i] & 0x00FF);
crc ^= c;
for (j = 0; j < 8; j++)
{
if ((crc & 0x0001) != 0)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
crc = (ushort)((crc >> 8) + (crc << 8));
return (crc);
}
public static string byteArrayConvertToHexStr(byte[] buff,int start,int buffLength)//无空格
{
string strHex = "";
for (int i= 0; i<buffLength;i++)
{
strHex += String.Format("{0:X2}", buff[start+i]);
}
return strHex;
}
public static string strConvertToHexStrNoSpace(string str)//无空格
{
string strHex = "";
foreach (byte b in str)
{
strHex += String.Format("{0:X2}", b);
}
return strHex;
}
public static string strConvertToHexStr(string str)//字符转16进制
{
string strHex = "";
foreach (byte b in str)
{
strHex += String.Format("{0:X2} ", b);
}
return strHex;
}
public static byte[] hexConvertToByteArray(String str) //16进制字符串转16进制数组
{
str = str.Replace(" ", "");
byte[] b = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i = i + 2)
{
b[i / 2] = (byte)Convert.ToInt32(str.Substring(i, 2), 16); //将十六进制“10”转换为十进制i
}
return b;
}
/// <summary>
/// Get the system devices information with windows api.
/// </summary>
/// <param name="hardType">Device type.</param>
/// <param name="propKey">the property of the device.</param>
/// <returns></returns>
public static string[] GetHarewareInfo(HardwareEnum hardType, string propKey)
{
List<string> strs = new List<string>();
try
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
{
var hardInfos = searcher.Get();
foreach (var hardInfo in hardInfos)
{
if (hardInfo.Properties[propKey].Value != null)
{
String str = hardInfo.Properties[propKey].Value.ToString();
strs.Add(str);
}
}
}
return strs.ToArray();
}
catch
{
return null;
}
finally
{
strs = null;
}
}//end of func GetHarewareInfo().
/// <summary>
/// 枚举win32 api
/// </summary>
public enum HardwareEnum
{
// 硬件
Win32_Processor, // CPU 处理器
Win32_PhysicalMemory, // 物理内存条
Win32_Keyboard, // 键盘
Win32_PointingDevice, // 点输入设备,包括鼠标。
Win32_FloppyDrive, // 软盘驱动器
Win32_DiskDrive, // 硬盘驱动器
Win32_CDROMDrive, // 光盘驱动器
Win32_BaseBoard, // 主板
Win32_BIOS, // BIOS 芯片
Win32_ParallelPort, // 并口
Win32_SerialPort, // 串口
Win32_SerialPortConfiguration, // 串口配置
Win32_SoundDevice, // 多媒体设置,一般指声卡。
Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP)
Win32_USBController, // USB 控制器
Win32_NetworkAdapter, // 网络适配器
Win32_NetworkAdapterConfiguration, // 网络适配器设置
Win32_Printer, // 打印机
Win32_PrinterConfiguration, // 打印机设置
Win32_PrintJob, // 打印机任务
Win32_TCPIPPrinterPort, // 打印机端口
Win32_POTSModem, // MODEM
Win32_POTSModemToSerialPort, // MODEM 端口
Win32_DesktopMonitor, // 显示器
Win32_DisplayConfiguration, // 显卡
Win32_DisplayControllerConfiguration, // 显卡设置
Win32_VideoController, // 显卡细节。
Win32_VideoSettings, // 显卡支持的显示模式。
// 操作系统
Win32_TimeZone, // 时区
Win32_SystemDriver, // 驱动程序
Win32_DiskPartition, // 磁盘分区
Win32_LogicalDisk, // 逻辑磁盘
Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。
Win32_LogicalMemoryConfiguration, // 逻辑内存配置
Win32_PageFile, // 系统页文件信息
Win32_PageFileSetting, // 页文件设置
Win32_BootConfiguration, // 系统启动配置
Win32_ComputerSystem, // 计算机信息简要
Win32_OperatingSystem, // 操作系统信息
Win32_StartupCommand, // 系统自动启动程序
Win32_Service, // 系统安装的服务
Win32_Group, // 系统管理组
Win32_GroupUser, // 系统组帐号
Win32_UserAccount, // 用户帐号
Win32_Process, // 系统进程
Win32_Thread, // 系统线程
Win32_Share, // 共享
Win32_NetworkClient, // 已安装的网络客户端
Win32_NetworkProtocol, // 已安装的网络协议
Win32_PnPEntity,//all device
}
}
}
到了这里,关于C#正则提取内容 AT指令类,串口类,字符转换hex类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!