6

Tôi đang sử dụng khung công tác CoreBlueTooth để viết vào một trong những đặc điểm có thể ghi của Ngoại vi. Tôi đang thực hiện "didWriteValueForCharacteristic: error:" đại biểu ở trung tâm luôn trả lại cho tôi lỗi dưới đây. Mặc dù tôi đã nhận được dữ liệu trên thiết bị ngoại vi của mình.CoreBlueTooth: Nhận lỗi ngay cả khi dữ liệu được ghi vào các đặc điểm ghi được

Error Domain=CBErrorDomain Code=0 "Unknown error." UserInfo=0x166762e0 {NSLocalizedDescription=Unknown error.} 

Trong mã của tôi, self.data là từ điển NSD với 3 khóa và giá trị.

// Central 

- (void)centralManagerDidUpdateState:(CBCentralManager *)iCentral { 
    if (iCentral.state != CBCentralManagerStatePoweredOn) { 
     return; 
    } 

    [self.centralManager scanForPeripheralsWithServices:self.peripheralServices options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES}]; 
} 


- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)iPeripheral advertisementData:(NSDictionary *)iAdvertisementData RSSI:(NSNumber *)iRSSI { 
    if (self.discoveredPeripheral != iPeripheral) { 
     // Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it 
     self.discoveredPeripheral = iPeripheral; 

     // Connect to the discovered peripheral 
     [self.centralManager connectPeripheral:iPeripheral options:nil]; 
    } 
} 

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)iPeripheral advertisementData:(NSDictionary *)iAdvertisementData RSSI:(NSNumber *)iRSSI { 
    if (self.discoveredPeripheral != iPeripheral) { 
     // Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it 
     self.discoveredPeripheral = iPeripheral; 

     // Connect to the discovered peripheral 
     [self.centralManager connectPeripheral:iPeripheral options:nil]; 
    } 
} 


// We've connected to the peripheral, now we need to discover the services and characteristics to find the 'writeable' characteristic. 
- (void)centralManager:(CBCentralManager *)iCentral didConnectPeripheral:(CBPeripheral *)iPeripheral { 
    // Stop scanning 
    [self.centralManager stopScan]; 

    // Make sure we get the discovery callbacks 
    iPeripheral.delegate = self; 

    // Search only for services that match our UUID 
    [iPeripheral discoverServices:self.peripheralServices]; 
} 


- (void)peripheral:(CBPeripheral *)iPeripheral didDiscoverServices:(NSError *)iError { 
    if (iError) { 
     [self cleanup]; 
     return; 
    } 

    // Loop through the newly filled peripheral.services array, just in case there's more than one. 
    for (CBService *service in iPeripheral.services) { 
     [iPeripheral discoverCharacteristics:@[self.writeableCharactersticsUUID] forService:service]; 
    } 
} 


// Write the data into peripheral's characterstics 
- (void)peripheral:(CBPeripheral *)iPeripheral didDiscoverCharacteristicsForService:(CBService *)iService error:(NSError *)iError { 
    if (iError) { 
     [self cleanup]; 

     return; 
    } 

    // Find out the writable characterstics 
    for (CBCharacteristic *characteristic in iService.characteristics) { 
     if ([characteristic.UUID isEqual:self.writeableCharactersticsUUID]) { 
      NSData *dataToWrite = [NSJSONSerialization dataWithJSONObject:self.data options:0 error:nil]; 
      NSInteger dataSize = [[NSByteCountFormatter stringFromByteCount:dataToWrite.length countStyle:NSByteCountFormatterCountStyleFile] integerValue]; 
      if (dataSize > 130) { 
       NSLog(@"Cannot send more than 130 bytes"); 
       return; 
      } 

      [self.discoveredPeripheral writeValue:dataToWrite forCharacteristic:self.centralWriteableCharacteristic type:CBCharacteristicWriteWithResponse]; 

      break; 
     } 
    } 
} 


- (void)peripheral:(CBPeripheral *)iPeripheral didWriteValueForCharacteristic:(CBCharacteristic *)iCharacteristic error:(NSError *)iError { 
    NSLog(@"Error = %@", iError); 
} 


- (void)cleanup { 
    // Don't do anything if we're not connected 
    if (self.discoveredPeripheral.state != CBPeripheralStateConnected) { 
     return; 
    } 

    // If we've got this far, we're connected, but we're not subscribed, so we just disconnect 
    [self.centralManager cancelPeripheralConnection:self.discoveredPeripheral]; 
} 


// Peripheral 

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)iPeripheral { 
    if (iPeripheral.state != CBPeripheralManagerStatePoweredOn) { 
     return; 
    } 

    CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:iCID properties:CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsWriteable]; 

    CBMutableService *writableService = [[CBMutableService alloc] initWithType:iServiceId primary:YES]; 
    writableService.characteristics = @[characteristic]; 

    //[self.peripheralManager removeAllServices]; 
    [self.peripheralManager addService:writableService]; 
    [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[iServiceId]}]; 
} 

- (void)peripheralManager:(CBPeripheralManager *)iPeripheral didReceiveWriteRequests:(NSArray *)iRequests { 
    CBATTRequest *aRequest = iRequests[0]; 
    NSData *aData = aRequest.value; 
    NSDictionary *aResponse = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:nil]; 

    NSLog(@"Received Data = %@", aResponse); 
} 

Trả lời

9

Tôi đã tìm ra. Vấn đề là với loại Đặc điểm. Thay vì "CBCharacteristicWriteWithResponse", tôi đã sử dụng "CBCharacteristicWriteWithoutResponse" và nó hoạt động.

Tôi đã làm điều này sau khi đọc bài viết này:

writeValue forCharacteristic writeType, chức năng này là chức năng chính cho văn bản cho một đặc tính trên một thiết bị. thuộc tính writeType được thiết lập để viết mà không có phản hồi hoặc ghi với đáp ứng. Khi viết với phản hồi được sử dụng, tất cả ghi vào thiết bị ngoại vi được lưu trữ trong khi thiết bị iOS đang chờ nhận phản hồi ok và gọi lại. Khi viết không có phản ứng được sử dụng, dữ liệu sẽ không được lưu trữ. Điều này rất quan trọng khi sử dụng những thứ cần độ trễ thấp, như một chiếc xe RC hoặc máy bay trực thăng, vv khi sử dụng viết với phản hồi, thiết bị iOS đôi khi có thể tụt lại phía sau, điều này không thực hiện được phản hồi tuyệt vời… Đối với mỗi ghi lại hàm gọi lại didWriteCharacteristic.

+0

Tôi đã có chính xác cùng một thời gian và thời gian vấn đề này một lần nữa (với yêu cầu thay đổi firmware). Tôi cần phải Google nó mỗi lần :) – SJoshi

+0

Tôi đã thực hiện thay đổi tương tự nhưng tôi vẫn không nhận được bất kỳ cuộc gọi nào về Kết thúc ngoại vi. Tôi đang tìm bất kỳ bản cập nhật nào trong phương thức PeripheralManager của 'didReceiveWriteRequests'. tôi có đúng không – Mrug

2

Để điều này ở đây cho những người khác, nhưng câu trả lời của OP không chính xác.

Sai lầm đó đã được thực hiện ở đây là ông không cập nhật đặc trưng của mình trong chức năng này:

- (void)peripheralManager:(CBPeripheralManager *)iPeripheral didReceiveWriteRequests:(NSArray *)iRequests { 
    CBATTRequest *aRequest = iRequests[0]; 
    NSData *aData = aRequest.value; 
    NSDictionary *aResponse = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:nil]; 


    NSLog(@"Received Data = %@", aResponse); 
} 

Vì không có đặc trưng được tìm thấy sẽ được cập nhật, hệ điều hành giả một cái gì đó đã đi sai và tạo ra một lỗi.

CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:iCID properties:CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsWriteable]; 

Mã này là thực sự thiết lập để có thể ghi đặc trưng với một phản ứng, enum mà xác định không trả lời là:

CBCharacteristicPropertyWriteWithoutResponse 

Hope this helps những người vấp ngã về vấn đề này.

4

ghi này cho hậu thế: Bạn phải trả lời để ngăn chặn các lỗi:

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests 
{ 
    // respond! 
    [peripheral respondToRequest:[requests objectAtIndex:0] withResult:CBATTErrorSuccess]; 
+0

Không hoạt động. vẫn còn dữ liệu getitng Null –

+0

Hoạt động tốt. Cảm ơn! – flame3