[英]Unable to find BLE peripherals
I am new on Xcode and I wrote a little bit of code to discover and connect to BLE module (Adafruit Bluefruit LE). 我是Xcode的新手,我写了一些代码来发现并连接到BLE模块(Adafruit Bluefruit LE)。 However when scanning, nothing is found.
但是,在扫描时,什么也没找到。 Any help please ?
有什么帮助吗?
Here is my code 这是我的代码
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
//let BLUEFRUIT_SERVICE = "DFB0"
var centralManager: CBCentralManager!
var connectedPeripheral : CBPeripheral!
@IBAction func myButton(sender: UIButton) {
print(sender.tag)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
centralManager=CBCentralManager(delegate: self, queue: nil)
}
func scanForDevice () {
centralManager.scanForPeripheralsWithServices(nil, options: nil )
// I also tried with the following line, but I don't understand the use of BLUEFRUIT_SERVICE = "DFB0"
// centralManager.scanForPeripheralsWithServices([CBUUID(string: BLUEFRUIT_SERVICE)], options: nil)
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("\(peripheral.name!)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Central Manager delegates
func centralManagerDidUpdateState(central: CBCentralManager) {
print("central manager did updated started")
switch(central.state){
case .PoweredOff:
print("Power is OFF")
break
case .Resetting:
print("Resetting")
break
case .PoweredOn :
print("Power is ON");
break
case.Unauthorized:
print("Unauthorized")
break
case .Unsupported:
print("Unsupported")
break
default:
print("Unknown")
break
}
}
}
Are you able to see the device when you scan using an application like LightBlue? 使用LightBlue之类的应用程序进行扫描时,能够看到设备吗?
I ran into similar problems while trying to connect to a Bluno device. 尝试连接到Bluno设备时遇到了类似的问题。 Feel free to take a look at my code and see if it works for you.
随时查看我的代码,看看它是否对您有用。 It's currently hard coded to look for two particular Bluno devices, but you should be able to easily change it to connect if it finds the correct one.
目前很难对它进行编码以查找两个特定的Bluno设备,但是如果找到正确的设备,您应该可以轻松地将其更改为连接状态。
https://github.com/FredLoh/BluetoothResearchProject https://github.com/FredLoh/BluetoothResearchProject
Try the following code. 请尝试以下代码。 Note: You might have to update the device name (currently Bluno), as well as the DF80 and DF81 strings to whatever your device accepts.
注意:您可能必须将设备名称(当前为Bluno)以及DF80和DF81字符串更新为设备可接受的名称。 You might also have to wire this up correctly to whatever interface you are using.
您可能还必须将其正确连接到正在使用的任何接口。
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var connectedPeripheral: CBPeripheral!
@IBAction func myButton(sender: UIButton) {
print(sender.tag)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
centralManager=CBCentralManager(delegate: self, queue: nil)
}
func startScanning() {
print("Started Scanning!")
//Could add service UUID here to scan for only relevant services
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func sendMessage() {
let message = "5"
let data = message.dataUsingEncoding(NSUTF8StringEncoding)
if terminalChar != nil {
peripheral!.writeValue(data!, forCharacteristic: terminalChar, type: CBCharacteristicWriteType.WithoutResponse)
}
}
func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("Value was sent")
}
func discoverDevices() {
print("discovering devices")
centralManager.scanForPeripheralsWithServices(nil, options: nil)
}
func centralManagerDidUpdateState(central: CBCentralManager) {
print("Checking state")
switch (central.state) {
case .PoweredOff:
print("CoreBluetooth BLE hardware is powered off")
case .PoweredOn:
print("CoreBluetooth BLE hardware is powered on and ready")
bluetoothAvailable = true;
case .Resetting:
print("CoreBluetooth BLE hardware is resetting")
case .Unauthorized:
print("CoreBluetooth BLE state is unauthorized")
case .Unknown:
print("CoreBluetooth BLE state is unknown");
case .Unsupported:
print("CoreBluetooth BLE hardware is unsupported on this platform");
}
if bluetoothAvailable == true {
discoverDevices()
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
// print(peripheral)
let deviceName = "Bluno"
if let nameOfDeviceFound = peripheral.name {
if (nameOfDeviceFound == deviceName) {
print("Discovered \(deviceName)")
print("")
print(peripheral)
// Stop scanning
self.centralManager.stopScan()
print("Stopped Scanning")
// Set as the peripheral to use and establish connection
self.peripheral = peripheral
self.peripheral.delegate = self
self.centralManager.connectPeripheral(peripheral, options: nil)
}
else {
print("NOPE.EXE")
}
}
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
print("Did connect to peripheral.")
print("")
peripheral.delegate = self
peripheral.discoverServices([CBUUID(string: "DFB0")])
let state = peripheral.state == CBPeripheralState.Connected ? "yes" : "no"
print("Connected:\(state)")
}
// // Check if the service discovered is a valid IR Temperature Service
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
if(error != nil) {
print(error?.description)
}
for svc in peripheral.services! {
print("Service \(svc)\n")
print("Discovering Characteristics for Service : \(svc)")
peripheral.discoverCharacteristics([CBUUID(string: "DFB1")], forService: svc as CBService)
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if(error != nil) {
print(error?.description)
}
for characteristic in service.characteristics! {
if characteristic.UUID == CBUUID(string: "DFB1") {
self.terminalChar = (characteristic as CBCharacteristic)
peripheral.setNotifyValue(true, forCharacteristic: characteristic as CBCharacteristic)
// Send notification that Bluetooth is connected and all required characteristics are discovered
print("Found characteristic we were looking for!")
print(peripheral.readValueForCharacteristic(characteristic as CBCharacteristic))
}
}
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
print("Failed to connect to peripheral.")
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
print("CONNECTION WAS DISCONNECTED")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.