[C#] 控制電腦藍牙與外部藍牙設備通信


 

 

 

 

源碼:  https://github.com/chinayixia/c-bluetooth-pc-communicate-with-devices_20190820.git

 

 

 

 

 控制台:

using System;
using System.IO;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
// [注意1]:要添加如下三個命名空間
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;

namespace cs_bt_20190820
{
class Program
{
static void Main(string[] args)
{
BluetoothRadio bluetoothRadio = BluetoothRadio.PrimaryRadio;
if (bluetoothRadio == null)
{
Console.WriteLine("沒有找到本機藍牙設備!");
Console.ReadLine();
}
else
{
Program p = new Program();
p.localAdapterInfo(bluetoothRadio);
p.openDoor();
}
}

/**
* 連接目標藍牙設備發送開門指令
* **/
private void openDoor()
{
BluetoothClient cli = new BluetoothClient();
BluetoothAddress addr = null;
BluetoothEndPoint ep = null;
try
{
// [注意2]:要注意MAC地址中字節的對應關系,直接來看順序是相反的,例如
// 如下對應的MAC地址為——12:34:56:78:9a:bc
addr = new BluetoothAddress(new byte[] { 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12 });
ep = new BluetoothEndPoint(addr, BluetoothService.SerialPort);
cli.Connect(ep); // 連接藍牙
if (cli.Connected)
{
Stream peerStream = cli.GetStream();
peerStream.WriteByte(0xBB); // 發送開門指令
}
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
Console.ReadLine();

}
finally
{
if (cli != null)
{
// [注意3]:要延遲一定時間(例如1000毫秒)
//避免因連接后又迅速斷開而導致藍牙進入異常(傻逼)狀態
Thread.Sleep(1000);
cli.Close();
}
}
}

/**
*
* 顯示本地藍牙的信息
*
* **/
private void localAdapterInfo(BluetoothRadio bluetoothRadio)
{
Console.WriteLine("ClassOfDevice: " + bluetoothRadio.ClassOfDevice);
Console.WriteLine("HardwareStatus: " + bluetoothRadio.HardwareStatus);
Console.WriteLine("HciRevision: " + bluetoothRadio.HciRevision);
Console.WriteLine("HciVersion: " + bluetoothRadio.HciVersion);
Console.WriteLine("LmpSubversion: " + bluetoothRadio.LmpSubversion);
Console.WriteLine("LmpVersion: " + bluetoothRadio.LmpVersion);
Console.WriteLine("LocalAddress: " + bluetoothRadio.LocalAddress);
Console.WriteLine("Manufacturer: " + bluetoothRadio.Manufacturer);
Console.WriteLine("Mode: " + bluetoothRadio.Mode);
Console.WriteLine("Name: " + bluetoothRadio.Name);
Console.WriteLine("Remote:" + bluetoothRadio.Remote);
Console.WriteLine("SoftwareManufacturer: " + bluetoothRadio.SoftwareManufacturer);
Console.WriteLine("StackFactory: " + bluetoothRadio.StackFactory);
Console.ReadLine();

}
}
}

 

 

 

 winform:

 

using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace wf_bluetooth_20190819
{
public partial class Form1 : Form
{

//https://www.jb51.net/article/82144.htm

 

BluetoothRadio radio = null;//藍牙適配器
string sendFileName = null;//發送文件名
InTheHand.Net.BluetoothAddress sendAddress = null;//發送目的地址
ObexListener listener = null;//監聽器
string recDir = null;//接受文件存放目錄
Thread listenThread, sendThread;//發送/接收線程

public Form1()
{
InitializeComponent();
radio = BluetoothRadio.PrimaryRadio;//獲取當前PC的藍牙適配器
CheckForIllegalCrossThreadCalls = false;//不檢查跨線程調用
if (radio == null)//檢查該電腦藍牙是否可用
{
MessageBox.Show("這個電腦藍牙不可用!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
labelRecDir.Text = recDir;
}

private void buttonSelectBluetooth_Click(object sender, EventArgs e)//選擇遠程藍牙設備
{
InTheHand.Windows.Forms.SelectBluetoothDeviceDialog dialog = new InTheHand.Windows.Forms.SelectBluetoothDeviceDialog();
dialog.ShowRemembered = true;//顯示已經記住的藍牙設備
dialog.ShowAuthenticated = true;//顯示認證過的藍牙設備
dialog.ShowUnknown = true;//顯示位置藍牙設備
if (dialog.ShowDialog() == DialogResult.OK)
{
sendAddress = dialog.SelectedDevice.DeviceAddress;//獲取選擇的遠程藍牙地址
labelAddress.Text = "地址:" + sendAddress.ToString() + " 設備名:" + dialog.SelectedDevice.DeviceName;
}
}

private void buttonSelectFile_Click(object sender, EventArgs e)//選擇要發送的本地文件
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
sendFileName = dialog.FileName;//設置文件名
labelPath.Text = Path.GetFileName(sendFileName);
}
}



private void ButtonSend_Click(object sender, EventArgs e)
{
sendThread = new Thread(sendFile);//開啟發送文件線程
sendThread.Start();
}

private void sendFile()//發送文件方法
{
ObexWebRequest request = new ObexWebRequest(sendAddress, Path.GetFileName(sendFileName));//創建網絡請求
WebResponse response = null;
try
{
buttonSend.Enabled = false;
request.ReadFile(sendFileName);//發送文件
labelInfo.Text = "開始發送!";
response = request.GetResponse();//獲取回應
labelInfo.Text = "發送完成!";
}
catch (System.Exception ex)
{
MessageBox.Show("發送失敗!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
labelInfo.Text = "發送失敗!";
}
finally
{
if (response != null)
{
response.Close();
buttonSend.Enabled = true;
}
}
}

 

 

private void receiveFile()//收文件方法
{
ObexListenerContext context = null;
ObexListenerRequest request = null;
while (listener.IsListening)
{
context = listener.GetContext();//獲取監聽上下文
if (context == null)
{
break;
}
request = context.Request;//獲取請求
string uriString = Uri.UnescapeDataString(request.RawUrl);//將uri轉換成字符串
string recFileName = recDir + uriString;
request.WriteFile(recFileName);//接收文件
labelRecInfo.Text = "收到文件" + uriString.TrimStart(new char[] { '/' });
}
}

private void ButtonListen_Click(object sender, EventArgs e)
{
if (listener == null || !listener.IsListening)
{
radio.Mode = RadioMode.Discoverable;//設置本地藍牙可被檢測
listener = new ObexListener(ObexTransport.Bluetooth);//創建監聽
listener.Start();
if (listener.IsListening)
{
buttonListen.Text = "停止";
labelRecInfo.Text = "開始監聽";
listenThread = new Thread(receiveFile);//開啟監聽線程
listenThread.Start();
}
}
else
{
listener.Stop();
buttonListen.Text = "監聽";
labelRecInfo.Text = "停止監聽";
}
}

private void ButtonselectRecDir_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "請選擇藍牙接收文件的存放路徑";
if (dialog.ShowDialog() == DialogResult.OK)
{
recDir = dialog.SelectedPath;
labelRecDir.Text = recDir;
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (sendThread != null)
{
sendThread.Abort();
}
if (listenThread != null)
{
listenThread.Abort();
}
if (listener != null && listener.IsListening)
{
listener.Stop();
}
}
}
}

 

 

 

 

 

原文鏈接:https://www.cnblogs.com/zjutlitao/p/3886826.html    &  https://blog.csdn.net/geekwangminli/article/details/7851673

 &    https://www.jb51.net/article/82144.htm    &   http://www.diy-robots.com/?p=410%20%E8%93%9D%E7%89%99


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM