Commit 671a3d9e4f68a8db84cd9dabbd3f60d7bc86f544

Authored by jason
1 parent ac9763e7

refactor:replace the mtk with original code, for the mtk filter the peripheral's…

… services, can't get all sevices and no way to do the ota update
attension:redo the reconnect, triggered in init method instead
HDFwear/Home/HomeViewController.swift
@@ -93,7 +93,7 @@ class HomeViewController: UIViewController, CLLocationManagerDelegate { @@ -93,7 +93,7 @@ class HomeViewController: UIViewController, CLLocationManagerDelegate {
93 BluetoothManager.shared.startScanning()//modify断蓝牙连接不上Bug 93 BluetoothManager.shared.startScanning()//modify断蓝牙连接不上Bug
94 BluetoothManager.shared.registerDelegate(self) 94 BluetoothManager.shared.registerDelegate(self)
95 BluetoothManager.shared.registerSyncDelegate(self) 95 BluetoothManager.shared.registerSyncDelegate(self)
96 - BluetoothManager.shared.reConnect() 96 +// BluetoothManager.shared.reConnect()
97 // updateStepView() 97 // updateStepView()
98 98
99 if #available(iOS 14.0, *) { 99 if #available(iOS 14.0, *) {
HDFwear/Setting/SettingViewController.swift
@@ -82,6 +82,7 @@ class SettingViewController: UIViewController, LBXScanViewControllerDelegate { @@ -82,6 +82,7 @@ class SettingViewController: UIViewController, LBXScanViewControllerDelegate {
82 82
83 override func viewDidLoad() { 83 override func viewDidLoad() {
84 super.viewDidLoad() 84 super.viewDidLoad()
  85 + settingArray = setting_828
85 setupUI() 86 setupUI()
86 87
87 BluetoothManager.shared.registerDelegate(self) 88 BluetoothManager.shared.registerDelegate(self)
@@ -554,7 +555,9 @@ extension SettingViewController: BluetoothManagerDelegate { @@ -554,7 +555,9 @@ extension SettingViewController: BluetoothManagerDelegate {
554 GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing") 555 GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing")
555 } 556 }
556 557
557 - collectionView.reloadData() 558 + if settingArray.count > 1 {
  559 + collectionView.reloadData()
  560 + }
558 scanView?.updateUI(.PairSuccess) 561 scanView?.updateUI(.PairSuccess)
559 // addDeviceView.isHidden = true 562 // addDeviceView.isHidden = true
560 // connectView.isHidden = false 563 // connectView.isHidden = false
HDFwear/Tools/BluetoothManager+OTA.swift 0 → 100644
  1 +//
  2 +// BluetoothManager+OTA.swift
  3 +// HDFwear
  4 +//
  5 +// Created by admin on 2024/1/23.
  6 +//
  7 +
  8 +import Foundation
HDFwear/Tools/BluetoothManager.swift
@@ -69,6 +69,7 @@ extension BluetoothSyncDelegate { @@ -69,6 +69,7 @@ extension BluetoothSyncDelegate {
69 69
70 70
71 class BluetoothManager: NSObject { 71 class BluetoothManager: NSObject {
  72 + private var peripheralUUIDKey = "lastConnectedPeripheralUUID"
72 //Closure 73 //Closure
73 var setCmdClosure: ((_ error: Int?) -> ())? 74 var setCmdClosure: ((_ error: Int?) -> ())?
74 75
@@ -132,7 +133,7 @@ class BluetoothManager: NSObject { @@ -132,7 +133,7 @@ class BluetoothManager: NSObject {
132 133
133 // weak var delegate: BluetoothManagerDelegate? 134 // weak var delegate: BluetoothManagerDelegate?
134 135
135 - var manger: MTKBleManager? 136 +// var manger: MTKBleManager?
136 var peripheral: CBPeripheral? = nil 137 var peripheral: CBPeripheral? = nil
137 // private var conPeripheral: CBPeripheral? = nil //已连接的 138 // private var conPeripheral: CBPeripheral? = nil //已连接的
138 var platform: Platform = .other 139 var platform: Platform = .other
@@ -146,7 +147,8 @@ class BluetoothManager: NSObject { @@ -146,7 +147,8 @@ class BluetoothManager: NSObject {
146 private var contactArray: [ContactModel] = [] 147 private var contactArray: [ContactModel] = []
147 148
148 //ota 149 //ota
149 - var transceiver = LETransceiver() 150 + var isOTAUpdating: Bool = false
  151 + var otaTransceiver : LETransceiver?
150 var otaManager = OTAManager() 152 var otaManager = OTAManager()
151 153
152 //mergeData 154 //mergeData
@@ -170,32 +172,34 @@ class BluetoothManager: NSObject { @@ -170,32 +172,34 @@ class BluetoothManager: NSObject {
170 // manger.registerClientProfile(BLEConfig.MTKBasServerUUID, clientProfileDelegate: self) 172 // manger.registerClientProfile(BLEConfig.MTKBasServerUUID, clientProfileDelegate: self)
171 // manger.registerClientProfile(BLEConfig.MTKDialServerUUID, clientProfileDelegate: self) 173 // manger.registerClientProfile(BLEConfig.MTKDialServerUUID, clientProfileDelegate: self)
172 // FmpGattClient.getInstance() 174 // FmpGattClient.getInstance()
173 - manger = MTKBleManager.sharedInstance() as? MTKBleManager 175 +// manger = MTKBleManager.sharedInstance() as? MTKBleManager
174 platform = CurDevice.platform 176 platform = CurDevice.platform
175 - setupManger(nil) 177 +// setupManger(nil)
176 // registerClientProfile() 178 // registerClientProfile()
  179 +// let options = ["CBCentralManagerOptionShowPowerAlertKey":false]
  180 + centralManger = CBCentralManager(delegate: self, queue: .main)
177 181
178 } 182 }
179 - private func setupManger(_ peripheral: CBPeripheral?) {  
180 - if peripheral == nil {  
181 - if CurDevice.uuid == "" {  
182 - return  
183 - } else {  
184 - registerClientProfile()  
185 - }  
186 - } else {  
187 - registerClientProfile()  
188 - }  
189 - }  
190 -  
191 - private func registerClientProfile() {  
192 - switch platform {  
193 - case ._828:  
194 - manger?.registerClientProfile(BLEConfig.ServerUUID, clientProfileDelegate: self)  
195 - default:  
196 - break  
197 - }  
198 - } 183 +// private func setupManger(_ peripheral: CBPeripheral?) {
  184 +// if peripheral == nil {
  185 +// if CurDevice.uuid == "" {
  186 +// return
  187 +// } else {
  188 +// registerClientProfile()
  189 +// }
  190 +// } else {
  191 +// registerClientProfile()
  192 +// }
  193 +// }
  194 +//
  195 +// private func registerClientProfile() {
  196 +// switch platform {
  197 +// case ._828:
  198 +// manger?.registerClientProfile(BLEConfig.ServerUUID, clientProfileDelegate: self)
  199 +// default:
  200 +// break
  201 +// }
  202 +// }
199 203
200 func registerDelegate(_ delegate: BluetoothManagerDelegate) { 204 func registerDelegate(_ delegate: BluetoothManagerDelegate) {
201 delegateList.append(delegate) 205 delegateList.append(delegate)
@@ -223,10 +227,18 @@ class BluetoothManager: NSObject { @@ -223,10 +227,18 @@ class BluetoothManager: NSObject {
223 print("jason_bluetooth_action_0:开始扫描") 227 print("jason_bluetooth_action_0:开始扫描")
224 peripheralDic = [:] 228 peripheralDic = [:]
225 deviceArray = [] 229 deviceArray = []
226 - centralManger = CBCentralManager(delegate: self, queue: nil)  
227 -  
228 - manger?.startScanning()  
229 -//mClientProfileDic __NSDictionaryM * 1 key/value pair 0x0000000281a694c0 230 + if centralManger != nil {
  231 +// getInfo(state: centralManger!.state)
  232 + centralManger!.scanForPeripherals(withServices: nil, options: nil)
  233 + } else {
  234 + let options = ["CBCentralManagerOptionShowPowerAlertKey":false]
  235 + centralManger = CBCentralManager(delegate: self, queue: .main, options: options)
  236 + centralManger!.scanForPeripherals(withServices: nil, options: nil)
  237 + }
  238 +// centralManger = CBCentralManager(delegate: self, queue: nil)
  239 +//
  240 +// manger?.startScanning()
  241 +////mClientProfileDic __NSDictionaryM * 1 key/value pair 0x0000000281a694c0
230 } 242 }
231 243
232 func stopScanning() { 244 func stopScanning() {
@@ -234,9 +246,9 @@ class BluetoothManager: NSObject { @@ -234,9 +246,9 @@ class BluetoothManager: NSObject {
234 if centralManger!.isScanning { 246 if centralManger!.isScanning {
235 centralManger?.stopScan() 247 centralManger?.stopScan()
236 } 248 }
237 - centralManger = nil 249 +// centralManger = nil
238 } 250 }
239 - manger?.stopScanning() 251 +// manger?.stopScanning()
240 252
241 } 253 }
242 254
@@ -246,8 +258,11 @@ class BluetoothManager: NSObject { @@ -246,8 +258,11 @@ class BluetoothManager: NSObject {
246 let name = peripheral.name 258 let name = peripheral.name
247 // 这里是根据名字来判断其平台类型 259 // 这里是根据名字来判断其平台类型
248 platform = ._828 260 platform = ._828
249 - registerClientProfile()  
250 - manger?.connectPeripheral(peripheral) 261 + if centralManger != nil {
  262 + centralManger!.connect(peripheral, options: nil)
  263 + }
  264 +// registerClientProfile()
  265 +// manger?.connectPeripheral(peripheral)
251 } 266 }
252 267
253 func reconnectPer() { 268 func reconnectPer() {
@@ -260,16 +275,17 @@ class BluetoothManager: NSObject { @@ -260,16 +275,17 @@ class BluetoothManager: NSObject {
260 275
261 276
262 func reConnect() { 277 func reConnect() {
263 - startScanning() 278 +// startScanning()
  279 + reconnectToPeripheral()
264 } 280 }
265 281
266 func forgetPeripheral() { 282 func forgetPeripheral() {
267 print("forgetPeripheral") 283 print("forgetPeripheral")
268 - manger?.forgetPeripheral() 284 +// manger?.forgetPeripheral()
269 // let menstrual = .menstrual 285 // let menstrual = .menstrual
270 - manger = nil 286 +// manger = nil
271 // MTKBleManager.sharedInstance() = nil 287 // MTKBleManager.sharedInstance() = nil
272 - manger = MTKBleManager.sharedInstance() as? MTKBleManager 288 +// manger = MTKBleManager.sharedInstance() as? MTKBleManager
273 289
274 // OTAPeripheral = nil 290 // OTAPeripheral = nil
275 peripheral = nil 291 peripheral = nil
@@ -280,8 +296,12 @@ class BluetoothManager: NSObject { @@ -280,8 +296,12 @@ class BluetoothManager: NSObject {
280 296
281 func disconnect() { 297 func disconnect() {
282 for per in connectedPerArray { 298 for per in connectedPerArray {
283 - manger?.disconnectPeripheral(per) 299 +// manger?.disconnectPeripheral(per)
  300 + if centralManger != nil {
  301 + centralManger!.cancelPeripheralConnection(per)
  302 + }
284 } 303 }
  304 + connectedPerArray = []
285 305
286 // manger.disconnectPeripheral() 306 // manger.disconnectPeripheral()
287 // manger.foundPeripherals = [] 307 // manger.foundPeripherals = []
@@ -296,10 +316,10 @@ class BluetoothManager: NSObject { @@ -296,10 +316,10 @@ class BluetoothManager: NSObject {
296 disconnect() 316 disconnect()
297 // peripheral = nil 317 // peripheral = nil
298 // manger.peripheral = nil 318 // manger.peripheral = nil
299 - manger?.foundPeripherals = nil  
300 - manger?.tempPeripheral = nil  
301 - manger?.connectedService = nil  
302 - manger?.connectPeripherals = nil 319 +// manger?.foundPeripherals = nil
  320 +// manger?.tempPeripheral = nil
  321 +// manger?.connectedService = nil
  322 +// manger?.connectPeripherals = nil
303 // if centralManger != nil { 323 // if centralManger != nil {
304 // if centralManger!.isScanning { 324 // if centralManger!.isScanning {
305 // centralManger?.stopScan() 325 // centralManger?.stopScan()
@@ -1342,24 +1362,243 @@ class BluetoothManager: NSObject { @@ -1342,24 +1362,243 @@ class BluetoothManager: NSObject {
1342 } 1362 }
1343 1363
1344 1364
1345 -extension BluetoothManager: ClientProfileDelegate {  
1346 - func onCentralManagerStateChange(_ state: Int32) {  
1347 -// var managerState: CBCentralManagerState = .unknown  
1348 - switch state {  
1349 - case 0:  
1350 -// managerState = .unknown 1365 +//extension BluetoothManager: ClientProfileDelegate {
  1366 +// func onCentralManagerStateChange(_ state: Int32) {
  1367 +//// var managerState: CBCentralManagerState = .unknown
  1368 +// switch state {
  1369 +// case 0:
  1370 +//// managerState = .unknown
  1371 +// print("unknown")
  1372 +// case 1:
  1373 +//// managerState = .resetting
  1374 +// print("resetting")
  1375 +// case 2:
  1376 +//// managerState = .unsupported
  1377 +// print("unsupported")
  1378 +// case 3:
  1379 +//// managerState = .unauthorized
  1380 +// print("unauthorized")
  1381 +// case 4:
  1382 +//// managerState = .poweredOff
  1383 +// print("poweredOff")
  1384 +// if DeviceIsConnected {
  1385 +// DeviceIsConnected = false
  1386 +// for delegate in delegateList {
  1387 +// delegate.didDisconnected()
  1388 +// }
  1389 +// }
  1390 +// case 5:
  1391 +// print("poweredOn")
  1392 +//// managerState = .poweredOn
  1393 +// centralManger?.scanForPeripherals(withServices: nil, options: nil)
  1394 +// default:
  1395 +// print(" ")
  1396 +// }
  1397 +//
  1398 +// for delegate in delegateList {
  1399 +// delegate.centralManagerDidUpdateState(Int(state))
  1400 +// }
  1401 +// }
  1402 +//
  1403 +// func onConnected(_ peripheral: CBPeripheral!) {
  1404 +// print("jason_bluetooth_action_3:通过MTKBleManager的ClientProfileDelegate得到连接成功回调");
  1405 +// print("已经连接: \(peripheral.identifier.uuidString)--\(peripheral.name ?? "")")
  1406 +//
  1407 +// stopScanning()
  1408 +// connectedPerArray.append(peripheral)
  1409 +// self.peripheral = peripheral
  1410 +// print("jason_bluetooth_action_4:开始发现外设服务");
  1411 +// peripheral.discoverServices(nil)
  1412 +//
  1413 +//// var delayTime: Double = 2
  1414 +//
  1415 +// if CurDevice.uuid == "" {
  1416 +// var mac = ""
  1417 +// for device in deviceArray {
  1418 +// if peripheral!.identifier.uuidString == device.peripheral.identifier.uuidString {
  1419 +// mac = device.mac
  1420 +// }
  1421 +// }
  1422 +//
  1423 +// let admin = AdminHelper.shared.loadLocalAdminData()
  1424 +// if admin.userInfo.mac != mac {
  1425 +// print("不同设备")
  1426 +// admin.userInfo.mac = mac
  1427 +// admin.userInfo.dailVersion = "0"
  1428 +// admin.userInfo.isDailSync = false
  1429 +// admin.userInfo.dailIndex = -1
  1430 +// admin.userInfo.dialIndexPath = ""
  1431 +// admin.userInfo.customDial = ""
  1432 +//// admin.userInfo.dialNumDic = [:]
  1433 +// }
  1434 +// admin.device = DeviceModel(uuid: peripheral!.identifier.uuidString, name: peripheral!.name ?? "", platform: platform, mac: mac)
  1435 +//
  1436 +// AdminHelper.shared.savaAdminInfo(admin)
  1437 +//// AdminHelper.shared.updateDevice(DeviceModel(uuid: peripheral!.identifier.uuidString, name: peripheral!.name ?? "", platform: platform, mac: mac))
  1438 +//// delayTime = 3
  1439 +//// GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "SyncLanguage", timeInterval: 2, queue: .main, repeats: false) {
  1440 +//// self.syncLanguage()
  1441 +//// }
  1442 +// }
  1443 +//
  1444 +// if platform == ._828 {
  1445 +// print("828连接")
  1446 +//// OTAProfile = RTKOTAProfile(delegate: self)
  1447 +// //j!!! 取消自动同步
  1448 +//// startSync828(delayTime)
  1449 +// }
  1450 +//
  1451 +// DeviceIsConnected = true
  1452 +//// MusicManager.shared.controlMusic()
  1453 +// for delegate in delegateList {
  1454 +// delegate.didConnect(peripheral, CurDevice.mac)
  1455 +// }
  1456 +//
  1457 +//// GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "FirstSync", timeInterval: 5+delayTime, queue: .main, repeats: false) {
  1458 +//// self.syncBug()
  1459 +//// for delegate in self.syncDelegateList {
  1460 +//// delegate.firstSync()
  1461 +//// }
  1462 +//// }
  1463 +////
  1464 +//// isFirstSync = true
  1465 +// }
  1466 +//
  1467 +// func onDisconnected() {
  1468 +// for delegate in delegateList {
  1469 +// delegate.didDisconnected()
  1470 +// }
  1471 +// print("断开连接1")
  1472 +// }
  1473 +//
  1474 +// func onServiceDiscovered(_ periphearl: CBPeripheral!, error: Error!) {
  1475 +// print("jason_bluetooth_action_5:通过MTKBleManager的ClientProfileDelegate得到发现服务成功回调,这里应该是SDK做了相关后续动作,直接触发后续回调");
  1476 +//// print("已经连接2")
  1477 +// }
  1478 +//
  1479 +// func onCharacteristicDiscovered(_ peripheral: CBPeripheral!, for service: CBService!, error err: Error!) {
  1480 +// print("jason_bluetooth_action_6:通过MTKBleManager的ClientProfileDelegate得到发现特征回调");
  1481 +// if service.characteristics == nil {
  1482 +// return
  1483 +// }
  1484 +// for char in service.characteristics! {
  1485 +// let uuid = char.uuid.uuidString
  1486 +// // 这里读出来的uuid被截断,应该是本身数据有问题
  1487 +//// switch uuid {
  1488 +//// case BLEConfig.MTKReadUUID, BLEConfig.MTKBasReadUUID, BLEConfig.MTKDialReadUUID, BLEConfig.ReadUUID:
  1489 +//// peripheral.setNotifyValue(true, for: char)
  1490 +//// default:
  1491 +//// break
  1492 +//// }
  1493 +// if BLEConfig.ReadUUID .contains(uuid) {
  1494 +// peripheral.setNotifyValue(true, for: char)
  1495 +// }
  1496 +// }
  1497 +// }
  1498 +// //MARK: - 接收数据
  1499 +// func onUpdateValue(forCharacteristic peripheral: CBPeripheral!, for characteristic: CBCharacteristic!, error err: Error!) {
  1500 +// guard let data = characteristic.value, data.count >= 0 else {
  1501 +// return
  1502 +// }
  1503 +//
  1504 +// switch characteristic.uuid.uuidString {
  1505 +// case BLEConfig.MTKBasReadUUID:
  1506 +// print("电量------\([UInt8](data))")
  1507 +// Battery = Int([UInt8](data)[0])
  1508 +// for delegate in syncDelegateList {
  1509 +// delegate.didReceiveBattery(value: Battery)
  1510 +// }
  1511 +// case BLEConfig.MTKDialReadUUID:
  1512 +// print("表盘------\([UInt8](data))")
  1513 +// let bytes = [UInt8](data)
  1514 +// if bytes.count > 13 {
  1515 +// if bytes[13] == 1 {
  1516 +// sendNextSyncData()
  1517 +// } else if bytes[13] == 2 {
  1518 +//// sendDialData(dialRemainData)
  1519 +// }
  1520 +// }
  1521 +// case BLEConfig.ReadUUID:
  1522 +// print("接收: \([UInt8](data))")
  1523 +// mergeData(data)
  1524 +// default:
  1525 +// print("接收: \([UInt8](data))")
  1526 +// mergeData(data)
  1527 +// }
  1528 +// }
  1529 +//
  1530 +// func mergeData(_ data: Data) {
  1531 +// let bytes = [UInt8](data)
  1532 +//// print(bytes)
  1533 +// isSyncReceived = true
  1534 +// if bytes[0] == 0xED && bytes[1] == 0x7E {
  1535 +//// if bytes.count > 10, BleCmd(rawValue: bytes[8]) == .sync {
  1536 +//// if isSync {
  1537 +//// if SyncCmd(rawValue: bytes[10]) != isSyncType {
  1538 +//// syncReceiveFail()
  1539 +//// } else {
  1540 +//// isNextSync = bytes[1] == 112
  1541 +//// startSyncTimer()
  1542 +//// isSyncReceived = true
  1543 +//// }
  1544 +//// }
  1545 +//// }
  1546 +// // 内容长度加上其他位的长度
  1547 +// totalLength = Int(UInt16(bytes[8]) << 8 | UInt16(bytes[9])) + 12
  1548 +// if data.count == totalLength {
  1549 +// parseData(bytes)
  1550 +// } else {
  1551 +// totalBytes = []
  1552 +// totalBytes.append(contentsOf: bytes)
  1553 +// mergeLength = bytes.count
  1554 +// }
  1555 +// } else {
  1556 +// if isSync {
  1557 +// if isSyncReceived {
  1558 +// startSyncTimer()
  1559 +// isSyncReceived = true
  1560 +// }
  1561 +// }
  1562 +// totalBytes.append(contentsOf: bytes)
  1563 +// mergeLength += bytes.count
  1564 +// if mergeLength == totalLength {
  1565 +// parseData(totalBytes)
  1566 +// }
  1567 +// }
  1568 +//
  1569 +//
  1570 +// }
  1571 +//
  1572 +//
  1573 +// func onCharacteristicWrite() {
  1574 +//// print("已经连接5")
  1575 +// }
  1576 +//
  1577 +// func onReadRssi(_ peripheral: CBPeripheral!, rssiValue rssi: Int32, error err: Error!) {
  1578 +//// print("已经连接6")
  1579 +// }
  1580 +//}
  1581 +
  1582 +
  1583 +
  1584 +extension BluetoothManager: CBCentralManagerDelegate {
  1585 + func centralManagerDidUpdateState(_ central: CBCentralManager) {
  1586 + // var managerState: CBCentralManagerState = .unknown
  1587 + switch central.state {
  1588 + case .unknown:
  1589 + // managerState = .unknown
1351 print("unknown") 1590 print("unknown")
1352 - case 1:  
1353 -// managerState = .resetting 1591 + case .resetting:
  1592 + // managerState = .resetting
1354 print("resetting") 1593 print("resetting")
1355 - case 2:  
1356 -// managerState = .unsupported 1594 + case .unsupported:
  1595 + // managerState = .unsupported
1357 print("unsupported") 1596 print("unsupported")
1358 - case 3:  
1359 -// managerState = .unauthorized 1597 + case .unauthorized:
  1598 + // managerState = .unauthorized
1360 print("unauthorized") 1599 print("unauthorized")
1361 - case 4:  
1362 -// managerState = .poweredOff 1600 + case .poweredOff:
  1601 + // managerState = .poweredOff
1363 print("poweredOff") 1602 print("poweredOff")
1364 if DeviceIsConnected { 1603 if DeviceIsConnected {
1365 DeviceIsConnected = false 1604 DeviceIsConnected = false
@@ -1367,27 +1606,93 @@ extension BluetoothManager: ClientProfileDelegate { @@ -1367,27 +1606,93 @@ extension BluetoothManager: ClientProfileDelegate {
1367 delegate.didDisconnected() 1606 delegate.didDisconnected()
1368 } 1607 }
1369 } 1608 }
1370 - case 5: 1609 + case .poweredOn:
1371 print("poweredOn") 1610 print("poweredOn")
1372 -// managerState = .poweredOn  
1373 - centralManger?.scanForPeripherals(withServices: nil, options: nil) 1611 + // managerState = .poweredOn
  1612 + reconnectToPeripheral()
  1613 +// centralManger?.scanForPeripherals(withServices: nil, options: nil)
1374 default: 1614 default:
1375 print(" ") 1615 print(" ")
1376 } 1616 }
1377 1617
1378 for delegate in delegateList { 1618 for delegate in delegateList {
1379 - delegate.centralManagerDidUpdateState(Int(state)) 1619 + delegate.centralManagerDidUpdateState(Int(central.state.rawValue))
1380 } 1620 }
1381 } 1621 }
1382 1622
1383 - func onConnected(_ peripheral: CBPeripheral!) {  
1384 - print("jason_bluetooth_action_3:通过MTKBleManager的ClientProfileDelegate得到连接成功回调");  
1385 - print("已经连接: \(peripheral.identifier.uuidString)--\(peripheral.name ?? "")") 1623 + func reconnectToPeripheral() {
  1624 + print("try reconnectToPeripheral")
  1625 + guard let savedUUIDString = UserDefaults.standard.string(forKey: peripheralUUIDKey),
  1626 + let savedUUID = UUID(uuidString: savedUUIDString) else {
  1627 + // 没有保存的设备UUID,可能是首次连接
  1628 + return
  1629 + }
  1630 +
  1631 + let peripherals = centralManger?.retrievePeripherals(withIdentifiers: [savedUUID])
  1632 + if let peripheral = peripherals?.first {
  1633 + self.peripheral = peripheral
  1634 + self.peripheral?.delegate = self
  1635 + print("reconnectToPeripheral work")
  1636 + centralManger?.connect(peripheral, options: nil)
  1637 + }
  1638 + }
1386 1639
  1640 + func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
  1641 + print("jason_bluetooth_action_1:通过CBCentralManagerDelegate回调得到扫描结果");
  1642 + print("jason " + (peripheral.name ?? ""));
  1643 + if peripheralDic.keys.contains(peripheral.identifier.uuidString) {
  1644 + return
  1645 + }
  1646 +// if peripheral.name?.range(of: "You 1_LE") != nil || peripheral.name?.range(of: "Pro_LE") != nil || peripheral.name?.range(of: "MTB025B") != nil || peripheral.name?.range(of: "MTB033B") != nil || peripheral.name?.range(of: "hq7") != nil || peripheral.name?.range(of: "D09") != nil || peripheral.name?.range(of: "P8GT") != nil || peripheral.name?.range(of: "hq8") != nil || peripheral.name?.range(of: "Watch 8") != nil || peripheral.name?.range(of: "D07") != nil || peripheral.name?.range(of: "S7 NO.1") != nil || peripheral.name?.range(of: "G7 Pro Max Gameboy") != nil {
  1647 +// if peripheral.name?.range(of: "KV-S10f44efd8deb8b") != nil {
  1648 +// if peripheral.name?.range(of: "CHiQ Compass_50c0f0668129") != nil {
  1649 + if peripheral.name?.range(of: "CHiQ") != nil {
  1650 + peripheralDic[peripheral.identifier.uuidString] = peripheral
  1651 + // print(peripheral.name)key String "kCBAdvDataServiceData"
  1652 +
  1653 +
  1654 + if let data = advertisementData["kCBAdvDataManufacturerData"] as? Data {
  1655 + var mac = data.hexToString(":")
  1656 + mac = mac.substring(fromIndex: mac.length-17)
  1657 + deviceArray.append(ScanDevice(peripheral, mac: mac))
  1658 + for delegate in delegateList {
  1659 + delegate.didDiscover(devices: deviceArray)
  1660 + }
  1661 + } else {
  1662 + if let json = advertisementData["kCBAdvDataServiceData"] {
  1663 + if let dic = json as? Dictionary<CBUUID, Data> {
  1664 + if let data = dic.values.first {
  1665 + var mac = data.hexToString(":")
  1666 + mac = mac.substring(fromIndex: mac.length-17)
  1667 + deviceArray.append(ScanDevice(peripheral, mac: mac))
  1668 + for delegate in delegateList {
  1669 + delegate.didDiscover(devices: deviceArray)
  1670 + }
  1671 + }
  1672 + }
  1673 + }else {// 当无值时直接给个值跑通调试
  1674 + var mac = "111"
  1675 + deviceArray.append(ScanDevice(peripheral, mac: mac))
  1676 + for delegate in delegateList {
  1677 + delegate.didDiscover(devices: deviceArray)
  1678 + }
  1679 + }
  1680 + }
  1681 + }
  1682 + }
  1683 +
  1684 + func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
  1685 + print("jason_bluetooth_action_3:得到连接成功回调");
  1686 + print("已经连接: \(peripheral.identifier.uuidString)--\(peripheral.name ?? "")")
  1687 + // 连接成功,保存设备 UUID
  1688 + UserDefaults.standard.set(peripheral.identifier.uuidString, forKey: peripheralUUIDKey)
  1689 + UserDefaults.standard.synchronize()
  1690 +
1387 stopScanning() 1691 stopScanning()
1388 connectedPerArray.append(peripheral) 1692 connectedPerArray.append(peripheral)
1389 self.peripheral = peripheral 1693 self.peripheral = peripheral
1390 print("jason_bluetooth_action_4:开始发现外设服务"); 1694 print("jason_bluetooth_action_4:开始发现外设服务");
  1695 + peripheral.delegate = self;
1391 peripheral.discoverServices(nil) 1696 peripheral.discoverServices(nil)
1392 1697
1393 // var delayTime: Double = 2 1698 // var delayTime: Double = 2
@@ -1395,7 +1700,7 @@ extension BluetoothManager: ClientProfileDelegate { @@ -1395,7 +1700,7 @@ extension BluetoothManager: ClientProfileDelegate {
1395 if CurDevice.uuid == "" { 1700 if CurDevice.uuid == "" {
1396 var mac = "" 1701 var mac = ""
1397 for device in deviceArray { 1702 for device in deviceArray {
1398 - if peripheral!.identifier.uuidString == device.peripheral.identifier.uuidString { 1703 + if peripheral.identifier.uuidString == device.peripheral.identifier.uuidString {
1399 mac = device.mac 1704 mac = device.mac
1400 } 1705 }
1401 } 1706 }
@@ -1411,7 +1716,7 @@ extension BluetoothManager: ClientProfileDelegate { @@ -1411,7 +1716,7 @@ extension BluetoothManager: ClientProfileDelegate {
1411 admin.userInfo.customDial = "" 1716 admin.userInfo.customDial = ""
1412 // admin.userInfo.dialNumDic = [:] 1717 // admin.userInfo.dialNumDic = [:]
1413 } 1718 }
1414 - admin.device = DeviceModel(uuid: peripheral!.identifier.uuidString, name: peripheral!.name ?? "", platform: platform, mac: mac) 1719 + admin.device = DeviceModel(uuid: peripheral.identifier.uuidString, name: peripheral.name ?? "", platform: platform, mac: mac)
1415 1720
1416 AdminHelper.shared.savaAdminInfo(admin) 1721 AdminHelper.shared.savaAdminInfo(admin)
1417 // AdminHelper.shared.updateDevice(DeviceModel(uuid: peripheral!.identifier.uuidString, name: peripheral!.name ?? "", platform: platform, mac: mac)) 1722 // AdminHelper.shared.updateDevice(DeviceModel(uuid: peripheral!.identifier.uuidString, name: peripheral!.name ?? "", platform: platform, mac: mac))
@@ -1444,20 +1749,34 @@ extension BluetoothManager: ClientProfileDelegate { @@ -1444,20 +1749,34 @@ extension BluetoothManager: ClientProfileDelegate {
1444 // isFirstSync = true 1749 // isFirstSync = true
1445 } 1750 }
1446 1751
1447 - func onDisconnected() {  
1448 - for delegate in delegateList {  
1449 - delegate.didDisconnected()  
1450 - }  
1451 - print("断开连接1") 1752 + func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
  1753 +
1452 } 1754 }
1453 1755
1454 - func onServiceDiscovered(_ periphearl: CBPeripheral!, error: Error!) {  
1455 - print("jason_bluetooth_action_5:通过MTKBleManager的ClientProfileDelegate得到发现服务成功回调,这里应该是SDK做了相关后续动作,直接触发后续回调");  
1456 -// print("已经连接2") 1756 + func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
  1757 +
  1758 + }
  1759 +}
  1760 +
  1761 +extension BluetoothManager: CBPeripheralDelegate {
  1762 + func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
  1763 + print("didDiscoverServices: \(peripheral.name ?? "")")
  1764 +
  1765 + guard error == nil else {
  1766 + print("Error discovering service: \(error!.localizedDescription)")
  1767 + return
  1768 + }
  1769 +
  1770 + if let services = peripheral.services {
  1771 + for service in services {
  1772 + print("service: \(service)")
  1773 + peripheral.discoverCharacteristics(nil, for: service)
  1774 + }
  1775 + }
1457 } 1776 }
1458 1777
1459 - func onCharacteristicDiscovered(_ peripheral: CBPeripheral!, for service: CBService!, error err: Error!) {  
1460 - print("jason_bluetooth_action_6:通过MTKBleManager的ClientProfileDelegate得到发现特征回调"); 1778 + func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
  1779 + print("jason_bluetooth_action_6:得到发现特征回调");
1461 if service.characteristics == nil { 1780 if service.characteristics == nil {
1462 return 1781 return
1463 } 1782 }
@@ -1475,8 +1794,12 @@ extension BluetoothManager: ClientProfileDelegate { @@ -1475,8 +1794,12 @@ extension BluetoothManager: ClientProfileDelegate {
1475 } 1794 }
1476 } 1795 }
1477 } 1796 }
1478 - //MARK: - 接收数据  
1479 - func onUpdateValue(forCharacteristic peripheral: CBPeripheral!, for characteristic: CBCharacteristic!, error err: Error!) { 1797 +
  1798 + func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
  1799 +
  1800 + }
  1801 +
  1802 + func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
1480 guard let data = characteristic.value, data.count >= 0 else { 1803 guard let data = characteristic.value, data.count >= 0 else {
1481 return 1804 return
1482 } 1805 }
@@ -1545,95 +1868,7 @@ extension BluetoothManager: ClientProfileDelegate { @@ -1545,95 +1868,7 @@ extension BluetoothManager: ClientProfileDelegate {
1545 parseData(totalBytes) 1868 parseData(totalBytes)
1546 } 1869 }
1547 } 1870 }
1548 -  
1549 -  
1550 } 1871 }
1551 -  
1552 -  
1553 - func onCharacteristicWrite() {  
1554 -// print("已经连接5")  
1555 - }  
1556 -  
1557 - func onReadRssi(_ peripheral: CBPeripheral!, rssiValue rssi: Int32, error err: Error!) {  
1558 -// print("已经连接6")  
1559 - }  
1560 -}  
1561 -  
1562 -  
1563 -  
1564 -extension BluetoothManager: CBCentralManagerDelegate {  
1565 - func centralManagerDidUpdateState(_ central: CBCentralManager) {  
1566 - switch central.state {  
1567 - case .unknown:  
1568 - print("unknown1")  
1569 - case .resetting:  
1570 - print("resetting1")  
1571 - case .unsupported:  
1572 - print("unsupported1")  
1573 - case .unauthorized:  
1574 - if let curVC = UIViewController.getCurrentViewController() {  
1575 - curVC.showAlert(title: LocString("提示"), message: LocString("请在“设置-隐私-蓝牙”选项中,允许'YTWatch'使用蓝牙"), cancelText: nil, confirm: nil)  
1576 - }  
1577 - print("unauthorized1")  
1578 - case .poweredOff:  
1579 - print("poweredOff1")  
1580 - case .poweredOn:  
1581 - print("poweredOn1")  
1582 - centralManger?.scanForPeripherals(withServices: nil, options: nil)  
1583 - @unknown default:  
1584 - print(" ")  
1585 - }  
1586 -  
1587 - for delegate in delegateList {  
1588 - delegate.centralManagerDidUpdateState(central.state.rawValue)  
1589 - }  
1590 -  
1591 - }  
1592 -  
1593 - func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {  
1594 - print("jason_bluetooth_action_1:通过CBCentralManagerDelegate回调得到扫描结果");  
1595 - print("jason " + (peripheral.name ?? ""));  
1596 - if peripheralDic.keys.contains(peripheral.identifier.uuidString) {  
1597 - return  
1598 - }  
1599 -// if peripheral.name?.range(of: "You 1_LE") != nil || peripheral.name?.range(of: "Pro_LE") != nil || peripheral.name?.range(of: "MTB025B") != nil || peripheral.name?.range(of: "MTB033B") != nil || peripheral.name?.range(of: "hq7") != nil || peripheral.name?.range(of: "D09") != nil || peripheral.name?.range(of: "P8GT") != nil || peripheral.name?.range(of: "hq8") != nil || peripheral.name?.range(of: "Watch 8") != nil || peripheral.name?.range(of: "D07") != nil || peripheral.name?.range(of: "S7 NO.1") != nil || peripheral.name?.range(of: "G7 Pro Max Gameboy") != nil {  
1600 -// if peripheral.name?.range(of: "KV-S10f44efd8deb8b") != nil {  
1601 -// if peripheral.name?.range(of: "CHiQ Compass_50c0f0668129") != nil {  
1602 - if peripheral.name?.range(of: "CHiQ") != nil {  
1603 - peripheralDic[peripheral.identifier.uuidString] = peripheral  
1604 - // print(peripheral.name)key String "kCBAdvDataServiceData"  
1605 -  
1606 -  
1607 - if let data = advertisementData["kCBAdvDataManufacturerData"] as? Data {  
1608 - var mac = data.hexToString(":")  
1609 - mac = mac.substring(fromIndex: mac.length-17)  
1610 - deviceArray.append(ScanDevice(peripheral, mac: mac))  
1611 - for delegate in delegateList {  
1612 - delegate.didDiscover(devices: deviceArray)  
1613 - }  
1614 - } else {  
1615 - if let json = advertisementData["kCBAdvDataServiceData"] {  
1616 - if let dic = json as? Dictionary<CBUUID, Data> {  
1617 - if let data = dic.values.first {  
1618 - var mac = data.hexToString(":")  
1619 - mac = mac.substring(fromIndex: mac.length-17)  
1620 - deviceArray.append(ScanDevice(peripheral, mac: mac))  
1621 - for delegate in delegateList {  
1622 - delegate.didDiscover(devices: deviceArray)  
1623 - }  
1624 - }  
1625 - }  
1626 - }else {// 当无值时直接给个值跑通调试  
1627 - var mac = "111"  
1628 - deviceArray.append(ScanDevice(peripheral, mac: mac))  
1629 - for delegate in delegateList {  
1630 - delegate.didDiscover(devices: deviceArray)  
1631 - }  
1632 - }  
1633 - }  
1634 - }  
1635 - }  
1636 -  
1637 } 1872 }
1638 1873
1639 1874