欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 蓝牙/BLE4.0

程序员文章站 2024-03-24 23:58:22
...
//
//  ViewController.m
//  BLE4.0
//
//  Created by djlovettt on 2017/5/18.
//  Copyright © 2017年 djlovettt. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (nonatomic, strong) CBCentralManager *mgr; /** *管理者 */
@property(nonatomic,strong)NSMutableArray *peripheralsArr; /** 存储扫描到的设备 */
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    _peripheralsArr = [NSMutableArray new];
}

/**
 检测设备的蓝牙状态
 */
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBManagerStatePoweredOff:
            NSLog(@"设备未开启蓝牙!");
            break;
        case CBManagerStatePoweredOn:
            NSLog(@"设备蓝牙已开启!");
            //开始扫描设备
            [self.mgr scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBManagerStateUnsupported:
            NSLog(@"设备不支持蓝牙!");
            break;
        default:
            break;
    }
}

/**
 扫描到蓝牙设备的代理方法
 @param RSSI 信号强度
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    if (![self.peripheralsArr containsObject:peripheral]) {
        [self.peripheralsArr addObject:peripheral];
        //扫描到的全部蓝牙设备
        NSLog(@"Scan BLE Devices === %@",self.peripheralsArr);
    }
    //匹配出需要连接的设备,进行连接
    for (CBPeripheral *peripheral in self.peripheralsArr) {
        NSLog(@"peripheral.name === %@",peripheral.identifier.UUIDString);
        if ([peripheral.identifier.UUIDString isEqualToString:@"设备标识码"]) {
            [self connect:peripheral];
        }
    }
}

/**
 连接设备的方法
 */
-(void)connect:(CBPeripheral*)peripheral {
    if (!peripheral) {
        NSLog(@"未检索到该设备!");
    } else {
        [self.mgr connectPeripheral:peripheral options:nil];
    }
}

/**
 设备连接成功
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"设备已连接成功!");
}

/**
 设备连接失败
 */
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"连接外围设备失败!");
}

/**
 搜索到蓝牙设备的服务信息
 */
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    NSLog(@"peripheral.services === %@",peripheral.services);
    for (CBService *serive in peripheral.services) {
        if ([serive.UUID.UUIDString isEqualToString:@"设备的某个服务码"]) {
            //遍历到需要的服务之后开始扫描特征值
            [peripheral discoverCharacteristics:nil forService:serive];
        }
    }
}

/**
 扫描设备特征值
 */
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    NSLog(@"service.characteristics === %@",service.characteristics);
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        
        if ([characteristic.UUID.UUIDString isEqualToString:@"设备的某个服务码"]) {
            NSLog(@"%lu",             (unsigned long)characteristic.properties);
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            [peripheral readValueForCharacteristic:characteristic];
            
            //读取特征值
            NSString *value=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
            NSLog(@"读取到特征值:%@",value);
        }
        else if ([characteristic.UUID.UUIDString isEqualToString:@"设备的某个服务码"]) {
            NSLog(@"%lu",(unsigned long)characteristic.properties);
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            [peripheral readValueForCharacteristic:characteristic];
            
            //读取特征值
            NSString *value=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
            NSLog(@"读取到特征值:%@",value);
            
            //需要写入的数据
            NSString *str = [NSString stringWithFormat:@"需要交互的数据"];
            NSData  *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }
    }
}

/**
 收到特征值更新
 */
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"收到特征更新通知...%@", characteristic);
    if(characteristic.value){
        NSString *value=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        NSLog(@"读取到特征值:%@",value);
    }
    if (error) {
        NSLog(@"更新通知状态时发生错误,错误信息:%@",error.localizedDescription);
    }
}

//读取数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"%@", characteristic);
    if(characteristic.value){
        NSString *value=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        NSLog(@"读取到特征值:%@",value);
        
        int i=0;
        [characteristic.value getBytes:&i length:2];
        NSLog(@"%d",i);
    }
    if (error) {
        NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);
        return;
    }
}

//写操作完成调用
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"---didWriteValueForCharacteristic-----%@", characteristic);
    NSString *value=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    NSLog(@"读取到特征值:%@",value);
}

/**
 断开与设备的链接
 */
-(void)disConnect:(CBPeripheral *)peripheral {
    if (peripheral != nil) {
        [_mgr cancelPeripheralConnection:peripheral];
    } else {
        NSLog(@"断开连接失败,未检索到设备!");
    }
}

@end