iOS--蓝牙通讯/blutooth________向周边发数据________处理蓝牙发过来的数据

来源:互联网 发布:矩阵张量积 计算公式 编辑:程序博客网 时间:2024/06/10 03:36
最近做了iOS蓝牙通讯的一个项目,使用blutooth,支持蓝牙ble 4.0

1,导入

2,#import <CoreBluetooth/CoreBluetooth.h>

3,协议<CBCentralManagerDelegate,CBPeripheralDelegate>

4,CBCentralManager *cm = [[CBCentralManager allocinitWithDelegate:self queue:nil];

    cm.delegate = self;

 //scan外设

        NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumbernumberWithBool:NOforKey:CBCentralManagerScanOptionAllowDuplicatesKey];

        [cm scanForPeripheralsWithServices:nil options:scanOptions];


- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber*)RSSI//scan到设备就会调用此方法


//connect设备

NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]forKey:CBCentralManagerScanOptionAllowDuplicatesKey];

        [cm connectPeripheral:(CBPeripheral *)[_peripheralArrayobjectAtIndex:indexPath.rowoptions:scanOptions];


- (void) centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral*)peripheral error:(NSError *)error//连接外设时调用


- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral*)peripheral//当连接上一个外设  CBCentralManager 代理 处理此方法


4,//查询设备服务特征,注意 这块的peripheral 一定得为连接上的设备 后续发送接收数据有用

[peripheral setDelegate:self];

[peripheral discoverServices:nil];

#pragma mark -- CBPeripheralDelegate

//返回的蓝牙服务通知通过代理实现[_peripheral discoverServices:nil];


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

//查询服务所带的特征值[_peripheral discoverCharacteristics:nil forService:myService];

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


5,

//发送数据

[peripheral writeValue:datastr forCharacteristic:writeCharacteristictype:CBCharacteristicWriteWithResponse];

//发送成功调用

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

//处理蓝牙发过来的数据

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

0 0
原创粉丝点击