iOS - 蓝牙开门智能门锁

蓝牙的实现原理网上很多 在此就不一一描述了 有需要的可以看以下的文章学习
在ios 的开发中iBeacon和BLE的区别
iBeacon介绍
iOS蓝牙空中升级(固件升级)

本文主要是写实现过程:
github 上完整Demo地址,大家可以下载看看:ZYiBeacon

项目需求:
业主反馈拿出门卡开门这一动作繁琐,想要手机蓝牙连接门口机进行摇一摇或者点击对应的大门,实现开门功能。

实现步骤:

1.  扫描蓝牙设备,将设备列表展示
2.  连接其中一台设备
3.  连接成功后,向外设发送一串开锁指令
4.  发送成功后,断开和外设的连接

代码实现思路:
1. 需要蓝牙管理者mgr 管理者可以扫描外围设备 遵守CBCentralManagerDelegate协议
2. mgr扫描到外设,与外设进行连接断开连接信息交流等一系列反馈回调 需要遵循CBPeripheralDelegate协议

主要实现:
封装一套管理类,在工程的任何地方 只要shareSYSearchPeriphalsMgr 就可以得到管理者

+ (SYSearchPeriphalsMgr *) shareSYSearchPeriphalsMgr{
    static SYSearchPeriphalsMgr * mgr;
    if (mgr == nil) {
        mgr = [[SYSearchPeriphalsMgr alloc]init];
        dispatch_queue_t centralQueue = dispatch_queue_create("no.nordicsemi.ios.nrftoolbox", DISPATCH_QUEUE_SERIAL);
        mgr.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:mgr queue:centralQueue];

        mgr.peripherals = [NSMutableArray array];
        mgr.orinPeripherals = [NSMutableArray array];
        mgr.filter = NO;

        //初始化
        mgr->UART_Service_UUID = [CBUUID UUIDWithString:uartServiceUUIDString];
        mgr->UART_TX_Characteristic_UUID = [CBUUID UUIDWithString:uartTXCharacteristicUUIDString];
        mgr->UART_RX_Characteristic_UUID = [CBUUID UUIDWithString:uartRXCharacteristicUUIDString];

        [mgr starScan];
    }
    return mgr;
}

是否扫描设备:

/** 是否扫描设备*/
- (int) scanForPeripherals:(BOOL)enable{
    if (self.bluetoothManager.state != CBManagerStatePoweredOn) {
        return -1;
    }

    dispatch_async(dispatch_get_main_queue(), ^{

        if (enable) {
            NSDictionary * options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],CBCentralManagerScanOptionAllowDuplicatesKey, nil];
            if (self.filterUUID != nil) {
                [self.bluetoothManager scanForPeripheralsWithServices:@[self.filterUUID] options:options];
            }
            else{
                [self.bluetoothManager scanForPeripheralsWithServices:nil options:options];
            }

            self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        }
        else{
            [self.timer invalidate];
            self.timer = nil;

            [self.bluetoothManager stopScan];
        }

    });
    return 0;
}

连接设备:

[self.bluetoothManager cancelPeripheralConnection:self.bluetoothPeripheral];

// 通过UART服务查看是否是自己的蓝牙设备 是的话建立连接后 则可以向设备发送信息 不然设备会接收不到
// 设备接收到信息后,经过处理,验证成功后则开锁
/** 设备特征值*/
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(nonnull CBService *)service error:(nullable NSError *)error{
    NSLog(@"向设备发送开锁指令 === %@",peripheral.name);
    if (error)
    {
        NSLog(@"Characteristics discovery failed");
        NSLog(@"error : %@",error);

    }
    else
    {
        NSLog(@"Characteristics discovered");

        if ([service.UUID isEqual:UART_Service_UUID]) {
            CBCharacteristic *txCharacteristic = nil;


            for (CBCharacteristic *characteristic in service.characteristics)
            {
                NSLog(@"Characteristics ==== %@ ",characteristic);
                if ([characteristic.UUID isEqual:UART_TX_Characteristic_UUID])
                {
                    NSLog(@"TX Characteristic found");
                    txCharacteristic = characteristic;
                }
                else if ([characteristic.UUID isEqual:UART_RX_Characteristic_UUID])
                {
                    NSLog(@"RX Characteristic found");
                    self.uartRXCharacteristic = characteristic;


                    // 3. 向设备发送开锁指令
                    // 发送数据
                    [self send:@"1234567" withByteCount:7];
                    NSString *command = self.sendText;
                    [self send:command withByteCount:20];

                    NSLog(@"向设备发送开锁指令 === %@",command);

                    // 4. 失去设备连接
                    [self disconnectDevice];

                }
            }
        }
    }

}

你可能感兴趣的:(iOS笔记)