iOS蓝牙开发,数据发送遇到问题


小弟目前在做iOS的蓝牙开发,用CoreBluetooth框架,目前从非iOS外设处接收数据已经没有问题了,但是发送数据一直不成功,外设收不到数据,用lightblue却可以正常收发数据,想问问大家是什么原因。

谢谢!

蓝牙模块的代码如下


 #define kServiceUUID @"FFE0"
#define kCharacteristicUUID @"FFE1"
#import "BTManager.h"
@interface BTManager()
@property (strong,nonatomic) NSMutableArray *peripherals;   //连接的外围设备
@property (nonatomic, strong) CBCharacteristic *writeCharacteristic;
@end
@implementation BTManager

#pragma mark - Public Methods
- (void)writeToPeripheral:(NSString *)dataString {
    NSLog(@"writeToPeripheral:%@",dataString);
    if(_writeCharacteristic == nil){
        NSLog(@"writeCharacteristic 为空");
        return;
    }
    NSData *value = [self dataWithHexstring:dataString];
    NSLog(@"十六进制:%@",value);
    [_peripheral writeValue:value forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
    NSLog(@"已经向外设%@的特征值%@写入数据",_peripheral.name,_writeCharacteristic.description);
}

- (void)scan{                         options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];
    [manager scanForPeripheralsWithServices:nil
                                    options:nil];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        manager.delegate = self;
    }
    return self;
}
#pragma mark - CBCentralManager Delegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString * state = nil;

    switch ([central state])
    {
        case CBCentralManagerStateUnsupported:
            state = @"StateUnsupported";
            break;
        case CBCentralManagerStateUnauthorized:
            state = @"StateUnauthorized";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"PoweredOff";
            break;
        case CBCentralManagerStatePoweredOn:
            state = @"PoweredOn";
            break;
        case CBCentralManagerStateUnknown:
            state = @"unknown";
            break;
        default:
            break;
    }
    NSLog(@"手机状态:%@", state);
}
// 发现外设后
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral
     advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    NSString *str = [NSString stringWithFormat:@"发现外设:%@ rssi:%@, UUID:%@ advertisementData: %@ ", peripheral, RSSI, peripheral.identifier.UUIDString, advertisementData];
    NSLog(@"%@",str);
    [_peripherals addObject:peripheral];

    if ([peripheral.name isEqualToString:@"BT"]) {
        [manager stopScan];
        [manager connectPeripheral:peripheral options:nil];
        NSLog(@"连接外设:%@",peripheral.description);
        self.peripheral = peripheral;
    }
}
// 连接到外设后
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"已经连接到:%@", peripheral.description);
    peripheral.delegate = self;
    [central stopScan];
    [peripheral discoverServices:nil];
}
// 连接失败后
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

}
// 断开外设
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
}
#pragma mark - CBPeripheral Delegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    NSLog(@"didDiscoverServices");
    if (error) {
        NSLog(@"搜索服务%@时发生错误:%@", peripheral.name, [error localizedDescription]);
        return;
    }
    for (CBService *service in peripheral.services) {
        //发现服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
            NSLog(@"发现服务:%@", service.UUID);
            [peripheral discoverCharacteristics:nil forService:service];
            break;
        }
    }
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    if (error) {
        NSLog(@"搜索特征%@时发生错误:%@", service.UUID, [error localizedDescription]);
        return;
    }
    NSLog(@"服务:%@",service.UUID);
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"特征:%@",characteristic);
        //发现特征
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
            NSLog(@"监听特征:%@",characteristic);//监听特征
            _writeCharacteristic = characteristic;
            [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error)
    {
        NSLog(@"更新特征值%@时发生错误:%@", characteristic.UUID, [error localizedDescription]);
        return;
    }
    // 收到数据
    NSLog(@"%@",[self hexadecimalString:characteristic.value]);
}
#pragma mark - NSData and NSString

//将传入的NSData类型转换成NSString并返回
- (NSString*)hexadecimalString:(NSData *)data{
    NSString* result;
    const unsigned char* dataBuffer = (const unsigned char*)[data bytes];
    if(!dataBuffer){
        return nil;
    }
    NSUInteger dataLength = [data length];
    NSMutableString* hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    for(int i = 0; i < dataLength; i++){
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
    }
    result = [NSString stringWithString:hexString];
    return result;
}
//将传入的NSString类型转换成NSData并返回
- (NSData*)dataWithHexstring:(NSString *)hexstring{
    NSData* aData;
    return aData = [hexstring dataUsingEncoding: NSASCIIStringEncoding];
}
@end

蓝牙 ios bluetooth

御坂09489 10 years, 5 months ago

用lightblue看看你往蓝牙发送数据的那个Characteristics是什么,还是说你读取和发送用得是同一个Characteristics?

ヤ﹏喵ら、m answered 10 years, 5 months ago

Your Answer