From: liangzhenying <867174124@qq.com> Date: Sat, 16 Mar 2024 10:32:33 +0000 (+0800) Subject: 增加蓝牙设备断开后重连 X-Git-Tag: 阿里鉴权~17 X-Git-Url: http://git.snicker.com.cn/?a=commitdiff_plain;h=18f2a464206db5fb42f8429b0cb69777636d45b5;p=mirrors%2FMouseSdk-MacOS.git 增加蓝牙设备断开后重连 --- diff --git a/MouseSdk/AiMouseSdk/AiMouse.h b/MouseSdk/AiMouseSdk/AiMouse.h index 0ae61f6..3ba2ace 100644 --- a/MouseSdk/AiMouseSdk/AiMouse.h +++ b/MouseSdk/AiMouseSdk/AiMouse.h @@ -20,7 +20,7 @@ NS_ASSUME_NONNULL_BEGIN - (void)aiMouseSendAuthData:(NSData *)data; /// 鼠标按键指令回调 -/// - Parameter data: 数据。AI键0x42单击,0x25按下,0x26抬起 ; 录音键0x51单击,0x32按下。0x31(未知),其他未知 +/// - Parameter data: 数据。AI键0x42 单击 0x25 按下(开始录音) 0x26抬起(结束录音); 语音键0x31开始录音,0x32结束录音;OCR 按键 单击 0x41;其他未定义 - (void)aiMouseSendCmdData:(NSData *)data; /// 录音回调 diff --git a/MouseSdk/AiMouseSdk/AiMouse.m b/MouseSdk/AiMouseSdk/AiMouse.m index 7c8d2af..ee56d77 100644 --- a/MouseSdk/AiMouseSdk/AiMouse.m +++ b/MouseSdk/AiMouseSdk/AiMouse.m @@ -70,6 +70,9 @@ return _audioManager; } #pragma mark - pub Api +- (void)initSDK{ + +} //开始鉴权 - (void)startAuthentication{ [self.authManager login]; @@ -115,7 +118,7 @@ } } - (void)showLog:(NSString *)log{ - NSLog(@"[sdk]%@",log); +// NSLog(@"[sdk]%@",log); } - (void)sendTestLP{ diff --git a/MouseSdk/MouseSdk.xcodeproj/project.pbxproj b/MouseSdk/MouseSdk.xcodeproj/project.pbxproj index 8a33ded..e1c27a6 100644 --- a/MouseSdk/MouseSdk.xcodeproj/project.pbxproj +++ b/MouseSdk/MouseSdk.xcodeproj/project.pbxproj @@ -17,7 +17,6 @@ 18BF1DE42B81AB8000B8D90F /* MouseSdkTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 18BF1DE32B81AB8000B8D90F /* MouseSdkTests.m */; }; 18BF1DEE2B81AB8000B8D90F /* MouseSdkUITests.m in Sources */ = {isa = PBXBuildFile; fileRef = 18BF1DED2B81AB8000B8D90F /* MouseSdkUITests.m */; }; 18BF1DF02B81AB8000B8D90F /* MouseSdkUITestsLaunchTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 18BF1DEF2B81AB8000B8D90F /* MouseSdkUITestsLaunchTests.m */; }; - 18BF1E052B81E18800B8D90F /* ConnectKitVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18BF1E042B81E18800B8D90F /* ConnectKitVC.swift */; }; 18BF1E222B83066200B8D90F /* BleManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 18BF1E212B83066200B8D90F /* BleManager.m */; }; 18BF1E762B832D2E00B8D90F /* ScanVC.m in Sources */ = {isa = PBXBuildFile; fileRef = 18BF1E752B832D2E00B8D90F /* ScanVC.m */; }; 18BF1E8A2B8362D300B8D90F /* AiMouseSdk.h in Headers */ = {isa = PBXBuildFile; fileRef = 18BF1E892B8362D300B8D90F /* AiMouseSdk.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -246,7 +245,6 @@ 18BF1DED2B81AB8000B8D90F /* MouseSdkUITests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MouseSdkUITests.m; sourceTree = ""; }; 18BF1DEF2B81AB8000B8D90F /* MouseSdkUITestsLaunchTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MouseSdkUITestsLaunchTests.m; sourceTree = ""; }; 18BF1E032B81E18700B8D90F /* MouseSdk-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "MouseSdk-Bridging-Header.h"; sourceTree = ""; }; - 18BF1E042B81E18800B8D90F /* ConnectKitVC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConnectKitVC.swift; sourceTree = ""; }; 18BF1E202B83066200B8D90F /* BleManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BleManager.h; sourceTree = ""; }; 18BF1E212B83066200B8D90F /* BleManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BleManager.m; sourceTree = ""; }; 18BF1E742B832D2E00B8D90F /* ScanVC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ScanVC.h; sourceTree = ""; }; @@ -503,7 +501,6 @@ 18F3235C2B8ED78300CABA2E /* ScanCell.m */, 18F328D32B98569D00CABA2E /* Config.h */, 18F328D42B98569D00CABA2E /* Config.m */, - 18BF1E042B81E18800B8D90F /* ConnectKitVC.swift */, 18BF1DD32B81AB7F00B8D90F /* Assets.xcassets */, 18BF1DD52B81AB7F00B8D90F /* Main.storyboard */, 18BF1DD82B81AB7F00B8D90F /* main.m */, @@ -1143,7 +1140,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 18BF1E052B81E18800B8D90F /* ConnectKitVC.swift in Sources */, 18F3235D2B8ED78300CABA2E /* ScanCell.m in Sources */, 18BF1DD22B81AB7C00B8D90F /* ViewController.m in Sources */, 18BF1DD92B81AB7F00B8D90F /* main.m in Sources */, @@ -1404,7 +1400,6 @@ 18BF1DF72B81AB8000B8D90F /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; @@ -1421,7 +1416,6 @@ 18BF1DF82B81AB8000B8D90F /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; @@ -1438,7 +1432,6 @@ 18BF1DFA2B81AB8000B8D90F /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; @@ -1453,7 +1446,6 @@ 18BF1DFB2B81AB8000B8D90F /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; diff --git a/MouseSdk/MouseSdk.xcworkspace/xcuserdata/apple.xcuserdatad/UserInterfaceState.xcuserstate b/MouseSdk/MouseSdk.xcworkspace/xcuserdata/apple.xcuserdatad/UserInterfaceState.xcuserstate index 2a8aa06..9bae047 100644 Binary files a/MouseSdk/MouseSdk.xcworkspace/xcuserdata/apple.xcuserdatad/UserInterfaceState.xcuserstate and b/MouseSdk/MouseSdk.xcworkspace/xcuserdata/apple.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/MouseSdk/MouseSdk/BleManager.h b/MouseSdk/MouseSdk/BleManager.h index f7b6b75..6e3749e 100644 --- a/MouseSdk/MouseSdk/BleManager.h +++ b/MouseSdk/MouseSdk/BleManager.h @@ -7,22 +7,31 @@ #import #import + +#define kDidConnectBleNotification @"kDidConnectBleNotification" +#define kDidDisconnectBleNotification @"kDidDisconnectBleNotification" + NS_ASSUME_NONNULL_BEGIN @interface BleManager : NSObject -@property (nonatomic,strong)void (^discoverDevice)(CBPeripheral *peripheral,NSDictionary *advertisementData) ; -@property (nonatomic,strong)void (^didConnectDevice)(CBPeripheral *peripheral); -@property (nonatomic,strong)void (^authCallBack)(BOOL isSuccess); +@property (nonatomic,strong)void (^discoverDevice)(CBPeripheral *peripheral) ;/// 扫描到设备 +@property (nonatomic,strong)void (^didConnectDevice)(CBPeripheral *peripheral);/// 连接成功 +@property (nonatomic,strong)void (^authCallBack)(BOOL isSuccess);/// 鉴权回调 -+(id)shared; ++(BleManager *)shared; +/// 扫描 - (void)startScanDevice; +/// 停止扫描 - (void)stopScanDevice; +/// 连接设备 +/// - Parameter peripheral: 蓝牙设备 - (void)connectPeripheral:(CBPeripheral *)peripheral; -- (void)startAuth; +/// 开始鉴权 +- (void)startAuthentication; @end NS_ASSUME_NONNULL_END diff --git a/MouseSdk/MouseSdk/BleManager.m b/MouseSdk/MouseSdk/BleManager.m index 7a5269c..e33a4f4 100644 --- a/MouseSdk/MouseSdk/BleManager.m +++ b/MouseSdk/MouseSdk/BleManager.m @@ -5,8 +5,6 @@ // Created by incar on 2024/1/30. // - - #import "BleManager.h" #import #import "Config.h" @@ -19,19 +17,16 @@ //#define kAuthUUID @"0783B73E-8535-B5A0-7140-A304D2194CB7" #define kAuthUUID @"0783B03E-8535-B5A0-7140-A304D2194CB7" - - @interface BleManager () -@property (nonatomic,strong) NSMutableArray *scanArray; -@property(nonatomic, strong) CBCentralManager *centralManager; -@property(nonatomic, strong) CBPeripheral *connectPeripheral; -@property(nonatomic, strong) CBCharacteristic *authCha; -@property(nonatomic, strong) CBCharacteristic *aiCha; -@property (nonatomic,strong)NSMutableData *recordData; +@property(nonatomic, strong) CBCentralManager *centralManager;///蓝牙管理 +@property(nonatomic, strong) CBPeripheral *connectPeripheral;//连接的设备 +@property(nonatomic, strong) CBCharacteristic *authCha;//鉴权特征 +@property(nonatomic, strong) CBCharacteristic *aiCha;//ai特征 +@property (nonatomic,strong) NSMutableData *recordData;//录音的数据 @end @implementation BleManager -+(id)shared{ ++(BleManager *)shared{ static BleManager *manager = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ @@ -40,13 +35,6 @@ return manager; } --(NSMutableArray *)scanArray{ - if (_scanArray == nil) { - _scanArray = [[NSMutableArray alloc] init]; - } - return _scanArray; -} - - (instancetype)init{ self = [super init]; if (self) { @@ -58,8 +46,8 @@ #pragma mark - CBCentralManagerDelegate - (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central { + [self showLog:[NSString stringWithFormat:@"设备状态 = %@",@(central.state)]]; switch (central.state) { - case CBManagerStateUnknown: break; @@ -76,47 +64,46 @@ break; case CBManagerStatePoweredOn: -// [self startScanDevice]; + [self autoConnectDevice]; break; } } - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{ - if ([self.scanArray containsObject:peripheral]){ - return; - } - if(peripheral.name == nil){ - return; - } - [self showLog:peripheral.name]; - [self.scanArray insertObject:peripheral atIndex:0]; +// [self showLog:[NSString stringWithFormat:@"扫描到设备 = %@, data = %@",peripheral,advertisementData]]; if(self.discoverDevice){ - self.discoverDevice(peripheral, advertisementData); + self.discoverDevice(peripheral); } } - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ + [self showLog:[NSString stringWithFormat:@"连接成功 name = %@",peripheral.name]]; if(self.didConnectDevice){ self.didConnectDevice(peripheral); } - - self.connectPeripheral = peripheral; peripheral.delegate = self; [peripheral discoverServices:nil]; + + [[NSNotificationCenter defaultCenter] postNotificationName:kDidConnectBleNotification object:nil]; } -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ [self showLog:[NSString stringWithFormat:@"断开连接。。。%@",error.description]]; + [[NSNotificationCenter defaultCenter] postNotificationName:kDidDisconnectBleNotification object:nil]; + + [self autoConnectDevice]; } - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{ [self showLog:[NSString stringWithFormat:@"连接失败。。。%@",error.description]]; } #pragma mark - CBPeripheralDelegate +//发现服务 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { for (CBService *service in peripheral.services){ [peripheral discoverCharacteristics:nil forService:service]; } } +// 发现特征 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { for (CBCharacteristic *characteristic in service.characteristics){ if ([characteristic.UUID.UUIDString isEqualToString:kAuthUUID]) { @@ -129,7 +116,7 @@ } } } - +//收到蓝牙数据 - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { NSData *data = characteristic.value; [self showLog:[NSString stringWithFormat:@"[receive] %@",[AiTools dataToHexString:data]]]; @@ -158,8 +145,8 @@ [self showLog:[NSString stringWithFormat:@"[send] %@",[AiTools dataToHexString:data]]]; [self.connectPeripheral writeValue:data forCharacteristic:self.authCha type:CBCharacteristicWriteWithoutResponse]; } -/// 指令回调 -/// - Parameter data: 数据 +/// 鼠标按键指令回调 +/// - Parameter data: 数据。AI键0x42 单击 0x25 按下(开始录音) 0x26抬起(结束录音); 语音键0x31开始录音,0x32结束录音;OCR 按键 单击 0x41;其他未定义 - (void)aiMouseSendCmdData:(NSData *)data{ NSString *cmd = [[AiTools dataToHexString:data] lowercaseString]; if([cmd hasSuffix:@"31"]){ @@ -178,6 +165,9 @@ [self showLog:@"AI键结束录音"]; [self finishRecored:self.recordData]; } + else{ + [self showLog:@"未定义指令!!!!!!!!"]; + } } /// 录音回调 /// - Parameter data: pcm格式语音数据 @@ -188,7 +178,6 @@ #pragma mark - public /// 连接设备 - (void)startScanDevice{ - [self.scanArray removeAllObjects]; [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : [NSNumber numberWithBool:NO]}]; } @@ -199,19 +188,36 @@ /// 连接设备 - (void)connectPeripheral:(CBPeripheral *)peripheral{ + self.connectPeripheral = peripheral; [self.centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : [NSNumber numberWithBool:YES]}]; } /// 开始鉴权 -- (void)startAuth{ +- (void)startAuthentication{ [[AiMouse shared] startAuthentication]; } #pragma mark - other +//自动连接,获取已配对的蓝牙,取第一个连接 +- (void)autoConnectDevice{ + //如果是已连接或者正在连接,则不再重连 + if (self.connectPeripheral && (self.connectPeripheral.state == CBPeripheralStateConnected || self.connectPeripheral.state == CBPeripheralStateConnecting)) { + return; + } + NSArray *devices = [self.centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]]]; + for (CBPeripheral *peripheral in devices) { + [self showLog:[NSString stringWithFormat:@"匹配过的设备%@",peripheral.name]]; + [self connectPeripheral:peripheral]; + break; + } + // 10s自动重连 + [self performSelector:@selector(autoConnectDevice) withObject:nil afterDelay:10]; +} - (void)showLog:(NSString *)log{ NSLog(@"%@",log); } +//将录音数据保存 - (void)finishRecored:(NSData *)data{ NSString *doc = NSTemporaryDirectory(); NSString *fullPath = [NSString stringWithFormat:@"%@1.pcm",doc]; diff --git a/MouseSdk/MouseSdk/ConnectKitVC.swift b/MouseSdk/MouseSdk/ConnectKitVC.swift deleted file mode 100644 index 40290b7..0000000 --- a/MouseSdk/MouseSdk/ConnectKitVC.swift +++ /dev/null @@ -1,102 +0,0 @@ -// -// ConnectKitVC.swift -// AliIotSdkDemo -// -// Created by incar on 2024/2/1. -// - -import Cocoa -//import AliIotConnectKit - -class ConnectKitVC: NSViewController { - override func viewDidLoad() { - super.viewDidLoad() - self.title = "AliIotConnectKit" - -// //先设置代理 -// AliConnectMananger_C.shared.iotStateDelegate = self -// AliConnectMananger_C.shared.bleSendDataDelegate = self -// AliConnectMananger_C.shared.appVersion = "1.0"//一定要设置app版本 -// AliCloudIotLogManager_C.shared.switchLogStatus(true) - -// if true{ -// let btn = UIButton(type: .custom) -// btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100) -// btn.backgroundColor = .orange; -// btn.setTitle("checkFGS", for: .normal) -// btn.addTarget(self, action: #selector(checkFGSStatus), for: .touchUpInside) -// view.addSubview(btn) -// } -// if true{ -// let btn = UIButton(type: .custom) -// btn.frame = CGRect(x: 100, y: 300, width: 100, height: 100) -// btn.backgroundColor = .orange; -// btn.setTitle("connectLp", for: .normal) -// btn.addTarget(self, action: #selector(connectLp), for: .touchUpInside) -// view.addSubview(btn) -// } - } - -// @objc func checkFGSStatus() { -// AliConnectMananger_C.shared.checkFgsState { isSuccess, data in -// if isSuccess { -// debugPrint("已有三元组数据") -// }else { -// debugPrint("没有,错误日志 : \(String(describing: data["msg"]))") -// } -// } -// } -// -// @objc func connectLp() { -// //swift-Lp连接 -// AliConnectMananger_C.shared.startConnectLpState { isSuccess, data in -// if isSuccess { -// debugPrint("LP连接成功") -// }else { -// debugPrint("LP连接失败,错误日志 : \(String(describing: data["msg"]))") -// } -// } -// } -// -// //Lp断开连接 -// @objc func disconnectLp() { -// AliConnectMananger_C.shared.disConnect(result: { (_ isSuccess:Bool, _ data:[String:Any]) in -// -// }) -// } -// -// //App端接收到蓝牙信息,请调用以下接口 -// func onBleDataReceived(data: Data) { -//// AliConnectMananger_C.shared.bleDataReceived(data: data) -// } - -} - -//extension ConnectKitVC: BleNeedSendDataDelegate_C { -// func sendBleData(data: Data) { -// print(data) -// debugPrint("在此处将数据发送给已连接的蓝牙") -// } -//} -// -//extension ConnectKitVC:IotStateDelatege_C{ -// func onIotConnected() { -// -// } -// -// func onIotConnectFailed() { -// -// } -// -// func onIotDisconeted() { -// -// } -// -// func onIotConnecting() { -// -// } -// -// func onLog(log: String) { -// -// } -//} diff --git a/MouseSdk/MouseSdk/ScanCell.h b/MouseSdk/MouseSdk/ScanCell.h index bb8a265..6bf06ee 100644 --- a/MouseSdk/MouseSdk/ScanCell.h +++ b/MouseSdk/MouseSdk/ScanCell.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN @interface ScanCell : NSTableCellView @property(nonatomic,strong)CBPeripheral *peripheral; -@property(nonatomic,strong)void (^connecCallBack)(CBPeripheral *peripheral); +@property(nonatomic,strong)void (^connecBtnActionCallBack)(CBPeripheral *peripheral); @end NS_ASSUME_NONNULL_END diff --git a/MouseSdk/MouseSdk/ScanCell.m b/MouseSdk/MouseSdk/ScanCell.m index a0bf16f..dae4419 100644 --- a/MouseSdk/MouseSdk/ScanCell.m +++ b/MouseSdk/MouseSdk/ScanCell.m @@ -42,8 +42,6 @@ btn.state = 1; [self addSubview:btn]; self.connectBtn = btn; - - } -(void)setPeripheral:(CBPeripheral *)peripheral{ @@ -56,8 +54,8 @@ } - (void)connetAction{ - if (self.connecCallBack) { - self.connecCallBack(self.peripheral); + if (self.connecBtnActionCallBack) { + self.connecBtnActionCallBack(self.peripheral); } } @end diff --git a/MouseSdk/MouseSdk/ScanVC.m b/MouseSdk/MouseSdk/ScanVC.m index 61432bd..75ad42d 100644 --- a/MouseSdk/MouseSdk/ScanVC.m +++ b/MouseSdk/MouseSdk/ScanVC.m @@ -24,15 +24,14 @@ - (void)viewDidLoad { [super viewDidLoad]; // Do view setup here. - self.title = @"扫描设备"; - [self tableViewSetting]; - [self setupBle]; + [self setupUI]; + [self setupBleManger]; } - (void)loadView{ self.view = [[NSView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; } -- (void)tableViewSetting{ +- (void)setupUI{ CALayer *viewLayer = [CALayer layer]; NSView *backgroundView= [[NSView alloc]init]; [backgroundView setWantsLayer:YES]; @@ -67,11 +66,11 @@ self.tableView.gridStyleMask = NSTableViewSolidHorizontalGridLineMask; } -- (void)setupBle{ +- (void)setupBleManger{ BleManager *manager = [BleManager shared]; __weak typeof(self) weakSelf= self; __weak typeof(BleManager) *weakManager = manager; - manager.discoverDevice = ^(CBPeripheral *peripheral,NSDictionary *advertisementData){ + manager.discoverDevice = ^(CBPeripheral *peripheral){ if ([weakSelf.scanArray containsObject:peripheral]){ return; } @@ -80,24 +79,29 @@ } [weakSelf.scanArray addObject:peripheral]; [weakSelf.tableView reloadData]; -// NSLog(@"%@",peripheral.name); -// iMouse Ublue_BT895x -// if([peripheral.name isEqualToString:@"iMouse"]){ -// [weakManager connectPeripheral:peripheral]; -// [weakManager stopScanDevice]; -// } }; manager.didConnectDevice = ^(CBPeripheral * _Nonnull peripheral) { - NSLog(@"连接成功"); - [weakManager stopScanDevice]; - [weakSelf dismissViewController:weakSelf]; + [weakSelf connectSuccess]; }; [manager startScanDevice]; } -- (void)connectDevice:(CBPeripheral *)peripheral{ +- (void)tapDevice:(CBPeripheral *)peripheral{ [[BleManager shared] connectPeripheral:peripheral]; } + +- (void)connectSuccess{ + [[BleManager shared] stopScanDevice]; + dispatch_async(dispatch_get_main_queue(), ^{ + NSAlert *alert = [NSAlert new]; + [alert addButtonWithTitle:@"确定"]; + [alert setMessageText:@"连接成功"]; + [alert setAlertStyle:NSAlertStyleInformational]; + [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSModalResponse returnCode) { + [self dismissViewController:self]; + }]; + }); +} #pragma mark - NSTableViewDelegate,NSTableViewDataSource -(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{ return self.scanArray.count; @@ -118,8 +122,8 @@ ScanCell *cell = [[ScanCell alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 44)]; cell.peripheral = self.scanArray[row]; __weak typeof(self) weakSelf = self; - cell.connecCallBack = ^(CBPeripheral * _Nonnull peripheral) { - [weakSelf connectDevice:peripheral]; + cell.connecBtnActionCallBack = ^(CBPeripheral * _Nonnull peripheral) { + [weakSelf tapDevice:peripheral]; }; return cell; } diff --git a/MouseSdk/MouseSdk/ViewController.m b/MouseSdk/MouseSdk/ViewController.m index 912680d..06e4dd9 100644 --- a/MouseSdk/MouseSdk/ViewController.m +++ b/MouseSdk/MouseSdk/ViewController.m @@ -12,19 +12,32 @@ @interface ViewController () +@property(nonatomic,strong)NSTextField *connectLabel; +@property(nonatomic,strong)NSTextField *autoLabel; @end @implementation ViewController - - - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. + [self setupUI]; + [self setupNotification]; + [self setupBleManger]; +} + +- (void)setRepresentedObject:(id)representedObject { + [super setRepresentedObject:representedObject]; + + // Update the view, if already loaded. +} + +- (void)setupUI{ self.title = @"AI SDK"; + { - NSButton *btn = [[NSButton alloc]initWithFrame:NSMakeRect(100, self.view.bounds.size.height - 100, 100, 45)]; + NSButton *btn = [[NSButton alloc]initWithFrame:NSMakeRect(100, self.view.bounds.size.height - 120, 100, 45)]; btn.bordered = true; btn.title = @"扫描"; [btn setTarget:self]; @@ -33,7 +46,7 @@ [self.view addSubview:btn]; } { - NSButton *btn = [[NSButton alloc]initWithFrame:NSMakeRect(100, self.view.bounds.size.height - 150, 100, 45)]; + NSButton *btn = [[NSButton alloc]initWithFrame:NSMakeRect(100, self.view.bounds.size.height - 200, 100, 45)]; btn.bordered = true; btn.title = @"鉴权"; [btn setTarget:self]; @@ -41,56 +54,64 @@ btn.state = 1; [self.view addSubview:btn]; } - [self setupBleManger]; -} - - -- (void)setRepresentedObject:(id)representedObject { - [super setRepresentedObject:representedObject]; - - // Update the view, if already loaded. -} - -- (void)scanAction{ - ScanVC *vc = [[ScanVC alloc] initWithNibName:nil bundle:nil]; - [self presentViewControllerAsModalWindow:vc]; -// [[BleManager shared] startScanDevice]; + { + NSTextField *label = [[NSTextField alloc] initWithFrame:CGRectMake(230, self.view.bounds.size.height - 120, 200, 35)]; + label.editable = NO; + label.bordered = NO; + label.stringValue = @"连接状态:未连接"; + label.backgroundColor = NSColor.clearColor; + self.connectLabel = label; + [self.view addSubview:label]; + } + { + NSTextField *label = [[NSTextField alloc] initWithFrame:CGRectMake(230, self.view.bounds.size.height - 200, 200, 35)]; + label.editable = NO; + label.bordered = NO; + label.stringValue = @"鉴权状态:--"; + label.backgroundColor = NSColor.clearColor; + self.autoLabel = label; + [self.view addSubview:label]; + } } - (void)setupBleManger{ BleManager *manager = [BleManager shared]; - __weak typeof(BleManager) *weakManager = manager; __weak typeof(self) ws = self; - manager.discoverDevice = ^(CBPeripheral *peripheral,NSDictionary *advertisementData){ - if(peripheral.name.length == 0){ - return; - } -// NSLog(@"%@",peripheral.name); -// iMouse Ublue_BT895x - if([peripheral.name isEqualToString:@"iMouse"]){ - [weakManager connectPeripheral:peripheral]; - [weakManager stopScanDevice]; - } - }; - manager.didConnectDevice = ^(CBPeripheral * _Nonnull peripheral) { - NSLog(@"连接成功"); - }; manager.authCallBack = ^(BOOL isSuccess) { [ws showAuthResult:isSuccess]; }; } +- (void)scanAction{ + ScanVC *vc = [[ScanVC alloc] initWithNibName:nil bundle:nil]; + [self presentViewControllerAsModalWindow:vc]; +} + - (void)checkAuth{ - [[BleManager shared] startAuth]; + [[BleManager shared] startAuthentication]; } - (void)showAuthResult:(BOOL)isSuccess{ dispatch_async(dispatch_get_main_queue(), ^{ - NSAlert *alert = [NSAlert new]; - [alert addButtonWithTitle:@"确定"]; - [alert setMessageText:isSuccess?@"鉴权成功":@"鉴权失败"]; - [alert setAlertStyle:NSAlertStyleInformational]; - [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSModalResponse returnCode) { - }]; + self.autoLabel.stringValue = isSuccess?@"鉴权结果:鉴权成功":@"鉴权结果:鉴权失败"; +// NSAlert *alert = [NSAlert new]; +// [alert addButtonWithTitle:@"确定"]; +// [alert setMessageText:isSuccess?@"鉴权成功":@"鉴权失败"]; +// [alert setAlertStyle:NSAlertStyleInformational]; +// [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSModalResponse returnCode) { +// }]; }); } + +#pragma mark - notication +- (void)setupNotification{ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bleDidConnect:) name:kDidConnectBleNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bleDidDisconnect:) name:kDidDisconnectBleNotification object:nil]; +} + +- (void)bleDidConnect:(NSNotification *)notification{ + self.connectLabel.stringValue = @"连接状态:已连接"; +} +- (void)bleDidDisconnect:(NSNotification *)notification{ + self.connectLabel.stringValue = @"连接状态:未连接"; +} @end