在.net开发中,实现一个蓝牙通讯功能:蓝牙扫描、蓝牙接收和发送。
开发环境:WIN10以上系统,且电脑自带蓝牙功能及开关
1、安装 32feet.NET 库
有大坑!!!
参考百度,一开始安装了 InTheHand.Net.Bluetooth 的NuGet库,最后发现调用如下函数时提示“BluetoothRadio未包含PrimaryRadio的定义”。
BluetoothRadio bluetoothRadio = BluetoothRadio.PrimaryRadio;
最后卸载再安装32feet.NET就好了,其它什么也不用动;
参考:C#蓝牙开发 “BluetoothRadio”未包含“PrimaryRadio”的定义 CSDN博客
2、开关蓝牙
本来想实现代码直接打开win10的蓝牙开关,后来放弃了。
只能做了一个UI提示;
2.1、通过判断本地蓝牙信息是否为空,来判断系统蓝牙是否打开;
2.2、如果蓝牙没有打开,则弹出提示页面,并打开系统蓝牙设置界面
让用户手动点击蓝牙开关
BluetoothRadio bluetoothRadio = BluetoothRadio.PrimaryRadio;
if (bluetoothRadio == null)
{
MessageBox.Show("请先打开Windows蓝牙");
Process.Start(@"ms-settings:bluetooth");
return;
}
3、蓝牙扫描
建立蓝牙客户端client,扫描设备信息;
如下:
3.1、在foreach加入的正则判断,过滤掉蓝牙名称为中文的设备;
3.2、字符串temp为蓝牙地址加设备名
InTheHand.Net.Sockets.BluetoothClient client = new InTheHand.Net.Sockets.BluetoothClient();
foreach (BluetoothDeviceInfo bdi in client.DiscoverDevices())
{
if ( !Regex.IsMatch(bdi.DeviceName, @"[\u4e00-\u9fa5]"))
{
string temp = bdi.DeviceAddress + " " + bdi.DeviceName;
}
}
4、蓝牙连接&蓝牙接收
蓝牙连接的参考处理形式如下:
获取输入的蓝牙地址字符串,将之转化为对应的long类型值,然后调用连接函数;
string btMac_s = str.Substring(0, 12);
ulong btMac_v = UInt64.Parse(btMac_s, System.Globalization.NumberStyles.HexNumber);
BluetoothAddress address = new BluetoothAddress((long)btMac_v);
if (client.Connected)
{
client.Close();
client = new BluetoothClient();
button18.Text = "打开蓝牙";
}
else
{
client.Connect(address, BluetoothService.SerialPort);
if (!client.Connected)
{
//连接失败
}
else
{
//连接成功,并监听接收线程
clientTask.Start();
button18.Text = "关闭蓝牙";
}
}
其中,client和clientTask是全局(静态)变量;
client用于保存实时的蓝牙状态,当主动断开或被动断开蓝牙连接时,要关闭并重新申请;
clientTask是对应的监听后台线程-负责读取蓝牙接收数据;
BluetoothClient client = new BluetoothClient();
Thread clientTask;
private void BluetoothClientTask()
{
while (true)
{
if (client.Connected)
{
try
{
Stream bt_stream = client.GetStream();
byte[] bt_data = new byte[256];
int bt_len = bt_stream.Read(bt_data, 0, 256);
string str = Encoding.Default.GetString(bt_data).Replace("\0", "");
//str即为接收数据的字符串形式,bt_data为接收的原始hex数据
}
catch
{
MessageBox.Show("蓝牙接收异常");
}
}
}
}
5、蓝牙发送
蓝牙发送是获取一个流传输,写入字节的形式进行发送;
Stream bt_stream = client.GetStream();
byte[] bytes = new byte[src.Length/2];
for (int i = 0; i < src.Length / 2; i++)
{
bytes[i] = (byte)Convert.ToByte(src.Substring(i * 2, 2), 16);
}
bt_stream.Write(bytes, 0, bytes.Length);