, поэтому я создаю приложение для подключения и управления устройством BLE. Я успешно создал одно представление для сканирования периферийных устройств и одно для отправки данных на периферийное устройство. Теперь у меня есть требование создать еще один контроллер представления, который отправляет данные на уже подключенное периферийное устройство. Может кто-то мне помочь, пожалуйста? это мой проект колледжа
представление, которое отправляет данные в ble
import UIKit
import CoreBluetooth
import AVFoundation
class MainViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate
{
//audio integration
var objPlayer: AVAudioPlayer?
func playAudioFile() {
guard let url = Bundle.main.url(forResource: "RaptorSoundOne", withExtension: "mp3") else { return } //audiofilename
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
// For iOS 13
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let aPlayer = objPlayer else { return }
aPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
//audio integration untill here
@IBAction func armsound(_ sender: Any) {
playAudioFile()
}
@IBAction func seriestwosound(_ sender: Any) {
playAudioFile()
(sender as? UIButton)?.isEnabled = false
}
var manager:CBCentralManager? = nil
var mainPeripheral:CBPeripheral? = nil
var mainCharacteristic:CBCharacteristic? = nil
let BLEService = "FFE0"
let BLECharacteristic = "FFE1"
@IBOutlet weak var recievedMessageText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil);
customiseNavigationBar()
}
func customiseNavigationBar () {
self.navigationItem.rightBarButtonItem = nil
let rightButton = UIButton()
if (mainPeripheral == nil) {
rightButton.setTitle("Scan", for: [])
rightButton.setTitleColor(UIColor.blue, for: [])
rightButton.frame = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 60, height: 30))
rightButton.addTarget(self, action: #selector(self.scanButtonPressed), for: .touchUpInside)
} else {
rightButton.setTitle("Disconnect", for: [])
rightButton.setTitleColor(UIColor.blue, for: [])
rightButton.frame = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 30))
rightButton.addTarget(self, action: #selector(self.disconnectButtonPressed), for: .touchUpInside)
}
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = rightButton
self.navigationItem.rightBarButtonItem = rightBarButton
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "scan-segue") {
let scanController : ScanTableViewController = segue.destination as! ScanTableViewController
//set the manager's delegate to the scan view so it can call relevant connection methods
manager?.delegate = scanController as? CBCentralManagerDelegate
scanController.manager = manager
scanController.parentView = self
}
}
// MARK: Button Methods
@objc func scanButtonPressed() {
performSegue(withIdentifier: "scan-segue", sender: nil)
}
@objc func disconnectButtonPressed() {
//this will call didDisconnectPeripheral, but if any other apps are using the device it will not immediately disconnect
manager?.cancelPeripheralConnection(mainPeripheral!)
}
@IBAction func SeriesTwo(_ sender: Any) {
let SeriesTwo = "Z"
let dataToSend = SeriesTwo.data(using: String.Encoding.utf8)
if (mainPeripheral != nil) {
mainPeripheral?.writeValue(dataToSend!, for: mainCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
} else {
print("haven't discovered device yet")
}
}
@IBAction func Fogger(_ sender: Any) {
let Fogger = "Fogger"
let dataToSend = Fogger.data(using: String.Encoding.utf8)
if (mainPeripheral != nil) {
mainPeripheral?.writeValue(dataToSend!, for: mainCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
} else {
print("haven't discovered device yet")
}
}
@IBAction func Tailwag(_ sender: Any) {
let Tailwag = "Tailwag"
let dataToSend = Tailwag.data(using: String.Encoding.utf8)
if (mainPeripheral != nil) {
mainPeripheral?.writeValue(dataToSend!, for: mainCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
} else {
print("haven't discovered device yet")
}
}
@IBAction func arm1(_ sender: Any) {
let armo = "armo"
let dataToSend = armo.data(using: String.Encoding.utf8)
if (mainPeripheral != nil) {
mainPeripheral?.writeValue(dataToSend!, for: mainCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
} else {
print("haven't discovered device yet")
}
}
@IBAction func arm2(_ sender: Any) {
let armt = "armt"
let dataToSend = armt.data(using: String.Encoding.utf8)
if (mainPeripheral != nil) {
mainPeripheral?.writeValue(dataToSend!, for: mainCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
} else {
print("haven't discovered device yet")
}
}
@IBAction func seriesone(_ sender: Any) {
let seriesone = "seriesone"
let dataToSend = seriesone.data(using: String.Encoding.utf8)
if (mainPeripheral != nil) {
mainPeripheral?.writeValue(dataToSend!, for: mainCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
} else {
print("haven't discovered device yet")
}
}
// MARK: - CBCentralManagerDelegate Methods
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
mainPeripheral = nil
customiseNavigationBar()
print("Disconnected" + peripheral.name!)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print(central.state)
}
// MARK: CBPeripheralDelegate Methods
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
print("Service found with UUID: " + service.uuid.uuidString)
//device information service
if (service.uuid.uuidString == "FFE0") {
peripheral.discoverCharacteristics(nil, for: service)
}
//GAP (Generic Access Profile) for Device Name
// This replaces the deprecated CBUUIDGenericAccessProfileString
if (service.uuid.uuidString == "FFE0") {
peripheral.discoverCharacteristics(nil, for: service)
}
//Bluno Service
if (service.uuid.uuidString == BLEService) {
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
//get device name
if (service.uuid.uuidString == "1800") {
for characteristic in service.characteristics! {
if (characteristic.uuid.uuidString == "2A00") {
peripheral.readValue(for: characteristic)
print("Found Device Name Characteristic")
}
}
}
if (service.uuid.uuidString == "180A") {
for characteristic in service.characteristics! {
if (characteristic.uuid.uuidString == "2A29") {
peripheral.readValue(for: characteristic)
print("Found a Device Manufacturer Name Characteristic")
} else if (characteristic.uuid.uuidString == "2A23") {
peripheral.readValue(for: characteristic)
print("Found System ID")
}
}
}
if (service.uuid.uuidString == BLEService) {
for characteristic in service.characteristics! {
if (characteristic.uuid.uuidString == BLECharacteristic) {
//we'll save the reference, we need it to write data
mainCharacteristic = characteristic
//Set Notify is useful to read incoming data async
peripheral.setNotifyValue(true, for: characteristic)
print("Found Bluno Data Characteristic")
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if (characteristic.uuid.uuidString == "2A00") {
//value for device name recieved
let deviceName = characteristic.value
print(deviceName ?? "No Device Name")
} else if (characteristic.uuid.uuidString == "2A29") {
//value for manufacturer name recieved
let manufacturerName = characteristic.value
print(manufacturerName ?? "No Manufacturer Name")
} else if (characteristic.uuid.uuidString == "2A23") {
//value for system ID recieved
let systemID = characteristic.value
print(systemID ?? "No System ID")
} else if (characteristic.uuid.uuidString == BLECharacteristic) {
//data recieved
if(characteristic.value != nil) {
let stringValue = String(data: characteristic.value!, encoding: String.Encoding.utf8)!
recievedMessageText.text = stringValue
}
}
}
}
представление, которое сканирует для BLE
import UIKit
import CoreBluetooth
class ScanTableViewController: UITableViewController, CBCentralManagerDelegate {
var peripherals:[CBPeripheral] = []
var manager:CBCentralManager? = nil
var parentView:MainViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
scanBLEDevices()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return peripherals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "scanTableCell", for: indexPath)
let peripheral = peripherals[indexPath.row]
cell.textLabel?.text = peripheral.name
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let peripheral = peripherals[indexPath.row]
manager?.connect(peripheral, options: nil)
}
// MARK: BLE Scanning
func scanBLEDevices() {
//manager?.scanForPeripherals(withServices: [CBUUID.init(string: parentView!.BLEService)], options: nil)
//if you pass nil in the first parameter, then scanForPeriperals will look for any devices.
manager?.scanForPeripherals(withServices: nil, options: nil)
//stop scanning after 3 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.stopScanForBLEDevices()
}
}
func stopScanForBLEDevices() {
manager?.stopScan()
}
// MARK: - CBCentralManagerDelegate Methods
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if(!peripherals.contains(peripheral)) {
peripherals.append(peripheral)
}
self.tableView.reloadData()
}
// func centralManager(_ central: CBCentralManager, didDiscover peripheral:
CBPeripheral, advertisementData: [String : AnyObject], rssi RSSI: NSNumber) {
//
// if(!peripherals.contains(peripheral)) {
// peripherals.append(peripheral)
// }
//
// self.tableView.reloadData()
// }
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print(central.state)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
//pass reference to connected peripheral to parent view
parentView?.mainPeripheral = peripheral
peripheral.delegate = parentView
peripheral.discoverServices(nil)
//set the manager's delegate view to parent so it can call relevant disconnect methods
manager?.delegate = parentView
parentView?.customiseNavigationBar()
if let navController = self.navigationController {
navController.popViewController(animated: true)
}
print("Connected to " + peripheral.name!)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print(error!)
}
}
просмотр Я хочу включить подключенное периферийное устройство для отправки данных
import UIKit
import AVFoundation
import CoreBluetooth
class cathistorycorrectrewardViewController: UIViewController {
//audio integration
var objPlayer: AVAudioPlayer?
func playAudioFile() {
guard let url = Bundle.main.url(forResource: "RaptorSoundTwo", withExtension:
"mp3") else { return } //audiofilename
do {
try
AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
// For iOS 13
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint:
AVFileType.mp3.rawValue)
guard let aPlayer = objPlayer else { return }
aPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
//audio integration untill here
@IBAction func PlayCorrectRewardSound(_ sender: Any) {
playAudioFile()
(sender as? UIButton)?.isEnabled = false
}
@IBAction func close(_ sender: Any) {
self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}