美文网首页iOS工程实践iOS开发杂货铺
智能交互(三) -  项目开发过程(蓝牙)

智能交互(三) -  项目开发过程(蓝牙)

作者: travin | 来源:发表于2016-08-24 14:12 被阅读227次

    如果你进来了,点下关注行不行_
    随说 : 本文结合自己做的这个项目来整理开发思路,这一篇着重 <蓝牙> 交互模块的
    关于蓝牙的框架,API等,可以google,也可以参考这一篇蓝牙常用开发步骤
    前期准备 :
    关于蓝牙基本的API详细解释,请参考这一篇蓝牙API

    1. 硬件商家提供的电路板
    2. 硬件商家提供的SDK包
    3. 硬件商家提供的电路板通讯协议

    1. 看懂通讯协议#

    我模拟了一份通讯协议的资料,凑合着看吧
    当然,实际情况的指令会多的多

    序号 : 指令的序号(没啥意义)
    指令名称 : 就是给指令定义一个名字,一般可以作为储存 本地的Key
    指令 : 实际操作电脑版接收的数据
    验证指令 : 根据一个验证算法得出的数据.
    备注 : 告诉你这个是干嘛的.

    2. 开始连接#

    将电路板通电,然后它就处于可被检测状态.
    作为App来说,首先需要检测iphone是否处于蓝牙开启状态

    2.1 创建Central管理器

    // CWLBluetoothEngine是一个继承NSObject类, 遵守<CBCentralManagerDelegate, CBPeripheralDelegate>代理
    // 创建Central管理器,这里我弄成单例
    +(CWLBluetoothEngine *)shareInstance
    {
        static dispatch_once_t pred = 0;
        __strong static CWLBluetoothEngine *_sharedObject = nil;
        dispatch_once(&pred, ^{
            _sharedObject = [[CWLBluetoothEngine alloc] init]; 
        });
        return _sharedObject;
    }
    

    2.2 检测蓝牙状态

    // 当创建Central管理器成功后,系统会自动调用该方法
    // 该方法的作用是检测蓝牙开启状态
    - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        
        // 具体又几种状态的,这里忽略
        switch ([central state])
        {
            case CBCentralManagerStatePoweredOn:
                 _state = @"正常打开了";
                 _bluetoothPowerOn = YES;
                // 注意这句, 调用CoreBluetooth框架 CBCentralManager类的 
                //scanForPeripheralsWithServices: options: 方法
                [self.centralManager scanForPeripheralsWithServices:nil options:nil];
                break;
            case CBCentralManagerStateUnknown:
            default:
                ;
        }
        NSLog(@"蓝牙此时状态: %@", _state);
    }
    
    

    2.3 确保蓝牙打开,才能扫描设备,扫描设备方法,在这里过滤你想连接的设备

    // 扫描到得设备,要需要过滤,扫描到设备后,会自动调用这个方法
    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
    {
           
        // cwl_bluetooth_fxy, 是硬件商定义的名字, 过滤找到的设备
        if ([peripheral.name isEqualToString:@"cwl_bluetooth_fxy"]) {
            // 正确的
            NSData * kcbData = [advertisementData valueForKey:@"kCBAdvDataManufacturerData"];
            NSLog(@"%@",kcbData);
            NSString * typeString = [[NSString stringWithHexData:kcbData] stringFromIndex:kcbData.length * 2 - 2];
             根据这个typeString ,我就能过滤操作,拿到peripheral之后,就可以连接准备
            if ([typeString isEqualToString:@"52"]) {
                if (!self.rightDeviceModel.peripheral) {
                   // 保存peripheral
                    self.rightDeviceModel.peripheral = peripheral;
                }
                
            }else{
                if (!self.leftDeviceModel.peripheral) {
                    self.leftDeviceModel.peripheral = peripheral;
                }
            }
            }
           
        }
    
    }
    
    

    2.4 这里主要注意, connectPeripheral: options:方法, 是连接蓝牙的方法

    // 自定义的一个方法,反正就是,连接成功就调用这里的方法.
    // 这里分左右,是因为业务需要,蓝牙产品分两个模块
    -(void)startconnectServiceWithType:(CWLSendModelType)senderType{
        if (senderType == CWLDataModelLeftType) {
             [self.centralManager connectPeripheral:self.leftDeviceModel.peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey :@YES}];
        }else{
             [self.centralManager connectPeripheral:self.rightDeviceModel.peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey :@YES}];
        }
    }
    
    

    2.5 连接成功,失败都又相应的回调方法,下面列出的时当成功连接的时候方法

    // 当连接成功后,会回调方法centralManager:didConnectPeripheral:。在这个方法中,你可以去记录当前的连接状态等数据。
    // self.leftDeviceModel.peripheral 已经在上面,搜索到设备的时候保存过了
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
    {
        if (peripheral == self.leftDeviceModel.peripheral) {
            self.leftDeviceModel.peripheral.delegate = self;
              // 寻找服务
              [self.leftDeviceModel.peripheral discoverServices:nil];
        }else{
            self.rightDeviceModel.peripheral.delegate = self;
              [self.rightDeviceModel.peripheral discoverServices:nil];
        }
    }
    

    2.6 当peripheral找到service之后, 就会就回调用peripheral: didDiscoverServices:

    // 当找到特定的 Service 以后,会回调的peripheral:didDiscoverServices:方法。Core Bluetooth 提供了CBService类来表示 service,找到以后,它们以数组的形式存入了当前 peripheral 的services属性中,你可以在当前回调中遍历这个属性。
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    {
        for (CBService *service in peripheral.services)
        {
            //  过滤服务, 找到自己相应的服务
            if ([service.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]])
            {
                   // 调用 discoverCharacteristics:   forService: 方法,寻找characteristics
                  [peripheral discoverCharacteristics:nil forService:service];
            }
        }
    }
    
    

    2.7 当然,寻找 characteristics 也有成功与失败的回调方法, 下面列出的时当发现characteristics时候的方法

    // 找到所有 characteristic 之后,回调peripheral:didDiscoverCharacteristicsForService:error:方法,此时 Core Bluetooth 提供了CBCharacteristic类来表示characteristic。可以通过以下代码来遍历找到的 characteristic :
    
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
    {
    
        if (peripheral == self.leftDeviceModel.peripheral) {
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF5"]]) {
                self.leftDeviceModel.characteristcs = characteristic;
                NSLog(@"写入");
            }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]){
                 NSLog(@"通知");
                [self.leftDeviceModel.peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
               !self.connectSuccessWithCWLSendModelType ? : self.connectSuccessWithCWLSendModelType (CWLDataModelLeftType);
        }else{
            for (CBCharacteristic *characteristic in service.characteristics) {
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF5"]]) {
                    // 将characteristic保存为成员变量
                    self.rightDeviceModel.characteristcs = characteristic;
                    NSLog(@"写入");
                }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]){
                    NSLog(@"通知");
                    
                    // 监听这个通知
                    [self.rightDeviceModel.peripheral setNotifyValue:YES forCharacteristic:characteristic];
                }
            }
            !self.connectSuccessWithCWLSendModelType ? : self.connectSuccessWithCWLSendModelType (CWLDataModelRightType);
        }
    }
    
    

    2.8 connectSuccessWithCWLSendModelType 这个block 连接之后

    [self.blueToothEngine setConnectSuccessWithCWLSendModelType:^(CWLSendModelType obj) {
             if (obj == CWLDataModelLeftType) {
                [ws.blueToothEngine startconnectServiceWithType:CWLDataModelRightType];
             }else{
                 // 连接成功,就需要停止扫描
                 [ws.blueToothEngine stopScan]; 
                 
                 //  这个方法发送了一些指令, 电路板接收到指令. 
                 [ws countModel];
    
                  NSLog(@"连接成功了")
             }
         }];
    
    

    3. 传输数据#

    characteristic 有几种属性
    Read : 只读
    Write Without Response : 写数据不接收回执
    Write : 只写
    Notify : 通知(不需要对方回复)
    Indicate : 通知(需要回复)

    这个项目中,只用到了write 与 notify

    - (void)countModel{
        NSString *  tureConnectMessage = [@"A502" stringCrc8String]; 
        // tureConnectMessage 的值, 经过Crc转化后, 就是 @"A502A8"
        NSData * data = [tureConnectMessage stringHexToBytesData];
        [self.blueToothEngine sendWriteData:data WithType:CWLDataModelLeftType];
        [self.blueToothEngine sendWriteData:data WithType:CWLDataModelRightType];
    }
    
    // sendWriteData: WithType: 实际调用了writeValue: forCharacteristic: type:方法, 写入数据
    - (void)sendWriteData:(NSData *)data WithType:(CWLSendModelType)senderType{
        if (senderType == CWLDataModelLeftType) {
            if (self.leftDeviceModel.peripheral) {
                if(self.leftDeviceModel.characteristcs){
                    // 写入数据,注意, 数据的格式,请严格按照硬件商提供的协议规范,.
                    // 我这里的data是  A502A8  A5是数据协议头,  02 是开关命令, A8是CRR算法验证后得出的数值, 
                    // 按照规范传输过去,硬件收到后, 就回关闭电路板电源了. 
                    [self.leftDeviceModel.peripheral writeValue:data forCharacteristic:self.leftDeviceModel.characteristcs type:CBCharacteristicWriteWithoutResponse];
                }
            }
        }else{
            if (self.rightDeviceModel.peripheral) {
                if(self.rightDeviceModel.characteristcs){
                    [self.rightDeviceModel.peripheral writeValue:data forCharacteristic:self.rightDeviceModel.characteristcs type:CBCharacteristicWriteWithoutResponse];
                }
            }
     
        }
    }
    
    

    接收电路板回来的信息.

    //获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    {
       
        // 如代码所示, 当接收到电路板的信息的时候, 执行dataReportingBluetooth这个block  
        // 将接收到得通知信息characteristic.value  传到block
        if (peripheral == self.leftDeviceModel.peripheral) {
            
            !self.dataReportingBluetooth ? : self.dataReportingBluetooth([NSString stringWithHexData:characteristic.value],@"");
        }else{
             !self.dataReportingBluetooth ? : self.dataReportingBluetooth(@"",[NSString stringWithHexData:characteristic.value]);
        }
        
    }
    
    // 在dataReportingBluetooth这个block中
         [self.blueToothEngine setDataReportingBluetooth:^(NSString *objLeft, NSString *objRight) {
             
             // objLeft,objRight 就会以字符窜的形式传过来, 这里可以执行获取字符窜之后的操作.
         }];
    
    

    相关文章

      网友评论

      • 经天纬地:关于characteristic 有几种属性这个不懂,这几个属性有什么作用,看头文件这些属性是只读的。
      • 蚯小麦:最近在做蓝牙,求demo:smiley:

      本文标题:智能交互(三) -  项目开发过程(蓝牙)

      本文链接:https://www.haomeiwen.com/subject/fuvsdttx.html