IOS BLE 蓝牙实现方式

//
//  ViewController.m
//  BleTemperatureDemo
//
//  Created by jacob on 16/3/9.
//  Copyright © 2016年 jacob. All rights reserved.
//

#import "ViewController.h"
#import 

//电池的service uuid
static NSString *BATTERY_SERVICE = @"1xxx";
//电池的特征值的UUID
static NSString *BATTERY_READ_CHAR = @"2Axx";
//体温数据的service UUID
static NSString *HEALTH_SERVICE = @"1xxx";
//体温特征值的UUID
static NSString *HEALTH_READ_CHAR = @"2xxx";


@interface ViewController () 
@property (weak, nonatomic) IBOutlet UILabel *labelState;
@property (weak, nonatomic) IBOutlet UILabel *labelTemperature;
@property (weak, nonatomic) IBOutlet UILabel *labelBattery;

@property(nonatomic,strong) CBCentralManager *bleManager;
@property(nonatomic,strong) NSMutableArray *multArray;
@property(nonatomic,strong) CBPeripheral *myPeripheral;

- (IBAction)startScan:(UIButton *)sender;
- (IBAction)stopScan:(UIButton *)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     _bleManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    NSLog(@"centralManagerDidUpdateState");
    switch (central.state) {
        case CBCentralManagerStatePoweredOff:
            NSLog(@"蓝牙已关闭");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@"蓝牙已打开");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"不支持蓝牙");
            break;
            
        default:
            break;
    }
}


-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    NSLog(@"peripheral--:%@",peripheral);
    if ([peripheral.name containsString:@"Thermometer"]) {
      
        self.labelState.text = @"已发现设备";
        peripheral.delegate = self;
        NSLog(@"开始连接设备");
        self.myPeripheral = peripheral;
        [self.bleManager connectPeripheral:self.myPeripheral options:nil];

    }
}


/**
 *连接上设备的信息回调,连接上设备后,开始发现服务
 */
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"设备连接成功,准备扫描服务");
  
    [peripheral discoverServices:nil];
    
    self.labelState.text  = @"设备连接成功";
}

-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    self.labelState.text  = @"设备已经断开";
    if (error) {
        NSLog(@"didDisconnectPeripheral with error : %@",error);
        return;
    }
}


/**
 扫描外设服务的数据回调
 */
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    
    if (error) {
        NSLog(@"didDiscoverServices with error : %@",error);
        return;
    }
    
    
    for (CBService *service in peripheral.services) {
        NSLog(@"service uuid: %@",service.UUID.UUIDString);
        if ([service.UUID.UUIDString isEqualToString:BATTERY_SERVICE]) {
            NSLog(@"已经发现电池对应的服务");
            [peripheral discoverCharacteristics:nil forService:service];
        }
        
        if ([service.UUID.UUIDString isEqualToString:HEALTH_SERVICE]) {
            NSLog(@"已经发现体温数据对应的服务");
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
}

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    
    NSLog(@"发现服务 %@, 特性数: %ld", service.UUID, [service.characteristics count]);
    if (error) {
        NSLog(@"didDiscoverCharacteristicsForService with error : %@",error);
        return;
    }
    
    //电池电量的数据直接读对应的特征值即可
    if ([service.UUID.UUIDString isEqualToString:BATTERY_SERVICE]) {
          for (CBCharacteristic *character in service.characteristics) {
              if ([character.UUID.UUIDString isEqualToString:BATTERY_READ_CHAR]) {
                  NSLog(@"已找到電池对应服务中的 特征值");
                  [peripheral readValueForCharacteristic:character];
            
              }
          }
    }
    
    
    //体温数据需要通过notify的方式进行获取
    if ([service.UUID.UUIDString isEqualToString:HEALTH_SERVICE]) {
        for (CBCharacteristic *character in service.characteristics) {
            if ([character.UUID.UUIDString isEqualToString:HEALTH_READ_CHAR]) {
                NSLog(@"已找到体温对应服务中的 特征值");
                [peripheral setNotifyValue:YES forCharacteristic:character];
            }
        }
    }


}

/**
 read 或者 notify的方式都会在这个函数中返回数据
 */
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error) {
        NSLog(@"didUpdateValueForCharacteristic with error : %@",error);
        return;
    }
    
    NSData *data = characteristic.value;
    NSLog(@"收到数据啦 %@---%@", data,characteristic.UUID);
    
    //电量数据
    if ([characteristic.UUID.UUIDString isEqualToString:BATTERY_READ_CHAR]) {
        int battery;
        [data getBytes: &battery length: sizeof(battery)];
        self.labelBattery.text = [NSString stringWithFormat:@"%d",battery];
    }
    
    
    
    //体温数据
    if ([characteristic.UUID.UUIDString isEqualToString:HEALTH_READ_CHAR]) {
        Byte *testByte = (Byte *)[data bytes];
        Byte orgin[4];
        orgin[0] = testByte[1];
        orgin[1] = testByte[2];
        orgin[2] = testByte[3];
        
        NSData *chidata=[NSData dataWithBytes:orgin length:4];
        int code;
        [chidata getBytes:&code length:4];
        //NSInteger temp = [self byteToInt:orgin];
        self.labelTemperature.text = [NSString stringWithFormat:@"%.2f",(0.1+0.01*code)];
    }
   
}



- (IBAction)startScan:(UIButton *)sender {
    [self.bleManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(YES)}];
     NSLog(@"开始扫描");
    
}

- (IBAction)stopScan:(UIButton *)sender {
    NSLog(@"停止扫描");
    [self.bleManager stopScan ];
    [self.bleManager cancelPeripheralConnection:self.myPeripheral];
    
    self.labelBattery.text = @"";
    self.labelState.text = @"";
    self.labelTemperature.text = @"";
}
@end

你可能感兴趣的:(IOS,UI基础)