我开始使用蓝牙作为由iPhone控制的项目车Arduino。 问题是我尝试从我的iphone发送单个数据,但仔细观察扫描功能并不是很好的特点,我认为问题来自于此。 您是否有想法在其特有的UUID中找到相同的内容?
import UIKit
import CoreBluetooth
@IBOutlet weak var peripheralLabel: UILabel!
//713D0000503E4C75BA943148F18D941E
let BEAN_NAME = "Carduino"
let CBUUIDUuidTx = CBUUID(string: "713D0000-503E-4C75-BA94-3148F18D941E")
let CBUUIDUuIdRx = CBUUID(string: "713D0000-503E-4C75-BA94-3148F18D941E")
let UuidTx = "713D0000-503E-4C75-BA94-3148F18D941E"
let UuIdRx = "713D0000-503E-4C75-BA94-3148F18D941E"
var peripheralBLE: CBPeripheral?
var manager:CBCentralManager!
var myPeripheral:CBPeripheral!
var sendDataCharacteristic:CBCharacteristic!
var txCharacteristic: CBCharacteristic!
var rxCharacteristic: CBCharacteristic!
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil)
}
//Scan For devices
func centralManagerDidUpdateState(_ central: CBCentralManager) {
manager.scanForPeripherals(withServices: [CBUUIDUuidTx], options: nil)
}
//Connect to a Device
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
let device = (advertisementData as NSDictionary)
.object(forKey: CBAdvertisementDataLocalNameKey)
as? NSString
if device?.contains(BEAN_NAME) == true {
self.manager.stopScan()
self.myPeripheral = peripheral
self.myPeripheral.delegate = self
manager.connect(peripheral, options: nil)
peripheralLabel.text = "Connect to \(peripheral.name!)"
}
}
//Get Services
func centralManager(
_ central: CBCentralManager,
didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
//Get Characteristics
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
let thisService = service as CBService
if service.uuid == CBUUIDUuidTx {
peripheral.discoverCharacteristics(
nil,
for: thisService
)
}
print("This Service : \(thisService)")
}
}
func peripheral( _ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
let thisCharacteristic = characteristic as CBCharacteristic
if thisCharacteristic.uuid == CBUUIDUuidTx {
self.myPeripheral.setNotifyValue(
true,
for: thisCharacteristic
)
}
print("This Characteristic : \(thisCharacteristic)")
}
}
//Disconnect and Try Again
func centralManager(
_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
central.scanForPeripherals(withServices: nil, options: nil)
}
@IBAction func ledAction(_ sender: AnyObject) {
writeValue(data: "0x01")
}
func writeValue(data: String) {
if(myPeripheral != nil)
{
print(myPeripheral)
//happens for sure
var bytesData = [UInt8](data.utf8)
let writeData = NSData (bytes: &bytesData, length: bytesData.count)
myPeripheral.writeValue(writeData as Data, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
print(txCharacteristic)
}
}