2017-10-03 10 views
0

단일 주변 기기와 통신하는 간단한 BLE 앱을 만들고 있습니다. 휴대 전화가 중심 역할을합니다. 나는 테스트를 위해 주변기기로 사용하고있는 iPad를 가지고있다. 주변 장치를 시뮬레이트하기 위해 LightBlue 앱이 설치되어 있습니다. 주변 장치는이 형식의 데이터 문자열을 보내야합니다.블루투스를 통한 문자열 데이터 수신

TEM : 25.11 | HUM : 70 | PM10 : 43 | PM25 : 32

LightBlue에서 하나의 서비스로 빈 가상 주변 장치를 만들었습니다.

enter image description here

enter image description here

다음은 블루투스 연결 처리에 대한 내 코드입니다.

import UIKit 
import CoreBluetooth 

class ViewController: UIViewController { 

    fileprivate let serviceUUID = CBUUID(string: "19B10010-E8F2-537E-4F6C-D104768A1214") 
    fileprivate let characteristicUUID = CBUUID(string: "19B10011-E8F2-537E-4F6C-D104768A1214") 

    fileprivate var manager: CBCentralManager! 
    fileprivate var peripheral: CBPeripheral! 
    fileprivate var characteristic: CBCharacteristic! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     manager = CBCentralManager(delegate: self, queue: nil) 
    } 

    override func viewWillDisappear(_ animated: Bool) { 
     super.viewWillDisappear(animated) 
     stopScan() 
    } 

    fileprivate func startScan() { 
     manager.scanForPeripherals(withServices: [serviceUUID], options: nil) 
    } 

    fileprivate func stopScan() { 
     manager.stopScan() 
    } 

    fileprivate func disconnectFromDevice() { 
     guard let peripheral = peripheral else { return } 
     manager.cancelPeripheralConnection(peripheral) 
    } 

    fileprivate func restoreCentralManager() { 
     manager.delegate = self 
    } 

} 

// MARK: - CBCentralManagerDelegate 
extension ViewController: CBCentralManagerDelegate { 
    func centralManagerDidUpdateState(_ central: CBCentralManager) { 
     switch central.state { 
     case .unsupported: 
      print("Unsupported") 
     case .unauthorized: 
      print("Unauthorized") 
     case .poweredOn: 
      print("Powered On") 
      startScan() 
     case .resetting: 
      print("Resetting") 
     case .poweredOff: 
      print("Powered Off") 
     case .unknown: 
      print("Unknown") 
     } 
    } 

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { 
     print("Discovered \(String(describing: peripheral.name)) at \(RSSI)") 

     if peripheral.name == nil || peripheral.name == "" { 
      return 
     } 

     if self.peripheral == nil || self.peripheral.state == .disconnected { 
      stopScan() 

      self.peripheral = peripheral 
      central.connect(peripheral, options: nil) 
     } 
    } 

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { 
     peripheral.delegate = self 
     peripheral.discoverServices([serviceUUID]) 
    } 

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { 

     self.peripheral = nil 
     central.scanForPeripherals(withServices: nil, options: nil) 
    } 

    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { 
     self.peripheral = nil 
    } 

    func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { 
    } 
} 

// MARK: - CBPeripheralDelegate 
extension ViewController: CBPeripheralDelegate { 
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 
     guard let services = peripheral.services else { return } 
     print("No. of services: \(services.count)") 

     for service in services { 
      print(service.uuid) 
      if service.uuid == serviceUUID { 
       peripheral.discoverCharacteristics(nil, for: service) 
      } 
     } 
    } 

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 
     guard let characteristics = service.characteristics else { return } 

     for characteristic in characteristics { 
      print("characteristic: \(characteristic.uuid)") 
      if characteristic.uuid == characteristicUUID { 
       self.characteristic = characteristic 
       peripheral.setNotifyValue(true, for: characteristic) 
       peripheral.readValue(for: characteristic) 
      } 
     } 
    } 

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { 
     print(error) 
    } 

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {   
     if characteristic.uuid == characteristicUUID { 
      print("Got reply from: \(characteristic.uuid)") 
      print(characteristic.value) 
      if let data = characteristic.value, let string = String(data: data, encoding: String.Encoding.utf8) { 
       print(string) 
      } else { 
       print("No response!") 
      } 
     } 
    } 

} 

발견 및 연결 부분은 잘 작동합니다. 문제는 주변 장치에서 해당 데이터 문자열을받지 못한다는 것입니다.

peripheral(_:didUpdateValueFor:error:) 메서드가 실행됩니다. 나는 콘솔에서 출력 된 : 19B10011-E8F2-537E-4F6C-D104768A1214의 응답을 받았다. 그러나 characteristic.value을 인쇄하여 데이터가 있는지 확인하려고 시도하면 nil을 반환합니다.

내 코드에 문제가 있는지 확실하지 않습니다. 또는 LightBlue에서 주변 장치를 잘못 구성했습니다. LightBlue가 자동으로 데이터를 전송합니까? 나는 어떤 것도 볼 수 없다 단추 또는 아무데도 보낼 수 있습니다.

데모 프로젝트 here도 올렸습니다.

+0

새로운 가상 주변 장치 구성은 무엇입니까? –

+0

@ VarunNaharia LightBlue 앱에서? – Isuru

+0

예 동일하게 구성한 다음 문제를 찾으려고 노력합니다 –

답변

1

LightBlue 구성은 특정 특성에 대한 가치 만 쓸 수 있음을 나타냅니다.이 내용도 읽어야합니다.