Advertisement
prem12390

corebluetooth

Oct 25th, 2012
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.38 KB | None | 0 0
  1.  
  2.  
  3. #import "MeBleFirstViewController.h"
  4.  
  5. @interface MeBleFirstViewController ()
  6.  
  7. @end
  8.  
  9. @implementation MeBleFirstViewController
  10. {
  11. PeripheralManager *peripheralManager;
  12. }
  13. @synthesize MeBleUISearch;
  14. @synthesize deviceTable;
  15. @synthesize alert;
  16. @synthesize array;
  17. @synthesize MeBle;
  18. @synthesize device;
  19. @synthesize alertButton;
  20. @synthesize batteryButton;
  21. @synthesize rssilabel;
  22.  
  23. char rssi=-100;
  24. - (void)viewDidLoad
  25. {
  26. [super viewDidLoad];
  27. // Do any additional setup after loading the view, typically from a nib.
  28. peripheralManager=[[PeripheralManager alloc]init];
  29. self.MeBle.enabled=NO;
  30. device=[[NSMutableArray alloc]init];
  31.  
  32. }
  33.  
  34. - (void)viewDidUnload
  35. {
  36. [self setDeviceTable:nil];
  37. [self setMeBleUISearch:nil];
  38. [self setMeBle:nil];
  39. [self setRssilabel:nil];
  40. [super viewDidUnload];
  41. // Release any retained subviews of the main view.
  42. }
  43.  
  44. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  45. {
  46. return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
  47. }
  48. - (void)viewWillAppear:(BOOL)animated
  49. {
  50. [super viewWillAppear:animated];
  51. }
  52.  
  53. - (void)viewDidAppear:(BOOL)animated
  54. {
  55. [super viewDidAppear:animated];
  56. }
  57.  
  58. - (void)viewWillDisappear:(BOOL)animated
  59. {
  60. [super viewWillDisappear:animated];
  61. }
  62.  
  63. - (void)viewDidDisappear:(BOOL)animated
  64. {
  65. [super viewDidDisappear:animated];
  66.  
  67. }
  68.  
  69. #pragma mark - PefipheralManagerDelegate methods
  70.  
  71.  
  72. - (void)peripheralManagerDidConnectPeripheral:(PeripheralManager *)peripheral
  73. {
  74. NSLog(@"%@",peripheral.deviceName);
  75. // NSLog(@"%@",peripheral.rssi);
  76. // [device addObject:[NSString stringWithFormat:@"%@",peripheral.deviceName]];
  77. [device addObject:peripheral];
  78. [self.deviceTable reloadData];
  79. }
  80.  
  81. - (void)peripheralManagerDidDisconnectPeripheral:(PeripheralManager *)manager
  82. {
  83. // self.label.text= @"name";
  84. self.MeBle.enabled = YES;
  85. // self.deviceTable.hidden=NO;
  86. deviceTable.hidden=YES;
  87. }
  88. - (void)peripheralManagerNotifyAlertReady:(PeripheralManager *)manager
  89. {
  90. self.alertButton.enabled = YES;
  91. }
  92.  
  93. - (void)peripheralManagerCheckBatteryReady:(PeripheralManager *)manager
  94. {
  95. self.batteryButton.enabled = YES;
  96. }
  97.  
  98. - (void)peripheralManager:(PeripheralManager *)manager
  99. didCheckBattery:(ushort)value
  100. {
  101.  
  102. alert = [[UIAlertView alloc] initWithTitle:@"batterylevel"
  103. message:[NSString stringWithFormat:@"Battery power is ー%d%% ", value]
  104. delegate:nil
  105. cancelButtonTitle:nil
  106. otherButtonTitles:@"OK", nil];
  107. [alert show];
  108. }
  109.  
  110. #pragma mark--UI elements
  111.  
  112. - (IBAction)MeBleUISearch:(id)sender {
  113. [device removeAllObjects];
  114. self.MeBle.enabled = YES;
  115. peripheralManager = [[PeripheralManager alloc] init];
  116. peripheralManager.delegate = self;
  117.  
  118. [peripheralManager scanForPeripheralsAndConnect];
  119. [NSTimer scheduledTimerWithTimeInterval:(float)5.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:YES];
  120. alert=[[UIAlertView alloc] initWithTitle:@"Bluetooth" message:@"Scanning" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
  121. UIActivityIndicatorView *progress=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
  122. [alert addSubview:progress];
  123. [progress startAnimating];
  124. [alert show];
  125. [MeBle setTitle:@"Searching" forState:UIControlStateNormal];
  126. }
  127. - (IBAction)cancelButton:(id)sender {
  128.  
  129. [peripheralManager stopScaning];
  130.  
  131. [MeBle setHidden:NO];
  132.  
  133. }
  134. - (void) connectionTimer:(NSTimer *)timer;
  135. {
  136. [peripheralManager stopScaning];
  137. [MeBle setTitle:@"Scan For Ble" forState:UIControlStateNormal];
  138. [alert dismissWithClickedButtonIndex:0 animated:YES];
  139. }
  140.  
  141.  
  142. #pragma table view
  143. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  144. {
  145. return device.count;
  146. }
  147.  
  148. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  149. {
  150. static NSString *simpleTableIdentifier=@"Cell";
  151.  
  152. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
  153. if(cell==nil)
  154. {
  155. cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
  156. }
  157. cell.textLabel.text=[[device objectAtIndex:indexPath.row]deviceName];
  158. return cell;
  159. }
  160. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  161. {
  162. PeripheralManager * objSelectedDevice=[device objectAtIndex:indexPath.row];
  163.  
  164.  
  165. // detailViewObject.objCurrentDevice=objSelectedDevice;
  166. }
  167.  
  168. -(void) prepareForSegue:(UIStoryboardSegue *)segue selectedDevice:(PeripheralManager *)pobjSelectedDevice sender:(id)sender
  169. {
  170.  
  171.  
  172. if ([segue.identifier isEqualToString:@"TableDetails"]) {
  173.  
  174. MeBleDetailViewController *detailViewObject=segue.destinationViewController;
  175. detailViewObject.dataArray=device;
  176.  
  177. detailViewObject.title=@"Supported Services";
  178.  
  179. detailViewObject.objCurrentDevice=pobjSelectedDevice;
  180. }
  181. }
  182. @end
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190. #import "PeripheralManager.h"
  191.  
  192. NSString *kUUIDServiceImmediateAlert = @"1800";
  193.  
  194. NSString *kUUIDServiceBatteryService = @"180F";
  195.  
  196. NSString *kUUIDCharacteristicsAlertLevel = @"2A06";
  197.  
  198. NSString *kUUIDCharacteristicsBatteryLevel = @"2A19";
  199.  
  200. NSString *kUUIDCharacteristicsTxPowerLevel=@"2A07";
  201.  
  202. @interface PeripheralManager () {
  203.  
  204. CBCentralManager *centralManager;
  205. CBPeripheral *targetPeripheral;
  206.  
  207. CBCharacteristic *alertLevelCharacteristic;
  208. CBCharacteristic *batteryLevelCharacteristic;
  209. CBCharacteristic *TxPowerLevelCharacteristic;
  210. }
  211.  
  212. @end
  213.  
  214. @implementation PeripheralManager
  215.  
  216. @synthesize delegate = _delegate;
  217. @synthesize deviceName=_deviceName;
  218. @synthesize rssi=_rssi;
  219. @synthesize connectButton;
  220.  
  221. #pragma mark - Properties
  222.  
  223. - (NSString *)deviceName
  224. {
  225. if (!targetPeripheral)
  226. {
  227. return nil;
  228. }
  229. return targetPeripheral.name;
  230. }
  231.  
  232. -(NSNumber *)rssi
  233. {
  234. if(!targetPeripheral)
  235. {
  236. return nil;
  237.  
  238. }
  239. return targetPeripheral.RSSI;
  240. }
  241. #pragma mark - View lifecycle methods
  242.  
  243. - (id)init
  244. {
  245. self = [super init];
  246. if (self)
  247. {
  248.  
  249. centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  250. }
  251. return self;
  252. }
  253.  
  254. #pragma mark - Public methods
  255. -(void)ConnectButton:(UIButton *)button
  256. {
  257. connectButton=button;
  258. }
  259.  
  260. - (void)scanForPeripheralsAndConnect
  261. {
  262.  
  263. NSArray *services = [NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDServiceImmediateAlert],
  264. [CBUUID UUIDWithString:kUUIDServiceBatteryService],[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel], nil];
  265.  
  266. NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
  267. forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
  268.  
  269. [centralManager scanForPeripheralsWithServices:services options:options];
  270. }
  271.  
  272. - (void)notifyAlert
  273. {
  274. // HighAlert
  275. ushort value = 2;
  276. NSMutableData *data = [NSMutableData dataWithBytes:&value length:8];
  277.  
  278. [targetPeripheral writeValue:data
  279. forCharacteristic:alertLevelCharacteristic
  280. type:CBCharacteristicWriteWithoutResponse];
  281. }
  282. -(void) stopScaning
  283. {
  284. [centralManager stopScan];
  285. }
  286. - (void)checkBattery
  287. {
  288.  
  289. [targetPeripheral readValueForCharacteristic:batteryLevelCharacteristic];
  290. }
  291. -(void)getAllservices:(CBPeripheral *)peripheral
  292. {
  293. [connectButton setTitle:@"Discovering services" forState:UIControlStateNormal];
  294. [peripheral discoverServices:nil];
  295. }
  296.  
  297. -(void) getAllCharacteristics:(CBPeripheral *)peripheral
  298. {
  299. NSLog(@"Get all characteristics");
  300. [connectButton setTitle:@"Discovering Characteristics" forState:UIControlStateNormal];
  301. for (int i=0;i<peripheral.services.count;i++) {
  302. CBService *services=[peripheral.services objectAtIndex:i];
  303. printf("Fetching characteristics for service with UUID : %s\r\n",nil);
  304. [peripheral discoverCharacteristics:nil forService:services];
  305. }
  306. }
  307.  
  308. #pragma mark - CBCentralManagerDelegate methods
  309.  
  310. - (void)centralManager:(CBCentralManager *)central
  311. didDiscoverPeripheral:(CBPeripheral *)peripheral
  312. advertisementData:(NSDictionary *)advertisementData
  313. RSSI:(NSNumber *)RSSI
  314. {
  315.  
  316. NSLog(@"didDiscoverPeriphera.peripheral: %@ rssi: %@, UUID:%@ advertisementData:%@", peripheral,RSSI,peripheral.UUID, [advertisementData description]);
  317.  
  318. targetPeripheral = peripheral;
  319. peripheral.delegate = self;
  320. // [[centralManager retrievePeripherals:NSArray arrayWithObject:(id)peripheral.UUID] ];
  321. // rssilabel.text=[RSSI stringValue];
  322. if (!peripheral.isConnected)
  323. {
  324. [centralManager connectPeripheral:peripheral options:nil];
  325. }
  326.  
  327. }
  328.  
  329. - (void)centralManager:(CBCentralManager *)central
  330. didConnectPeripheral:(CBPeripheral *)peripheral
  331. {
  332. NSLog(@"didConnectPeripheral");
  333.  
  334.  
  335. [self.delegate peripheralManagerDidConnectPeripheral:self];
  336.  
  337.  
  338. NSArray *services = [NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDServiceImmediateAlert],
  339. [CBUUID UUIDWithString:kUUIDServiceBatteryService],[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel] ,nil];
  340.  
  341. [peripheral discoverServices:services];
  342. }
  343.  
  344. - (void)centralManager:(CBCentralManager *)central
  345. didFailToConnectPeripheral:(CBPeripheral *)peripheral
  346. error:(NSError *)error
  347. {
  348. NSLog(@"didFailToConnectPeripheral %@", [error localizedDescription]);
  349. }
  350.  
  351. - (void)centralManager:(CBCentralManager *)central
  352. didDisconnectPeripheral:(CBPeripheral *)peripheral
  353. error:(NSError *)error
  354. {
  355. NSLog(@"didDisconnectPeripheral %@", [error localizedDescription]);
  356.  
  357. [self.delegate peripheralManagerDidDisconnectPeripheral:self];
  358. }
  359.  
  360. - (void)centralManagerDidUpdateState:(CBCentralManager *)central
  361. {
  362. switch (central.state) {
  363. case CBCentralManagerStatePoweredOn:
  364. NSLog(@"centralManagerDidUpdateState poweredOn");
  365. break;
  366.  
  367. case CBCentralManagerStatePoweredOff:
  368. NSLog(@"centralManagerDidUpdateState poweredOff");
  369. break;
  370.  
  371. case CBCentralManagerStateResetting:
  372. NSLog(@"centralManagerDidUpdateState resetting");
  373. break;
  374.  
  375. case CBCentralManagerStateUnauthorized:
  376. NSLog(@"centralManagerDidUpdateState unauthorized");
  377. break;
  378.  
  379. case CBCentralManagerStateUnsupported:
  380. NSLog(@"centralManagerDidUpdateState unsupported");
  381. break;
  382.  
  383. case CBCentralManagerStateUnknown:
  384. NSLog(@"centralManagerDidUpdateState unknown");
  385. break;
  386.  
  387. default:
  388. break;
  389. }
  390. }
  391.  
  392. #pragma mark - CBPeripheralDelegate methods
  393.  
  394. - (void)peripheral:(CBPeripheral *)peripheral
  395. didDiscoverServices:(NSError *)error
  396. {
  397. if (error)
  398. {
  399. NSLog(@"didDiscoverServices error: %@", error.localizedDescription);
  400. return;
  401. }
  402.  
  403. if (peripheral.services.count == 0)
  404. {
  405. NSLog(@"didDiscoverServices no services");
  406. return;
  407. }
  408.  
  409. NSLog(@"didDiscoverServices services:%@", [peripheral.services description]);
  410.  
  411. for (CBService *service in peripheral.services)
  412. {
  413. if ([service.UUID isEqual:[CBUUID UUIDWithString:kUUIDServiceImmediateAlert]])
  414. {
  415. // Immediate Alert、Alert Level
  416. [peripheral discoverCharacteristics:[NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDCharacteristicsAlertLevel], nil] forService:service];
  417. }
  418. else if ([service.UUID isEqual:[CBUUID UUIDWithString:kUUIDServiceBatteryService]])
  419. {
  420. // Battery Servic、Battery Level
  421. [peripheral discoverCharacteristics:[NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDCharacteristicsBatteryLevel], nil] forService:service];
  422. }
  423. else if([service.UUID isEqual:[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel]])
  424. [peripheral discoverCharacteristics:[NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel], nil] forService:service];
  425. }
  426. }
  427.  
  428. - (void)peripheral:(CBPeripheral *)peripheral
  429. didDiscoverCharacteristicsForService:(CBService *)service
  430. error:(NSError *)error
  431. {
  432. if (error)
  433. {
  434. NSLog(@"didDiscoverCharacteristics error: %@", error.localizedDescription);
  435. return;
  436. }
  437.  
  438. if (service.characteristics.count == 0)
  439. {
  440. NSLog(@"didDiscoverCharacteristics no characteristics");
  441. return;
  442. }
  443.  
  444. NSLog(@"didDiscoverCharacteristics %@", [service.characteristics description]);
  445.  
  446. for (CBCharacteristic *characteristic in service.characteristics)
  447. {
  448. if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kUUIDCharacteristicsAlertLevel]])
  449. {
  450.  
  451. alertLevelCharacteristic = characteristic;
  452.  
  453. [self.delegate peripheralManagerNotifyAlertReady:self];
  454. }
  455. else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kUUIDCharacteristicsBatteryLevel]])
  456. {
  457.  
  458. batteryLevelCharacteristic = characteristic;
  459.  
  460. [self.delegate peripheralManagerCheckBatteryReady:self];
  461. }
  462. }
  463. }
  464.  
  465. - (void)peripheral:(CBPeripheral *)peripheral
  466. didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
  467. error:(NSError *)error
  468. {
  469. if (error)
  470. {
  471. NSLog(@"didUpdateValueForCharacteristic error: %@", error.localizedDescription);
  472. return;
  473. }
  474.  
  475. NSLog(@"didUpdateValueForCharacteristic");
  476.  
  477. if ([characteristic isEqual:batteryLevelCharacteristic])
  478. {
  479.  
  480. ushort value;
  481. NSMutableData *data = [NSMutableData dataWithData:characteristic.value];
  482. [data increaseLengthBy:8];
  483. [data getBytes:&value length:sizeof(value)];
  484.  
  485. [self.delegate peripheralManager:self didCheckBattery:value];
  486. }
  487. NSLog(@"value= %@",characteristic.value);
  488.  
  489.  
  490. }
  491.  
  492. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement