Skip to content

Commit

Permalink
8
Browse files Browse the repository at this point in the history
  • Loading branch information
xianengqi committed Dec 23, 2024
1 parent c435108 commit 8406b94
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
Binary file not shown.
45 changes: 44 additions & 1 deletion demo-esp32/BlufiManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class BlufiManager: NSObject {
var onError: ((String) -> Void)?
var onConnected: (() -> Void)?
var onConfigured: (() -> Void)?
var onDeviceFound: ((CBPeripheral, NSNumber) -> Void)?

private override init() {
super.init()
Expand All @@ -21,17 +22,21 @@ class BlufiManager: NSObject {

// 开始扫描设备
func startScan() {
print("开始扫描...")
// 扫描所有可用设备,不过滤任何服务
centralManager?.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
}

// 停止扫描
func stopScan() {
print("停止扫描")
centralManager?.stopScan()
}

// 连接设备
func connect(peripheral: CBPeripheral) {
currentPeripheral = peripheral
peripheral.delegate = self // 设置代理
centralManager?.connect(peripheral, options: nil)
}

Expand Down Expand Up @@ -61,15 +66,28 @@ extension BlufiManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
print("蓝牙已开启")
onStateUpdate?("蓝牙已开启")
case .poweredOff:
print("蓝牙已关闭")
onStateUpdate?("蓝牙已关闭")
default:
print("蓝牙状态异常: \(central.state.rawValue)")
onError?("蓝牙状态异常")
}
}

// 发现外设
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// print("发现设备: \(peripheral.name ?? "Unknown") RSSI: \(RSSI)")

// 通知发现了新设备
onDeviceFound?(peripheral, RSSI)
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("已连接到设备: \(peripheral.name ?? "Unknown")")

// 创建并配置 BlufiClient
let client = BlufiClient()
client.blufiDelegate = self
Expand All @@ -80,33 +98,58 @@ extension BlufiManager: CBCentralManagerDelegate {
}

func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("连接失败: \(error?.localizedDescription ?? "未知错误")")
onError?("连接失败: \(error?.localizedDescription ?? "未知错误")")
}

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("设备断开连接: \(error?.localizedDescription ?? "正常断开")")
if let error = error {
onError?("设备断开连接: \(error.localizedDescription)")
}
}
}

// MARK: - CBPeripheralDelegate
extension BlufiManager: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("发现服务: \(error?.localizedDescription ?? "成功")")
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
print("发现特征: \(error?.localizedDescription ?? "成功")")
}
}

// MARK: - BlufiDelegate
extension BlufiManager: BlufiDelegate {
func blufi(_ client: BlufiClient!, gattPrepared status: Int32, service: CBService!, writeChar: CBCharacteristic!, notifyChar: CBCharacteristic!) {
if status == 0 {
print("GATT准备完成,开始安全协商")
client.negotiateSecurity()
} else {
print("GATT准备失败: \(status)")
onError?("GATT准备失败")
}
}

func blufi(_ client: BlufiClient!, didNegotiateSecurity status: Int32) {
if status == 0 {
print("安全协商成功")
onStateUpdate?("安全协商成功")
} else {
print("安全协商失败: \(status)")
onError?("安全协商失败")
}
}

func blufi(_ client: BlufiClient!, didPostConfigureParams status: Int32) {
if status == 0 {
print("WiFi配置成功")
onConfigured?()
} else {
print("WiFi配置失败: \(status)")
onError?("WiFi配置失败")
}
}
}
}
18 changes: 17 additions & 1 deletion demo-esp32/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,22 @@ class BluetoothViewModel: ObservableObject {
self?.state = .configured
}
}

// 添加设备发现回调
blufiManager.onDeviceFound = { [weak self] (peripheral, RSSI) in
DispatchQueue.main.async {
// 检查设备是否已存在
if !(self?.discoveredDevices.contains(where: { $0.peripheral.identifier == peripheral.identifier }) ?? false) {
let device = DiscoveredDevice(
id: UUID(),
peripheral: peripheral,
name: peripheral.name ?? "Unknown Device",
rssi: RSSI.intValue
)
self?.discoveredDevices.append(device)
}
}
}
}

func startScan() {
Expand Down Expand Up @@ -224,7 +240,7 @@ struct ContentView: View {
switch viewModel.state {
case .poweredOff: return "蓝牙已关闭"
case .poweredOn: return "蓝牙已开启"
case .scanning: return "正在扫描设备..."
case .scanning: return "正在扫���设备..."
case .connected: return "设备已连接"
case .configuring: return "正在配置WiFi..."
case .configured: return "配置成功"
Expand Down

0 comments on commit 8406b94

Please sign in to comment.