Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import "MeBleFirstViewController.h"
- @interface MeBleFirstViewController ()
- @end
- @implementation MeBleFirstViewController
- {
- PeripheralManager *peripheralManager;
- }
- @synthesize MeBleUISearch;
- @synthesize deviceTable;
- @synthesize alert;
- @synthesize array;
- @synthesize MeBle;
- @synthesize device;
- @synthesize alertButton;
- @synthesize batteryButton;
- @synthesize rssilabel;
- char rssi=-100;
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- peripheralManager=[[PeripheralManager alloc]init];
- self.MeBle.enabled=NO;
- device=[[NSMutableArray alloc]init];
- }
- - (void)viewDidUnload
- {
- [self setDeviceTable:nil];
- [self setMeBleUISearch:nil];
- [self setMeBle:nil];
- [self setRssilabel:nil];
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
- }
- - (void)viewWillAppear:(BOOL)animated
- {
- [super viewWillAppear:animated];
- }
- - (void)viewDidAppear:(BOOL)animated
- {
- [super viewDidAppear:animated];
- }
- - (void)viewWillDisappear:(BOOL)animated
- {
- [super viewWillDisappear:animated];
- }
- - (void)viewDidDisappear:(BOOL)animated
- {
- [super viewDidDisappear:animated];
- }
- #pragma mark - PefipheralManagerDelegate methods
- - (void)peripheralManagerDidConnectPeripheral:(PeripheralManager *)peripheral
- {
- NSLog(@"%@",peripheral.deviceName);
- // NSLog(@"%@",peripheral.rssi);
- // [device addObject:[NSString stringWithFormat:@"%@",peripheral.deviceName]];
- [device addObject:peripheral];
- [self.deviceTable reloadData];
- }
- - (void)peripheralManagerDidDisconnectPeripheral:(PeripheralManager *)manager
- {
- // self.label.text= @"name";
- self.MeBle.enabled = YES;
- // self.deviceTable.hidden=NO;
- deviceTable.hidden=YES;
- }
- - (void)peripheralManagerNotifyAlertReady:(PeripheralManager *)manager
- {
- self.alertButton.enabled = YES;
- }
- - (void)peripheralManagerCheckBatteryReady:(PeripheralManager *)manager
- {
- self.batteryButton.enabled = YES;
- }
- - (void)peripheralManager:(PeripheralManager *)manager
- didCheckBattery:(ushort)value
- {
- alert = [[UIAlertView alloc] initWithTitle:@"batterylevel"
- message:[NSString stringWithFormat:@"Battery power is ー%d%% ", value]
- delegate:nil
- cancelButtonTitle:nil
- otherButtonTitles:@"OK", nil];
- [alert show];
- }
- #pragma mark--UI elements
- - (IBAction)MeBleUISearch:(id)sender {
- [device removeAllObjects];
- self.MeBle.enabled = YES;
- peripheralManager = [[PeripheralManager alloc] init];
- peripheralManager.delegate = self;
- [peripheralManager scanForPeripheralsAndConnect];
- [NSTimer scheduledTimerWithTimeInterval:(float)5.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:YES];
- alert=[[UIAlertView alloc] initWithTitle:@"Bluetooth" message:@"Scanning" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
- UIActivityIndicatorView *progress=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
- [alert addSubview:progress];
- [progress startAnimating];
- [alert show];
- [MeBle setTitle:@"Searching" forState:UIControlStateNormal];
- }
- - (IBAction)cancelButton:(id)sender {
- [peripheralManager stopScaning];
- [MeBle setHidden:NO];
- }
- - (void) connectionTimer:(NSTimer *)timer;
- {
- [peripheralManager stopScaning];
- [MeBle setTitle:@"Scan For Ble" forState:UIControlStateNormal];
- [alert dismissWithClickedButtonIndex:0 animated:YES];
- }
- #pragma table view
- -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- {
- return device.count;
- }
- -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *simpleTableIdentifier=@"Cell";
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
- if(cell==nil)
- {
- cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
- }
- cell.textLabel.text=[[device objectAtIndex:indexPath.row]deviceName];
- return cell;
- }
- -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- {
- PeripheralManager * objSelectedDevice=[device objectAtIndex:indexPath.row];
- // detailViewObject.objCurrentDevice=objSelectedDevice;
- }
- -(void) prepareForSegue:(UIStoryboardSegue *)segue selectedDevice:(PeripheralManager *)pobjSelectedDevice sender:(id)sender
- {
- if ([segue.identifier isEqualToString:@"TableDetails"]) {
- MeBleDetailViewController *detailViewObject=segue.destinationViewController;
- detailViewObject.dataArray=device;
- detailViewObject.title=@"Supported Services";
- detailViewObject.objCurrentDevice=pobjSelectedDevice;
- }
- }
- @end
- #import "PeripheralManager.h"
- NSString *kUUIDServiceImmediateAlert = @"1800";
- NSString *kUUIDServiceBatteryService = @"180F";
- NSString *kUUIDCharacteristicsAlertLevel = @"2A06";
- NSString *kUUIDCharacteristicsBatteryLevel = @"2A19";
- NSString *kUUIDCharacteristicsTxPowerLevel=@"2A07";
- @interface PeripheralManager () {
- CBCentralManager *centralManager;
- CBPeripheral *targetPeripheral;
- CBCharacteristic *alertLevelCharacteristic;
- CBCharacteristic *batteryLevelCharacteristic;
- CBCharacteristic *TxPowerLevelCharacteristic;
- }
- @end
- @implementation PeripheralManager
- @synthesize delegate = _delegate;
- @synthesize deviceName=_deviceName;
- @synthesize rssi=_rssi;
- @synthesize connectButton;
- #pragma mark - Properties
- - (NSString *)deviceName
- {
- if (!targetPeripheral)
- {
- return nil;
- }
- return targetPeripheral.name;
- }
- -(NSNumber *)rssi
- {
- if(!targetPeripheral)
- {
- return nil;
- }
- return targetPeripheral.RSSI;
- }
- #pragma mark - View lifecycle methods
- - (id)init
- {
- self = [super init];
- if (self)
- {
- centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
- }
- return self;
- }
- #pragma mark - Public methods
- -(void)ConnectButton:(UIButton *)button
- {
- connectButton=button;
- }
- - (void)scanForPeripheralsAndConnect
- {
- NSArray *services = [NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDServiceImmediateAlert],
- [CBUUID UUIDWithString:kUUIDServiceBatteryService],[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel], nil];
- NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
- forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
- [centralManager scanForPeripheralsWithServices:services options:options];
- }
- - (void)notifyAlert
- {
- // HighAlert
- ushort value = 2;
- NSMutableData *data = [NSMutableData dataWithBytes:&value length:8];
- [targetPeripheral writeValue:data
- forCharacteristic:alertLevelCharacteristic
- type:CBCharacteristicWriteWithoutResponse];
- }
- -(void) stopScaning
- {
- [centralManager stopScan];
- }
- - (void)checkBattery
- {
- [targetPeripheral readValueForCharacteristic:batteryLevelCharacteristic];
- }
- -(void)getAllservices:(CBPeripheral *)peripheral
- {
- [connectButton setTitle:@"Discovering services" forState:UIControlStateNormal];
- [peripheral discoverServices:nil];
- }
- -(void) getAllCharacteristics:(CBPeripheral *)peripheral
- {
- NSLog(@"Get all characteristics");
- [connectButton setTitle:@"Discovering Characteristics" forState:UIControlStateNormal];
- for (int i=0;i<peripheral.services.count;i++) {
- CBService *services=[peripheral.services objectAtIndex:i];
- printf("Fetching characteristics for service with UUID : %s\r\n",nil);
- [peripheral discoverCharacteristics:nil forService:services];
- }
- }
- #pragma mark - CBCentralManagerDelegate methods
- - (void)centralManager:(CBCentralManager *)central
- didDiscoverPeripheral:(CBPeripheral *)peripheral
- advertisementData:(NSDictionary *)advertisementData
- RSSI:(NSNumber *)RSSI
- {
- NSLog(@"didDiscoverPeriphera.peripheral: %@ rssi: %@, UUID:%@ advertisementData:%@", peripheral,RSSI,peripheral.UUID, [advertisementData description]);
- targetPeripheral = peripheral;
- peripheral.delegate = self;
- // [[centralManager retrievePeripherals:NSArray arrayWithObject:(id)peripheral.UUID] ];
- // rssilabel.text=[RSSI stringValue];
- if (!peripheral.isConnected)
- {
- [centralManager connectPeripheral:peripheral options:nil];
- }
- }
- - (void)centralManager:(CBCentralManager *)central
- didConnectPeripheral:(CBPeripheral *)peripheral
- {
- NSLog(@"didConnectPeripheral");
- [self.delegate peripheralManagerDidConnectPeripheral:self];
- NSArray *services = [NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDServiceImmediateAlert],
- [CBUUID UUIDWithString:kUUIDServiceBatteryService],[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel] ,nil];
- [peripheral discoverServices:services];
- }
- - (void)centralManager:(CBCentralManager *)central
- didFailToConnectPeripheral:(CBPeripheral *)peripheral
- error:(NSError *)error
- {
- NSLog(@"didFailToConnectPeripheral %@", [error localizedDescription]);
- }
- - (void)centralManager:(CBCentralManager *)central
- didDisconnectPeripheral:(CBPeripheral *)peripheral
- error:(NSError *)error
- {
- NSLog(@"didDisconnectPeripheral %@", [error localizedDescription]);
- [self.delegate peripheralManagerDidDisconnectPeripheral:self];
- }
- - (void)centralManagerDidUpdateState:(CBCentralManager *)central
- {
- switch (central.state) {
- case CBCentralManagerStatePoweredOn:
- NSLog(@"centralManagerDidUpdateState poweredOn");
- break;
- case CBCentralManagerStatePoweredOff:
- NSLog(@"centralManagerDidUpdateState poweredOff");
- break;
- case CBCentralManagerStateResetting:
- NSLog(@"centralManagerDidUpdateState resetting");
- break;
- case CBCentralManagerStateUnauthorized:
- NSLog(@"centralManagerDidUpdateState unauthorized");
- break;
- case CBCentralManagerStateUnsupported:
- NSLog(@"centralManagerDidUpdateState unsupported");
- break;
- case CBCentralManagerStateUnknown:
- NSLog(@"centralManagerDidUpdateState unknown");
- break;
- default:
- break;
- }
- }
- #pragma mark - CBPeripheralDelegate methods
- - (void)peripheral:(CBPeripheral *)peripheral
- didDiscoverServices:(NSError *)error
- {
- if (error)
- {
- NSLog(@"didDiscoverServices error: %@", error.localizedDescription);
- return;
- }
- if (peripheral.services.count == 0)
- {
- NSLog(@"didDiscoverServices no services");
- return;
- }
- NSLog(@"didDiscoverServices services:%@", [peripheral.services description]);
- for (CBService *service in peripheral.services)
- {
- if ([service.UUID isEqual:[CBUUID UUIDWithString:kUUIDServiceImmediateAlert]])
- {
- // Immediate Alert、Alert Level
- [peripheral discoverCharacteristics:[NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDCharacteristicsAlertLevel], nil] forService:service];
- }
- else if ([service.UUID isEqual:[CBUUID UUIDWithString:kUUIDServiceBatteryService]])
- {
- // Battery Servic、Battery Level
- [peripheral discoverCharacteristics:[NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDCharacteristicsBatteryLevel], nil] forService:service];
- }
- else if([service.UUID isEqual:[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel]])
- [peripheral discoverCharacteristics:[NSArray arrayWithObjects:[CBUUID UUIDWithString:kUUIDCharacteristicsTxPowerLevel], nil] forService:service];
- }
- }
- - (void)peripheral:(CBPeripheral *)peripheral
- didDiscoverCharacteristicsForService:(CBService *)service
- error:(NSError *)error
- {
- if (error)
- {
- NSLog(@"didDiscoverCharacteristics error: %@", error.localizedDescription);
- return;
- }
- if (service.characteristics.count == 0)
- {
- NSLog(@"didDiscoverCharacteristics no characteristics");
- return;
- }
- NSLog(@"didDiscoverCharacteristics %@", [service.characteristics description]);
- for (CBCharacteristic *characteristic in service.characteristics)
- {
- if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kUUIDCharacteristicsAlertLevel]])
- {
- alertLevelCharacteristic = characteristic;
- [self.delegate peripheralManagerNotifyAlertReady:self];
- }
- else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kUUIDCharacteristicsBatteryLevel]])
- {
- batteryLevelCharacteristic = characteristic;
- [self.delegate peripheralManagerCheckBatteryReady:self];
- }
- }
- }
- - (void)peripheral:(CBPeripheral *)peripheral
- didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
- error:(NSError *)error
- {
- if (error)
- {
- NSLog(@"didUpdateValueForCharacteristic error: %@", error.localizedDescription);
- return;
- }
- NSLog(@"didUpdateValueForCharacteristic");
- if ([characteristic isEqual:batteryLevelCharacteristic])
- {
- ushort value;
- NSMutableData *data = [NSMutableData dataWithData:characteristic.value];
- [data increaseLengthBy:8];
- [data getBytes:&value length:sizeof(value)];
- [self.delegate peripheralManager:self didCheckBattery:value];
- }
- NSLog(@"value= %@",characteristic.value);
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement