免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2704 | 回复: 0
打印 上一主题 下一主题

[iOS] iOS BLE 4.0 实现搜索周边蓝牙设备并显示其信号强度(RSSI) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-06-30 09:47 |只看该作者 |倒序浏览
iOS BLE 4.0 实现搜索周边蓝牙设备并显示其信号强度(RSSI)

源码:https://git.oschina.net/laughingzhong/MyBluetoothDemo.git

[Objective-C]代码
  1. #import "ViewController.h"
  2. #import "TableViewCell.h"
  3. #import "PeripheralViewController.h"

  4. #define ScanTimeInterval 1.0

  5. @interface ViewController ()

  6. @property (nonatomic,strong) NSMutableArray *devicesArray;
  7. @property (nonatomic,strong) CBCentralManager *centralManager;
  8. @property (nonatomic,strong) CBPeripheral *selectedPeripheral;
  9. @property (nonatomic,strong) NSTimer *scanTimer;

  10. @end

  11. @implementation ViewController

  12. - (void)dealloc
  13. {
  14.     _devicesArray = nil;
  15.     _centralManager = nil;
  16.     _selectedPeripheral = nil;
  17.     _scanTimer = nil;
  18. }

  19. - (void)viewDidLoad {
  20.     [super viewDidLoad];
  21.     // Do any additional setup after loading the view, typically from a nib.
  22.     _devicesArray = [[NSMutableArray alloc] initWithCapacity:1];
  23.      
  24.     [self initWithLeftBarButton];
  25.     [self initWithRightBarButton];
  26.     [self initWithTableView];
  27.     [self initWithCBCentralManager];
  28. }

  29. #pragma mark - UI
  30. - (void)initWithLeftBarButton
  31. {
  32.     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  33.     [button setFrame:CGRectMake(0.0, 0.0, 60.0, 40.0)];
  34.     [button setBackgroundColor:[UIColor clearColor]];
  35.     [button setTitle:@"搜索" forState:UIControlStateNormal];
  36.     [button addTarget:self action:@selector(startScanPeripherals) forControlEvents:UIControlEventTouchUpInside];
  37.      
  38.     UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
  39.     [self.navigationItem setLeftBarButtonItem:item];
  40. }

  41. - (void)initWithRightBarButton
  42. {
  43.     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  44.     [button setFrame:CGRectMake(0.0, 0.0, 60.0, 40.0)];
  45.     [button setBackgroundColor:[UIColor clearColor]];
  46.     [button setTitle:@"停止" forState:UIControlStateNormal];
  47.     [button addTarget:self action:@selector(stopScan) forControlEvents:UIControlEventTouchUpInside];
  48.      
  49.     UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
  50.     [self.navigationItem setRightBarButtonItem:item];
  51. }

  52. - (void)initWithTableView
  53. {
  54.     if (!_tableView) {
  55.         _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
  56.         [_tableView setDelegate:self];
  57.         [_tableView setDataSource:self];
  58.         [_tableView setBackgroundColor:[UIColor clearColor]];
  59.         [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
  60.         [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
  61.     }
  62.     if (_tableView && _tableView.superview != self.view) {
  63.         [self.view addSubview:_tableView];
  64.          
  65.         NSArray *h = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_tableView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableView)];
  66.         NSArray *v = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_tableView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableView)];
  67.         [self.view addConstraints:h];
  68.         [self.view addConstraints:v];
  69.     }
  70. }

  71. #pragma mark - ScanTimer
  72. - (void)startScanPeripherals
  73. {
  74.     if (!_scanTimer) {
  75.         _scanTimer = [NSTimer timerWithTimeInterval:ScanTimeInterval target:self selector:@selector(scanForPeripherals) userInfo:nil repeats:YES];
  76.         [[NSRunLoop mainRunLoop] addTimer:_scanTimer forMode:NSDefaultRunLoopMode];
  77.     }
  78.     if (_scanTimer && !_scanTimer.valid) {
  79.         [_scanTimer fire];
  80.     }
  81. }

  82. - (void)stopScan
  83. {
  84.     if (_scanTimer && _scanTimer.valid) {
  85.         [_scanTimer invalidate];
  86.         _scanTimer = nil;
  87.     }
  88.     [_centralManager stopScan];
  89. }

  90. #pragma mark - CBCentralManager
  91. - (void)initWithCBCentralManager
  92. {
  93.     if (!_centralManager) {
  94.         dispatch_queue_t queue = dispatch_get_main_queue();
  95.         _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:queue options:@{CBCentralManagerOptionShowPowerAlertKey:@YES}];
  96.         [_centralManager setDelegate:self];
  97.     }
  98. }

  99. - (void)scanForPeripherals
  100. {
  101.     if (_centralManager.state == CBCentralManagerStateUnsupported) {//设备不支持蓝牙
  102.          
  103.     }else {//设备支持蓝牙连接
  104.         if (_centralManager.state == CBCentralManagerStatePoweredOn) {//蓝牙开启状态
  105.             //[_centralManager stopScan];
  106.             [_centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:[NSNumber numberWithBool:NO]}];
  107.         }
  108.     }
  109. }

  110. - (void)connectPeripheral
  111. {
  112.      
  113. }

  114. - (void)didReceiveMemoryWarning {
  115.     [super didReceiveMemoryWarning];
  116.     // Dispose of any resources that can be recreated.
  117. }

  118. #pragma mark - UITableView Datasource && Delegate
  119. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  120. {
  121.     return 1;
  122. }

  123. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  124. {
  125.     return _devicesArray.count;
  126. }

  127. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  128. {
  129.     if (section == 0) {
  130.         return @"Peripherals Nearby";
  131.     }else {
  132.         return nil;
  133.     }
  134. }

  135. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  136. {
  137.     return 50.0;
  138. }

  139. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  140. {
  141.     static NSString *cellID = @"cellID";
  142.     TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
  143.     if (!cell) {
  144.         cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
  145.     }
  146.     NearbyPeripheralInfo *info = [_devicesArray objectAtIndex:indexPath.row];
  147.     [cell setPeripheral:info];
  148.     return cell;
  149. }

  150. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  151. {
  152.     if (_centralManager.state == CBCentralManagerStateUnsupported) {//设备不支持蓝牙
  153.          
  154.     }else {//设备支持蓝牙连接
  155.         if (_centralManager.state == CBCentralManagerStatePoweredOn) {//蓝牙开启状态
  156.             //连接设备
  157.             NearbyPeripheralInfo *info = [_devicesArray objectAtIndex:indexPath.row];
  158.             [_centralManager connectPeripheral:info.peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey:@YES,CBConnectPeripheralOptionNotifyOnNotificationKey:@YES,CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES}];
  159.         }
  160.     }
  161. }

  162. #pragma mark - CBCentralManager Delegate
  163. - (void)centralManagerDidUpdateState:(CBCentralManager *)central
  164. {
  165.     switch (central.state) {
  166.         case CBCentralManagerStatePoweredOff:
  167.             NSLog(@"CBCentralManagerStatePoweredOff");
  168.             break;
  169.         case CBCentralManagerStatePoweredOn:
  170.             NSLog(@"CBCentralManagerStatePoweredOn");
  171.             break;
  172.         case CBCentralManagerStateResetting:
  173.             NSLog(@"CBCentralManagerStateResetting");
  174.             break;
  175.         case CBCentralManagerStateUnauthorized:
  176.             NSLog(@"CBCentralManagerStateUnauthorized");
  177.             break;
  178.         case CBCentralManagerStateUnknown:
  179.             NSLog(@"CBCentralManagerStateUnknown");
  180.             break;
  181.         case CBCentralManagerStateUnsupported:
  182.             NSLog(@"CBCentralManagerStateUnsupported");
  183.             break;
  184.             
  185.         default:
  186.             break;
  187.     }
  188. }
  189. //发现蓝牙设备
  190. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
  191. {
  192. //    NSLog(@"\nperipheral is :\n%@\nadvertisementData is :\n%@\nRSSI is :%d",peripheral,advertisementData,[RSSI intValue]);
  193.      
  194.      
  195.     BOOL isExist = NO;
  196.     NearbyPeripheralInfo *info = [[NearbyPeripheralInfo alloc] init];
  197.     info.peripheral = peripheral;
  198.     info.advertisementData = advertisementData;
  199.     info.RSSI = RSSI;
  200.      
  201.     if (_devicesArray.count == 0) {
  202.         [_devicesArray addObject:info];
  203.         NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
  204.         [_tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
  205.     }else {
  206.         for (int i = 0;i < _devicesArray.count;i++) {
  207.             NearbyPeripheralInfo *originInfo = [_devicesArray objectAtIndex:i];
  208.             CBPeripheral *per = originInfo.peripheral;
  209.             if ([peripheral.identifier.UUIDString isEqualToString:per.identifier.UUIDString]) {
  210.                 isExist = YES;
  211.                 [_devicesArray replaceObjectAtIndex:i withObject:info];
  212.                 [_tableView reloadData];
  213.             }
  214.         }
  215.         if (!isExist) {
  216.             [_devicesArray addObject:info];
  217.             NSIndexPath *path = [NSIndexPath indexPathForRow:(_devicesArray.count - 1) inSection:0];
  218.             [_tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
  219.         }
  220.     }
  221. }
  222. //连接蓝牙设备成功
  223. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
  224. {
  225.     NSLog(@"%s",__FUNCTION__);
  226.     [self stopScan];
  227.     _selectedPeripheral = peripheral;
  228.     PeripheralViewController *viewController = [[PeripheralViewController alloc] initWithNibName:nil bundle:nil];
  229.     viewController.currentPeripheral = _selectedPeripheral;
  230.     [self.navigationController pushViewController:viewController animated:YES];
  231. }
  232. //连接蓝牙设备失败
  233. - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  234. {
  235.     NSLog(@"%s",__FUNCTION__);
  236. }
  237. //断开连接
  238. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  239. {
  240.     NSLog(@"%s",__FUNCTION__);
  241. }
  242. @end
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP