iOS蓝牙

前几个月做了一个蓝牙的项目,初次接触,也查了好多资料,算是有了个大概的了解,最近又做另一个蓝牙的项目,发现还是有很多地方不是很明白,也为了防止忘记,就写下来吧!

在CBCentralManager初始化的时候,一般放在另一个线程中:

    dispatch_queue_t centralQueue = dispatch_queue_create("myCentralQueue",DISPATCH_QUEUE_SERIAL);
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue];
初始化也可以使用如下的方法:

- (id)initWithDelegate:(id<CBCentralManagerDelegate>)delegate queue:(dispatch_queue_t)queue options:(NSDictionary *)options
如:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES],CBCentralManagerOptionShowPowerAlertKey,
@"zStrapRestoreIdentifier",CBCentralManagerOptionRestoreIdentifierKey,
nil];

myCenter = [[CBCentralManager alloc] initWithDelegate:self
                                          queue:dispatch_queue_create("com.myBLEQueue", NULL)
                                          options:options];

Central Manager Initialization Options 对应的有两项:
CBCentralManagerOptionShowPowerAlertKey
布尔值,表示的是在central manager初始化时,如果当前蓝牙没打开,是否弹出alert框。
CBCentralManagerOptionRestoreIdentifierKey
CBCentralManagerOptionRestoreIdentifierKey,字符串,一个唯一的标示符,用来蓝牙的恢复连接的。在后台的长连接中可能会用到。

就是说,如果蓝牙程序进入后台,程序会被挂起,可能由于memory pressure,程序被系统kill了,那么代理方法就不会执行了。这时候可以使用State Preservation & Restoration,这样程序会重新加载进入后台。

调试iOS蓝牙的时候,可以下个LightBlue,非常方便,网上也有仿写LightBlue的Demo,参考这两处:
https://github.com/chenee/DarkBlue

http://boxertan.github.io/blog/2014/07/07/xue-xi-ioslan-ya-ji-zhu-%2Cfang-xie-lightblue/

使用scanForPeripheralsWithServices:options: 来扫描外设

NSDictionary *option = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey,nil];
[_centralManager scanForPeripheralsWithServices:nil options:option];


options是可选的,CBCentralManagerScanOptionAllowDuplicatesKey,bool值,为NO,表示不会重复扫描已经发现的设备。

连接外设使用connectPeripheral:options: 方法,options为可选,options可以为:
CBConnectPeripheralOptionNotifyOnConnectionKey
CBConnectPeripheralOptionNotifyOnDisconnectionKey
CBConnectPeripheralOptionNotifyOnNotificationKey

具体的意思参考文档

[myCenter connectPeripheral:peripheralInfo.peripheral options:@{
    CBConnectPeripheralOptionNotifyOnConnectionKey: @YES,
    CBConnectPeripheralOptionNotifyOnDisconnectionKey: @YES,
    CBConnectPeripheralOptionNotifyOnNotificationKey: @YES}];

在蓝牙连接的过程中,代理方法centralManagerDidUpdateState: 会判断中央设备的状态

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    // Determine the state of the peripheral
    if ([central state] == CBCentralManagerStatePoweredOff) {
        NSLog(@"CoreBluetooth BLE hardware is powered off");
    }
    else if ([central state] == CBCentralManagerStatePoweredOn) {
        NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
    }
    else if ([central state] == CBCentralManagerStateUnauthorized) {
        NSLog(@"CoreBluetooth BLE state is unauthorized");
    }
    else if ([central state] == CBCentralManagerStateUnknown) {
        NSLog(@"CoreBluetooth BLE state is unknown");
    }
    else if ([central state] == CBCentralManagerStateUnsupported) {
        NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
    }
}


返现characteristic后可以读取它的值,也可以订阅它:

[self.peripheral readValueForCharacteristic:characteristic];
[self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
以上两个方法都会调用代理方法:didUpdateValueForCharacteristic:error: 


向外设的某个characteristic写入值,可以这样写

- (void)writeToperipheral:(CBPeripheral *)peripheral Service:(NSString *)serviceUUID characteristic:(NSString *)characteristicUUID data:(NSData *)data
{
    CBUUID *servUUID = [CBUUID UUIDWithString:serviceUUID];
    CBUUID *charUUID = [CBUUID UUIDWithString:characteristicUUID];
    CBService *service = nil;
    CBCharacteristic *characteristic = nil;
    for (CBService *ser in peripheral.services) {
        if ([ser.UUID isEqual:servUUID]) {
            service = ser;
            break;
        }
    }
    if (service) {
        for (CBCharacteristic *charac in service.characteristics) {
            if ([charac.UUID isEqual:charUUID]) {
                characteristic = charac;
                break;
            }
        }
    }
    if (characteristic) {
        [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }
    else{
        NSLog(@"not found that characteristic");
    }
}


NSData的值可以这样组织,这与你的需求有关并不一定:

char data;
data = 0x15;
NSData *d = [[NSData alloc] initWithBytes:&data length:1];


读取某个characteristic的值

- (void)readPeripheral:(CBPeripheral *)peripheral serviceUUID:(NSString *)serviceUUID characteristicUUID:(NSString *)characteristicUUID
{
    CBUUID *servUUID = [CBUUID UUIDWithString:serviceUUID];
    CBUUID *charUUID = [CBUUID UUIDWithString:characteristicUUID];
    CBService *service = nil;
    CBCharacteristic *characteristic = nil;
    for (CBService *ser in peripheral.services) {
        if ([ser.UUID isEqual:servUUID]) {
            service = ser;
            break;
        }
    }
    if (service) {
        for (CBCharacteristic *charac in service.characteristics) {
            if ([charac.UUID isEqual:charUUID]) {
                characteristic = charac;
                break;
            }
        }
    }
    if (characteristic) {
        [peripheral readValueForCharacteristic:characteristic];
    }else{
        NSLog(@"----------未找到当前的characteristic");
    }
}


通过保存的identity来找到以前连接的设备
保存identity

NSUUID *uuid = peripheral.identifier;
NSString *uuidString = uuid.UUIDString;
[[NSUserDefaults standardUserDefaults] setObject:uuidString forKey:PERIPHERAL_UUID];
[[NSUserDefaults standardUserDefaults] synchronize];
然后通过identity,来搜索设备:

NSString *uuidString = [[NSUserDefaults standardUserDefaults] stringForKey:PERIPHERAL_UUID];
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
_peripheralArr = [NSMutableArray arrayWithArray: [self.centralManager retrievePeripheralsWithIdentifiers:@[uuid]]];
for (CBPeripheral *peripheral in _peripheralArr) {
    self.peripheral = peripheral;
    [self.centralManager connectPeripheral:peripheral options:nil];
}
通过retrieveConnectedPeripheralsWithServices:函数来检索当前连接到系统的蓝牙设备:

NSArray *atmp = [NSArray arrayWithObjects:[CBUUID UUIDWithString:@"180A"], nil];
NSArray *retrivedArray = [myCenter retrieveConnectedPeripheralsWithServices:atmp];
NSLog(@"retrivedArray:\n%@",retrivedArray);

for (CBPeripheral* peripheral in retrivedArray) {
    [self addPeripheral:peripheral advertisementData:nil  RSSI:nil];
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS蓝牙Mesh开发是指在iOS系统中使用蓝牙Mesh技术进行开发。蓝牙Mesh是一种用于无线网络通信的技术,它基于蓝牙低功耗(Bluetooth Low Energy,BLE)标准,并支持多对多的网络连接。通过使用蓝牙Mesh,可以实现设备间的直接通信,而无需通过传统的中心设备来中转数据。 在iOS蓝牙Mesh开发中,开发者可以利用iOS系统提供的CoreBluetooth框架来实现蓝牙Mesh的功能。CoreBluetooth框架提供了一系列API,可以用于扫描、连接和通信等操作。开发者可以使用这些API与蓝牙Mesh设备进行通信,并实现各种功能,如设备发现、数据传输、网络配置等。 在进行iOS蓝牙Mesh开发时,需要特别注意以下几点: 1. 版本要求:要使用蓝牙Mesh功能,需要iOS 11及以上的版本。 2. 硬件支持:要使用蓝牙Mesh功能,需要确保设备支持蓝牙4.0及以上版本。 3. 学习Mesh协议:蓝牙Mesh开发需要了解蓝牙Mesh协议的相关知识,如网络拓扑结构、节点之间的通信方式等。 4. 设备兼容性:不同厂商的设备对蓝牙Mesh的支持程度可能有所不同,需要考虑设备的兼容性。 总体来说,iOS蓝牙Mesh开发可以用于构建无线传感器网络、智能家居和物联网等应用。开发者可以根据具体需求,利用iOS系统提供的CoreBluetooth框架实现各种功能,并通过蓝牙Mesh技术实现设备间的直接通信。这将为用户带来更好的体验和更广泛的应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值