Ios Swift 3数据未从iPhone应用程序发送到蓝牙设备
我正在尝试将数据从iPhone发送到蓝牙设备,该设备连接到Arduino。我知道蓝牙设备工作正常,因为我使用了应用程序nRF connect,并从那里向Arduino读取的蓝牙发送数据 我认为我的应用程序的组织方式产生了一些问题。 目前有三个视图控制器 第一个视图控制器是一个没有太多内容的主页屏幕。您可以从主页连接第二个视图控制器和第三个视图控制器。 第二个视图控制器是蓝牙的连接屏幕 第三个视图控制器是一个带有按钮的操作屏幕 第二个视图控制器是一个带有扫描选项的表视图,用于查找可用的蓝牙设备。我使用以下代码:Ios Swift 3数据未从iPhone应用程序发送到蓝牙设备,ios,swift,bluetooth,hm-10,Ios,Swift,Bluetooth,Hm 10,我正在尝试将数据从iPhone发送到蓝牙设备,该设备连接到Arduino。我知道蓝牙设备工作正常,因为我使用了应用程序nRF connect,并从那里向Arduino读取的蓝牙发送数据 我认为我的应用程序的组织方式产生了一些问题。 目前有三个视图控制器 第一个视图控制器是一个没有太多内容的主页屏幕。您可以从主页连接第二个视图控制器和第三个视图控制器。 第二个视图控制器是蓝牙的连接屏幕 第三个视图控制器是一个带有按钮的操作屏幕 第二个视图控制器是一个带有扫描选项的表视图,用于查找可用的蓝牙设备。我
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, UITableViewDataSource, UITableViewDelegate
{
//MARK: Variables
//central manager
var manager: CBCentralManager?
//peripheral manager
var peripheral: CBPeripheral?
//HM-10 service code
let HMServiceCode = CBUUID(string: "0xFFE0")
//HM-10 characteristic code
let HMCharactersticCode = CBUUID(string: "0xFFE1")
//array to store the peripherals
var peripheralArray:[(peripheral: CBPeripheral, RSSI: Float)] = []
//for timing..obvs
var timer: Timer!
//MARK: IBOutlets
//if cancel is pressed go back to homepage
@IBAction func cancelButton(_ sender: Any)
{
performSegue(withIdentifier: "segueBackwards", sender: nil)
}
//this is for the tableview so that you can reference it
@IBOutlet var tableView: UITableView!
//allow for disabling the scanning button whilst scanning
@IBOutlet var scanningButton: UIBarButtonItem!
//loads the centralmanager delegate in here
override func viewDidLoad()
{
manager = CBCentralManager(delegate: self, queue: nil)
tableView.delegate = self
tableView.dataSource = self
super.viewDidLoad()
if(peripheral != nil)
{
disconnectPeripheral()
}
}
//nothing
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//MARK: cancel any preexisting connection - this still needs to be done
func disconnectPeripheral()
{
manager?.cancelPeripheralConnection(peripheral!)
}
//MARK: Bluetooth central
//required centralmanager component. Text for what power state currently is
func centralManagerDidUpdateState(_ central: CBCentralManager)
{
var consoleMsg = ""
switch (central.state)
{
case.poweredOff:
consoleMsg = "BLE is Powered Off"
scanningButton.isEnabled = false
alert()
case.poweredOn:
consoleMsg = "BLE is Powered On"
scanningButton.isEnabled = true
case.resetting:
consoleMsg = "BLE is resetting"
case.unknown:
consoleMsg = "BLE is in an unknown state"
case.unsupported:
consoleMsg = "This device is not supported by BLE"
case.unauthorized:
consoleMsg = "BLE is not authorised"
}
print("\(consoleMsg)")
}
//MARK: Alert if Bluetooth is not turned on
func alert ()
{
//main header
let title = "Bluetooth Power"
//the little debrief below the main title
let message = "Please turn on Bluetooth to use this app"
//text in the text box
let text = "OK"
//this says what the title and message is
let alert = UIAlertController(title: title, message: message , preferredStyle: UIAlertControllerStyle.alert)
//add button for the answer
let okayButton = UIAlertAction(title: text, style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(okayButton)
//show the alert
present(alert, animated: true, completion: nil)
print("said ok on button to turning on bluetooth")
}
//MARK: Connection to bluetooth
//once scanned this will say what has been discovered - add to peripheralArray
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber)
{
for existing in peripheralArray
{
if existing.peripheral.identifier == peripheral.identifier {return}
}
//adding peripheral to the array
let theRSSI = RSSI.floatValue
peripheralArray.append(peripheral: peripheral, RSSI: theRSSI)
peripheralArray.sort { $0.RSSI < $1.RSSI }
print("discovered peripheral")
tableView.reloadData()
print("There are \(peripheralArray.count) peripherals in the array")
}
//create a link/connection to the peripheral
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)
{
peripheral.discoverServices(nil) //may need to remove this not sure it does much
print("connected to peripheral")
}
//disconnect from the peripheral
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?)
{
print("disconnected from peripheral")
stopScanning()
}
//if it failed to connect to a peripheral will tell us (although not why)
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?)
{
print("failed to connect to peripheral")
stopScanning()
}
//MARK: scanning
//press scan button to initiate scanning sequence
@IBAction func scanButton(_ sender: Any)
{
startTimer()
}
//start scanning for 5 seconds
func startTimer()
{
//after 5 seconds this goes to the stop scanning routine
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.stopScanning), userInfo: nil, repeats: true)
print("Start Scan")
manager?.scanForPeripherals(withServices: [HMServiceCode], options: nil)
scanningButton.isEnabled = false
}
//stop the scanning and re-enable the scan button so you can do it again
func stopScanning()
{
timer?.invalidate()
print("timer stopped")
manager?.stopScan()
print("Scan Stopped")
print("array items are: \(peripheralArray)")
print("peripheral items are: \(peripheral)")
print("manager items are: \(manager)")
scanningButton.isEnabled = true
}
//MARK: Table View
//number of sections the table will have
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
//number of rows each section of the table will have
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return peripheralArray.count
}
//the way the data will be displayed in each row for the sections
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let BluetoothNaming = peripheralArray[indexPath.row].peripheral.name
cell.textLabel?.text = BluetoothNaming
return cell
}
//what happens when we select an item from the bluetooth list
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
//tableView.deselectRow(at: indexPath, animated: true)
stopScanning()
peripheral = peripheralArray[(indexPath as NSIndexPath).row].peripheral
print ("connecting to peripheral called \(peripheral)")
//store the name of the connected peripeheral
let connectedPeripheral = peripheral
manager?.connect(connectedPeripheral!, options: nil)
performSegue(withIdentifier: "segueBackwards", sender: nil)
}
//MARK: change label name
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "segueBackwards"
{
if let indexPath = self.tableView.indexPathForSelectedRow
{
//storing the name of the peripheral and then saving to send to Homepage
let peripheral = peripheralArray[indexPath.row].peripheral.name
let vc = segue.destination as! HomepageViewController
vc.selectedName = peripheral
//this is to unselect the row in the table
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
//MARK: end
}
我认为部分问题在于外围服务和特性没有连接到中央?这听起来对吗?
目前,我希望将值75发送到蓝牙,然后Arduino可以读取该值。
我对外围代理做了什么错事吗?
我需要做什么才能使它能够发送数据
谢谢,Larme说得对。创建一个singleton类来管理所有核心蓝牙操作。然后,在任意位置创建该单例的实例
我在这里创建了一个具有核心蓝牙功能的singleton类示例。@Larme是对的。创建一个singleton类来管理所有核心蓝牙操作。然后,在任意位置创建该单例的实例
我在这里创建了一个具有核心蓝牙功能的singleton类示例。您的Characterics UUID是错误的
if characteristic.uuid == CBUUID(string: "FFE1")
特性=FFFE0
如果characteristics.uuid==CBUUID(字符串:“FFE0”)您的characteristics uuid错误,请更改此->
if characteristic.uuid == CBUUID(string: "FFE1")
特性=FFFE0
更改此设置->如果characteristic.uuid==CBUUID(字符串:“FFE0”)
使用单例管理蓝牙部件。然后,所有ViewController都可以访问它。您是否有机会扩展此功能?请使用单例管理您的蓝牙部件。然后,所有的ViewController都可以访问它。你有没有可能扩展它?嗨,Alex,谢谢你的githb链接。我对斯威夫特相当陌生,我会怎么处理这个单身汉呢?我将如何将其整合到我的工作中?只需使用Singleton类来创建您希望在您的BLE设备上执行的所有方法和操作。然后在您需要的每个类上创建该单例类的实例。显然,您需要创建一个协议(或类似协议)来在singleton和其他控制器之间进行通信。用我想做的所有基于BLE的东西创建singleton。然后在所有视图控制器中创建该实例,对吗?我需要查找协议,因为我对它们不太熟悉。有任何指导吗?不是在所有视图控制器中,只是在您真正需要访问它们的视图控制器上。当然可以,搜索授权。好的,太好了,谢谢你,亚历克斯。如果我遇到麻烦,有什么办法可以联系你吗?嗨,亚历克斯,谢谢你的githb链接。我对斯威夫特相当陌生,我会怎么处理这个单身汉呢?我将如何将其整合到我的工作中?只需使用Singleton类来创建您希望在您的BLE设备上执行的所有方法和操作。然后在您需要的每个类上创建该单例类的实例。显然,您需要创建一个协议(或类似协议)来在singleton和其他控制器之间进行通信。用我想做的所有基于BLE的东西创建singleton。然后在所有视图控制器中创建该实例,对吗?我需要查找协议,因为我对它们不太熟悉。有任何指导吗?不是在所有视图控制器中,只是在您真正需要访问它们的视图控制器上。当然可以,搜索授权。好的,太好了,谢谢你,亚历克斯。如果我遇到麻烦,我可以联系你吗?我现在已经整理好了,但那不是问题。我现在已经整理好了,但那不是问题。