{"id":18272820,"url":"https://github.com/michaellynx/bledemo","last_synced_at":"2025-08-06T13:39:06.074Z","repository":{"id":45126022,"uuid":"249606015","full_name":"MichaelLynx/BleDemo","owner":"MichaelLynx","description":"swift版蓝牙连接Demo。Bluetooth demo for swift.","archived":false,"fork":false,"pushed_at":"2020-03-26T02:06:38.000Z","size":45,"stargazers_count":20,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-05T02:33:48.092Z","etag":null,"topics":["bluetooth","corebluetooth","ios","swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MichaelLynx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-03-24T03:42:40.000Z","updated_at":"2025-03-11T05:35:27.000Z","dependencies_parsed_at":"2022-07-13T09:50:33.220Z","dependency_job_id":null,"html_url":"https://github.com/MichaelLynx/BleDemo","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MichaelLynx/BleDemo","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichaelLynx%2FBleDemo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichaelLynx%2FBleDemo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichaelLynx%2FBleDemo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichaelLynx%2FBleDemo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MichaelLynx","download_url":"https://codeload.github.com/MichaelLynx/BleDemo/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichaelLynx%2FBleDemo/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266221459,"owners_count":23894966,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bluetooth","corebluetooth","ios","swift"],"created_at":"2024-11-05T12:03:58.046Z","updated_at":"2025-07-21T00:34:54.545Z","avatar_url":"https://github.com/MichaelLynx.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003e 之前做过蓝牙连接的功能，但是要么是直接在别人的基础上更改和新增功能，要么就是囫囵吞枣直接按别人的文章一步步写过去，写完了自己也还是没有头绪，仅仅是能用而已。这次借设计YModem升级工具及蓝牙多设备同时升级功能的机会，从头梳理一遍蓝牙连接的功能，并记之以文字。\n\n\n\n# 一、原理\n\n\u003e 更详细信息可以查看官方蓝牙框架文档：[《Core Bluetooth Programming Guide》](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/AboutCoreBluetooth/Introduction.html#//apple_ref/doc/uid/TP40013257-CH1-SW1)\n\u003e\n\u003e 文章链接：[蓝牙连接（swift版）](https://michaellynx.github.io/bluetooth-for-swift/)\n\n\n\n## 1.基本概念\n\n### 1.1 蓝牙版本\n\n#### 蓝牙2.0\n\n蓝牙2.0是传统蓝牙，也叫做经典蓝牙。\n\n蓝牙2.0如要上架需进行MFI认证，使用ExternalAccessory框架。\n\n#### 蓝牙4.0\n\n蓝牙4.0因为耗电低，也叫做低功耗蓝牙(BLE)。它将三种规格集于一体，包括传统蓝牙技术、高速技术和低耗能技术。\n\n蓝牙4.0使用CoreBluetooth框架。\n\n\n\n### 1.2 参数\n\n#### 基本参数\n\n- CBCentralManager：中心设备，连接硬件的设备。\n- CBPeripheral：外围设备，被连接的硬件。\n- service：服务\n- characteristic：特征\n\n一个外设包含多个服务,而每一个服务中又包含多个特征,特征包括特征的值和特征的描述.每个服务包含多个字段,字段的权限有read(读)、write(写)、notify(通知/订阅)。\n\n\n\n#### characteristic的三种操作：\n\n- write：发送信息给外围设备\n\n- notify：接收外围设备的通知\n\n- read：获取外围设备的信息。当部分设备为只读时，无法使用write发送信息给外围设备，但可以使用read去获取外围设备的信息。\n\n正常多使用write和notify。\n\n\n\n## 2.模式\n\n蓝牙开发分为两种模式，中心模式(central)，和外设模式(peripheral)。一般来讲，我们需要在软件内连接硬件，通过连接硬件给硬件发送指令以完成一些动作的蓝牙开发都是基于中心模式(central)模式的开发，也就是说我们开发的app是中心，我们要连接的硬件是外设。如果需要其他设备连接手机蓝牙，并对手机进行一些操作，那就是基于外设模式(peripheral)的开发。\n\n\n\n### 中心模式流程\n\n**swift版：**\n\n1. 创建中心设备(CBCentralManager)\n2. 中心设备开始扫描(scanForPeripherals)\n3. 扫描到外围设备之后, 自动调用中心设备的代理方法(didDiscoverPeripheral)\n4. 如果设备过多, 可以将扫描到的外围设备添加到数组\n5. 开始连接, 从数组中过滤出自己想要的设备, 进行连接(connectPeripheral)\n6. 连接上之后, 自动调用中心设备的代理方法(didConnectPeripheral), 在代理中, 进行查找外围设备的服务(peripheral.discoverServices)\n7. 查找到服务之后, 自动调用外围设备的代理(didDiscoverServices), 可通过UUID,查找具体的服务,查找服务(discoverCharacteristics)\n8. 查找到特征之后, 自动调用外围设备的代理(didDiscoverCharacteristics), 通过UUID找到自己想要的特征, 读取特征(readValueForCharacteristic)\n9. 读取到特征之后, 自动调用外设的代理方法(didUpdateValueForCharacteristic),在这里打印或者解析自己想要的特征值.\n\n**oc版：**\n\n1. 建立中心角色 [[CBCentralManager alloc] initWithDelegate:self queue:nil]\n2. 扫描外设 cancelPeripheralConnection\n3. 发现外设 didDiscoverPeripheral\n4. 连接外设 connectPeripheral\n   - 4.1连接失败 didFailToConnectPeripheral\n   - 4.2连接断开 didDisconnectPeripheral\n   - 4.3连接成功 didConnectPeripheral\n5. 扫描外设中的服务 discoverServices\n   - 5.1发现并获取外设中的服务 didDiscoverServices\n6. 扫描外设对应服务的特征 discoverCharacteristics\n   - 6.1发现并获取外设对应服务的特征 didDiscoverCharacteristicsForService\n   - 6.2给对应特征写数据 writeValue:forCharacteristic:type:\n7. 订阅特征的通知 setNotifyValue:forCharacteristic:\n   - 7.1根据特征读取数据 didUpdateValueForCharacteristic\n\n\n\n### 外设模式流程\n\n1. 建立外设设备\n2. 设置本地外设的服务和特征\n3. 发布外设和特征\n4. 广播服务\n5. 响应中心的读写请求\n6. 发送更新的特征值，订阅中心\n\n\u003cbr\u003e\n\n\n\n# 二、实现\n\n\u003e **常用方法**记录用到的方法，**代码**是具体运用\n\n\n\n## 2.1 前置\n\n- 设备的特征包含UUID，可通过UUID区分对应的特征。\n- 要用到蓝牙连接相关类的页面需导入头文件：`import CoreBluetooth`\n\n\n\n### 变量\n\n```swift\nprivate let BLE_WRITE_UUID = \"xxxx\"\nprivate let BLE_NOTIFY_UUID = \"xxxx\"\n\nvar centralManager:CBCentralManager?\n///扫描到的所有设备\nvar aPeArray:[CBPeripheral] = []\n//当前连接的设备\nvar pe:CBPeripheral?\nvar writeCh: CBCharacteristic?\nvar notifyCh: CBCharacteristic?\n```\n\n\n\n### 常用方法\n\n实例化\n\n```swift\nvar centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)\n```\n\n开始扫描\n\n```swift\ncentralManager.scanForPeripherals(withServices: serviceUUIDS, options: nil)\n```\n\n连接设备\n\n```swift\ncentralManager.connect(peripheral, options: nil)\n```\n\n- 连接设备之前要先设置代理，正常情况，当第一次获取外设peripheral的时候就会同时设置代理\n\n断开连接\n\n```swift\ncentralManager.cancelPeripheralConnection(peripheral)\n```\n\n停止扫描\n\n```swift\ncentralManager.stopScan()\n```\n\n发现服务\n\n```swift\nperipheral.discoverServices(nil)\n```\n\n- 外设连接成功的时候使用该方法发现服务\n- 一般在此处同步设置代理：`peripheral.delegate = self`\n\n发现特征\n\n```swift\nperipheral.discoverCharacteristics(nil, for: service)\n```\n\n- 搜索到服务之后执行该方法，将特征下的服务`peripheral.services`对应搜索特征\n\n设置通知\n\n```swift\nperipheral.setNotifyValue(true, for: characteristic)\n```\n\n- 当搜索到对应特征之后，可以根据条件判断是否设置及保存该特征，如特征的uuid\n- 通知的特征需要设置该项，以开启通知\n\n\n\n## 2.2 代码\n\n\n\n### 2.2.1 流程\n\n\n\n#### 实例化\n\n将CBCenteralManager实例化：\n\n```swift\ncentralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey:false])\n```\n\n实例化完成后的回调：\n\n```swift\nfunc centralManagerDidUpdateState(_ central: CBCentralManager) {\n    if central.state == CBManagerState.poweredOn {\n            print(\"powered on\")\n            \n        } else {\n            if central.state == CBManagerState.poweredOff {\n                print(\"BLE powered off\")\n            } else if central.state == CBManagerState.unauthorized {\n                print(\"BLE unauthorized\")\n            } else if central.state == CBManagerState.unknown {\n                print(\"BLE unknown\")\n            } else if central.state == CBManagerState.resetting {\n                print(\"BLE ressetting\")\n            }\n        }\n}\n```\n\n- CBCenteralManager实例化完毕，可以开始扫描外设`CBPeripheral`\n- 如无特殊要求，可以在此处直接进行扫描操作\n\n\n\n#### 扫描并发现设备\n\n扫描设备：\n\n```swift\ncentralManager.scanForPeripherals(withServices: serviceUUIDS, options: nil)\n```\n\n发现设备：\n\n```swift\nfunc centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {\n    guard !aPeArray.contains(peripheral), let deviceName = peripheral.name, deviceName.count \u003e 0 else {\n        return\n    }\n    \n}\n```\n\n- 此处可以将搜索到的设备保存并显示出来，也可以将需要的设备直接连接\n\n\n\n#### 连接设备\n\n连接设备：\n\n```swift\ncentralManager.connect(peripheral, options: nil)\n```\n\n设备连接完成后的回调：\n\n```swift\nfunc centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {\n    print(\"\\(#function)连接外设成功。\\ncentral:\\(central),peripheral:\\(peripheral)\\n\")\n    // 设置代理\n    peripheral.delegate = self\n    // 开始发现服务\n    peripheral.discoverServices(nil)\n}\n```\n\n- 连接完成后直接搜索对应的服务`Service`\n\n设备连接失败的回调：\n\n```swift\nfunc centralManager(_ central: CBCentralManager, didFailToConnect peripheral:\nCBPeripheral, error: Error?) {\n    print(\"\\(#function)连接外设失败\\n\\(String(describing:\nperipheral.name))连接失败：\\(String(describing: error))\\n\")\n    // 这里可以发通知出去告诉设备连接界面连接失败\n    \n}\n```\n\n连接丢失的回调：\n\n```swift\nfunc centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {\n    print(\"\\(#function)连接丢失\\n外设：\\(String(describing:\nperipheral.name))\\n错误：\\(String(describing: error))\\n\")\n    // 这里可以发通知出去告诉设备连接界面连接丢失\n    \n}\n```\n\n\n\n#### 搜索服务\n\n搜索服务（设备连接成功的回调处执行）：\n\n```swift\nperipheral.discoverServices(nil)\n```\n\n发现服务：\n\n```swift\nfunc peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {\n    if let error = error  {\n        print(\"\\(#function)搜索到服务-出错\\n设备(peripheral)：\\(String(describing:\nperipheral.name)) 搜索服务(Services)失败：\\(error)\\n\")\n        return\n    } else {\n        print(\"\\(#function)搜索到服务\\n设备(peripheral)：\\(String(describing:\nperipheral.name))\\n\")\n    }\n    for service in peripheral.services ?? [] {\n        peripheral.discoverCharacteristics(nil, for: service)\n    }\n}\n```\n\n- 搜索到服务之后直接搜索其对应的特征\n\n\n\n#### 搜索特征\n\n搜索特征（当发现服务之后即执行搜索）：\n\n```swift\nperipheral.discoverCharacteristics(nil, for: service)\n```\n\n发现特征\n\n```swift\nfunc peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {\n    if let _ = error {\n        print(\"\\(#function)发现特征\\n设备(peripheral)：\\(String(describing: peripheral.name))\\n服务(service)：\\(String(describing: service))\\n扫描特征(Characteristics)失败：\\(String(describing: error))\\n\")\n        return\n    } else {\n        print(\"\\(#function)发现特征\\n设备(peripheral)：\\(String(describing: peripheral.name))\\n服务(service)：\\(String(describing: service))\\n服务下的特征：\\(service.characteristics ?? [])\\n\")\n    }\n    \n    for characteristic in service.characteristics ?? [] {\n        if characteristic.uuid.uuidString.lowercased().isEqual(BLE_WRITE_UUID) {\n            pe = peripheral\n            writeCh = characteristic\n        } else if characteristic.uuid.uuidString.lowercased().isEqual(BLE_NOTIFY_UUID) {\n            notifyCh = characteristic\n            peripheral.setNotifyValue(true, for: characteristic)\n        }\n        //此处代表连接成功\n    }\n}\n```\n\n- 此处可保存连接设备外设`peripheral`和特征`characteristic`，后续发送接收数据时使用\n- swift的UUID与oc的不一样，要区分大小写，故UUID最好保存为字符串\n- 连接成功可在此处设置回调\n\n\n\n#### 读取设备发送的数据\n\n获取设备发送的数据：\n\n```swift\nfunc peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic:\nCBCharacteristic, error: Error?) {\n    if let _ = error {\n        return\n    }\n    //拿到设备发送过来的值,可传出去并进行处理\n    \n}\n```\n\n- 设备发送过来的数据会在此处回调，可设置闭包、协议等回调方式将值传出去\n\n\n\n#### 向设备发送数据\n\n发送数据：\n\n```swift\nperipheral.writeValue(data, for: characteristic, type: .withResponse)\n```\n\n- 类型根据需要填写\n- 特征`characteristic`需要是写入的特征，不能用其他的特征\n\n检测发送数据是否成功：\n\n```swift\nfunc peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {\n    if let error = error {\n        print(\"\\(#function)\\n发送数据失败！错误信息：\\(error)\")\n    }\n}\n```\n\n\n\n### 2.2.2 完整代码下载\n\ngithub代码：[BleDemo](https://github.com/MichaelLynx/BleDemo)\n\n欢迎相互学习交流，也欢迎去github点个star。\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaellynx%2Fbledemo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichaellynx%2Fbledemo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaellynx%2Fbledemo/lists"}