corebuletoolth

来源:互联网 发布:php网络爬虫代码 编辑:程序博客网 时间:2024/06/03 18:06
1,   
@property (nonatomic , strongCBCentralManager *centralManager;
@property (nonatomic , strongCBPeripheral *peripheral;
@property (nonatomic , copyNSString *peripheralName;
@property (strong,nonatomicNSMutableArray *nCharacteristics;

2,
self.centralManager = [[CBCentralManager allocinitWithDelegate:self queue:nil];
//初始化,启动一个centeralmanager


- (void)viewDidLoad

{

self.centralManager = [[CBCentralManager allocinitWithDelegate:self queue:nil];

}



3,

//主设备状态改变的委托,当设备状态为power on时,开始扫描设备

[self.centralManager scanForPeripheralsWithServices:nil                                             options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];



- (void)centralManagerDidUpdateState:(CBCentralManager *)central

{

    switch (central.state) {

        case CBCentralManagerStatePoweredOn:

        {

            NSLog(@"可用,现在可以搜索blueServer");

            //第一个参数指定了要搜寻的服务,如果传nil,表示搜寻搜有的服务

//            [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]]

//                                                        options:@{CBCentralManagerOptionShowPowerAlertKey:@YES}];

              //开始扫描

            [self.centralManager scanForPeripheralsWithServices:nil

                                                        options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];

        

        }

            break;

        case CBCentralManagerStatePoweredOff:

        {

            NSLog(@"Bluetooth is currently powered off.");

        }

            break;

        case CBCentralManagerStateUnauthorized:

        {

            NSLog(@"The application is not authorized to use the Bluetooth Low Energy Central/Client role.");

        }

            break;

        case CBCentralManagerStateUnsupported:

        {

            NSLog(@"The platform doesn't support the Bluetooth Low Energy Central/Client role.");

        }

            break;

        case CBCentralManagerStateResetting:

        {

            NSLog(@"The connection with the system service was momentarily lost, update imminent.");

        }

            break;

        case CBCentralManagerStateUnknown:

        {

            NSLog(@"State unknown, update imminent.");

        }

            break;

        default:

            break;

    }

}


4

//didDiscoverPeripheral 判断是否发现设备  然后开始连接外设


- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI

{

    NSLog(@"找到了服务:%@,信号质量:%@",advertisementData,RSSI);

    

   // self.serviceName = [advertisementData objectForKey:@"kCBAdvDataLocalName"];

self.peripheralName=periapheral.namep;    


    //停止扫描外围设备

    [self.centralManager stopScan];

    

    if (self.peripheral != peripheral) {

        

        self.peripheral = peripheral;

        NSLog(@"开始连接blueServer:%@",peripheral);

        

        //连接外设

        [self.centralManager connectPeripheral:self.peripheral options:nil];

        

    }

}


5


//连接外设成功  开始扫描指定的服务uuid

  [self.peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];


[self.peripheral discoverServices:nil];  扫描全部的服务id


- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

{

    //因为一个peripheral可能不止提供一个service

    NSLog(@"连接成功,进一步获取peripheralservice");

    

    //这个定时器用来查看当前的连接状态

    self.timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(readBLEServiceRSSI) userInfo:nilrepeats:YES];

    

    [self.data setLength:0];

    [self.peripheral setDelegate:self];

    

    //peripheral发现自己  扫描指定服务id

    [self.peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];

    

//    [self.peripheral discoverServices:nil];  扫描全部的服务id

}



- (void)readBLEServiceRSSI

{

//    NSLog(@"变化");

    [self.peripheral readRSSI];

}


//rssi更新回调的方法

- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error

{

    NSLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral);

    int rssi = abs([peripheral.RSSI intValue]);

    CGFloat ci = (rssi - 49) / (10 * 4.);

    self.mainLabel.text = [NSString stringWithFormat:@"发现BLT4.0热点:%@,距离:%.1fm",self.peripheralName,pow(10,ci)];

    


}


6


 //扫描到Services  然后扫描指定的特征值


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error

{

//    

//    [self.centralManager stopScan];

//    [self.centralManager connectPeripheral:self.peripheral options:nil];


    

    if (error) {

        NSLog(@"%s,error=%@",__PRETTY_FUNCTION__,error);

    } else {

        

        NSLog(@"----------服务%@",peripheral.services);

        

        

        for (CBService *service in peripheral.services) {

            

            NSLog(@"发现UUID=%@的服务",service.UUID);

            NSLog(@"开始检测这个服务的特征码...”);


//扫描扫描到的所有服务的全部特征值

              [self.peripheral discoverCharacteristics:nil forService:service];


            

            //扫描指定服务id的特征值

          //  if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {

                

                //扫描特征值

              //  [self.peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];

                

//                [self.peripheral discoverCharacteristics:nil forService:service];

//                

//                [self.centralManager connectPeripheral:self.peripheral options:nil];


          //  }


//            [self.peripheral discoverCharacteristics:nil forService:service];

        

        }

    }

}




7,

扫描到特征值, 订制一个特性值               

      [peripheral setNotifyValue:YES forCharacteristic:characteristic];


尽管通过readValueForCharacteristic:方法能够得到特性值,但是对于一个变化的特性值就不是很有效了。大多数的特性值是变化的,比如一个心率监测应用,

如果需要得到特性值,就需要通过预定的方法获得。当预定了一个特性值,当值改变时,就会收到设备发出的通知。


第一、 设置通知值 

[peripheral setNotifyValue:YES forCharacteristic:interestingCharacteristic]; 其中第一个参数一定要为YES 


第二、 判断是否订制特性值成功 

- (void)peripheral:(CBPeripheral *)peripheral 

didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { 

if (error) { 

NSLog(@"Error changing notification state: %@", [error localizedDescription]); } ... 

 

注意:不是所有特性都是允许订制值的。可以参考CBCharacteristic Class Reference。 


第三、 取得订制的特性值 

如果成功订制的特性值,当值有变化时,设备就会通知APP。每次值变化,call 

 peripheral:didUpdateValueForCharacteristic:error: 方法取得具体的值。


第一

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

{

    if (error) {

        NSLog(@"%s,%@",__PRETTY_FUNCTION__,error);

    } else {

        //如果是指定的服务id

        if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {

            

            //找到指定的特征id

            for (CBCharacteristic *characteristic in service.characteristics) {


 [_nCharacteristics addObject:characteristic];//记录所有的特征值

               

                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {

                    

                    [peripheral setNotifyValue:YES

                             forCharacteristic:characteristic];//设置接收的通知

                    

                   // _writeCharacteristic = characteristic;

                }                


            }

        }        

       

    }    

    

}



第二

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

{

    if (error) {

        NSLog(@"%s,%@",__PRETTY_FUNCTION__,error);

    }

//指定的特征id

    if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {

        return;

    }

    

    //已经发送通知

    if (characteristic.isNotifying) {

        NSLog(@"Notification began on %@",characteristic);

        [peripheral readValueForCharacteristic:characteristic];

    } else {

        //Notification has stopped

        //so disconnect from the peripheral

        NSLog(@"Notification stopped on %@ Disconnecting",characteristic);

        [self.centralManager cancelPeripheralConnection:self.peripheral];

    }

}


第三


//取得具体的值

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

{

    NSLog(@"peripheral = %@,%s",peripheral,__PRETTY_FUNCTION__);

    NSString *messageText = [[NSString allocinitWithData:[characteristic valueencoding:NSASCIIStringEncoding];


    requestLabel.text = messageText;

}


8发送


发送涵数


-(void)writeCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID data:(NSData *)data {

    // Sends data to BLE peripheral to process HID and send EHIF command to PC

    for ( CBService *service in peripheral.services ) {//找到指定的服务

        

        if ([service.UUID isEqual:[CBUUID UUIDWithString:sUUID]]) {

            

            for ( CBCharacteristic *characteristic in service.characteristics ) {//找到指定服务的指定特征值

                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:cUUID]]) {

                    /* EVERYTHING IS FOUND, WRITE characteristic ! */

                    NSLog(@"发送");

                    [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];

                    

                }

            }

        }

    }

}



- (void)buttonAction {


    NSData *data =[_editText.text dataUsingEncoding:NSASCIIStringEncoding];


    [self writeCharacteristic:_peripheral sUUID:@"FFE5" cUUID:@"FFE9" data:data];

    

}


0 0
原创粉丝点击