USB HID 连接TH20BL温湿度计读取实时温湿度的例子
// C# code using HidLibrary to connect to a USB HID device, send a hexadecimal string, receive data, and parse the received data
using HidSharp; //从nuget里面获取hidsharp库
using System;
using System.Linq;
using System.Threading;
class USBHIDExample
{
static void Main()
{
//连接上一个设备
HidDevice thDevice = GetOneTHDevice();
if (thDevice != null)
{
thDevice.Open();
//读取实时温湿度
GetRealtimeTH(thDevice);
}
}
public static HidDevice GetOneTHDevice()
{
// Connect to the USB HID device
var devices = DeviceList.Local.GetAllDevices().ToList();
HidDevice thDevice = null;
foreach (HidDevice device in devices)
{
try
{
string name = device.GetFriendlyName();
//Console.Write(device.DevicePath + "\t");
//Console.WriteLine(device.GetFriendlyName());
if (name.Contains("HHW"))
{
//温湿度的名称是以 HHW开头的
thDevice = device;
}
}
catch (Exception ex)
{
//Console.Write("Error getting friendly name: " + ex.Message + "\t");
//Console.WriteLine(device.DevicePath);
// Handle the exception as needed
}
}
return thDevice;
}
public static void GetRealtimeTH(HidDevice thDevice)
{
// Convert the hexadecimal string to bytes
// 8bytes 01 默认站号 04 功能码 00 00 02 数据个数 71 CB CRC。 这里以站号1做的例子,如果其他站号,指令要修改
//00 00 08 01 04 00 00 00 02 71 CB
byte[] dataToSend = StrToHexByte("00000801040000000271CB");
try
{
// Send the data to the device
HidStream stream = thDevice.Open();
stream.Write(dataToSend);
Console.WriteLine("send data: " + byteToHexStr(dataToSend));
// Receive data from the device
byte[] receivedData;
receivedData = stream.Read();
// Parse the received data
string hexStringReceive = byteToHexStr(receivedData);
Console.WriteLine("receive data: " + hexStringReceive);
parseRealtimeTH(hexStringReceive);
stream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//16进制字符串转化为16进制byte数组
public static byte[] StrToHexByte(string hexString)
{
if (string.IsNullOrEmpty(hexString))
{
return null;
}
hexString = hexString.ToUpper();
int length = hexString.Length / 2;
char[] hexChars = hexString.ToCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
int pos = i * 2;
d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c)
{
return (byte)"0123456789ABCDEF".IndexOf(c);
}
// byte[] to HexString
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
public static long ConvertHexToSInt(string hexstr)
{
if (hexstr.StartsWith("0x"))
{
hexstr = hexstr.Substring(2);
}
//如果不是有效的16进制字符串或者字符串长度大于16或者是空,均返回NULL
if (!IsHexadecimal(hexstr) || hexstr.Length > 16 || string.IsNullOrEmpty(hexstr))
{
return 99999;
}
if (hexstr.Length > 8)
{
return Convert.ToInt64(hexstr, 16);
}
else if (hexstr.Length > 4)
{
return Convert.ToInt32(hexstr, 16);
}
else
{
return Convert.ToInt16(hexstr, 16);
}
}
/// <summary>
/// 判断是否是十六进制格式字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsHexadecimal(string str)
{
const string PATTERN = @"[A-Fa-f0-9]+$";
return System.Text.RegularExpressions.Regex.IsMatch(str, PATTERN);
}
private static void parseRealtimeTH(String s)
{
int len = Int16.Parse(s.Substring(5, 1));
if (len == 9)
{
string validData = s.Substring(6, len * 2);
Console.WriteLine(validData);
float t = ConvertHexToSInt(validData.Substring(6, 4)) / 10.0f;
float h = ConvertHexToSInt(validData.Substring(10, 4)) / 10.0f;
Console.WriteLine("实时温度:{0},实时湿度:{1}", t, h);
}
}
}