Отправка данных в Bluno из iOS

Я недавно купил Bluno и пытаюсь создать приложение для iPhone, чтобы поговорить с ним. Производители Bluno включают в себя исходный код, но он находится в объективе-c, и я пытаюсь перенести его в Swift. В настоящее время я могу обнаружить Bluno, подключиться к нему и посмотреть его услуги. Однако я не вижу никаких характеристик и получаю ноль при их печати. Я настроил Bluno так, чтобы он мигал, как только я посылаю ему символ "5", но я не могу найти правильную характеристику для этого. Любая помощь приветствуется. Вот мой текущий код, код Obj-C можно найти здесь:

    //
//  ViewController.swift
//  Bluetooth-Interaction
//
//  Created by Frederik Lohner on 26/Oct/15.
//  Copyright © 2015 JeongGroup. All rights reserved.
//

import UIKit
import CoreBluetooth
import SnapKit

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
    let backgroundView = UIView()
    let scanButton =  UIButton()
    var DFRobotServiceId = "0000dfb0-0000-1000-8000-00805f9b34fb"
    var kBlunoService = "DFB1"
    var kBlunoDataCharacteristic = "dfb1"

    var DFRobotCharacteristicsNameSerialPortId = "0000dfb1-0000-1000-8000-00805f9b34fb"

    var NameCommandId = "0000dfb2-0000-1000-8000-00805f9b34fb"

    // BLE
    var centralManager: CBCentralManager!
    var sensorTagPeripheral: CBPeripheral!

    override func viewDidLoad() {
        scanButton.setTitle("Scan", forState: UIControlState.Normal)
        scanButton.addTarget(self, action: "startScanning", forControlEvents: UIControlEvents.TouchUpInside)
        scanButton.backgroundColor = UIColor.blackColor()
        backgroundView.addSubview(scanButton)
        self.view.addSubview(backgroundView)
        backgroundView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.bottom.equalTo(self.view)
        }
        scanButton.snp_makeConstraints { (make) -> Void in
            make.left.bottom.equalTo(backgroundView)
            make.width.height.equalTo(60)
        }

        // Initialize central manager on load
        centralManager = CBCentralManager(delegate: self, queue: nil)
        //        self.centralManager.stopScan()
    }

    func startScanning() {
//        print("Started Scanning!")
//        //Could add service UUID here to scan for only relevant services
//        self.centralManager.scanForPeripheralsWithServices(nil, options: nil)
        let one = "1"
        let data = one.dataUsingEncoding(NSUTF8StringEncoding)
//        self.sensorTagPeripheral.writeValue(data!, forCharacteristic: , type: .WithoutResponse)
//        self.sensorTagPeripheral.writeValue(data!, forCharacteristic: CBCharacteristic., type: .WithoutResponse)
//        self.centralManager.
    }

    // Check status of BLE hardware
    func centralManagerDidUpdateState(central: CBCentralManager) {
        if central.state == CBCentralManagerState.PoweredOn {
            print("Bluetooth is ON")
            central.scanForPeripheralsWithServices(nil, options: nil)
        } else if central.state == CBCentralManagerState.Resetting {
            print("RESETTING")
        } else if central.state == CBCentralManagerState.Unauthorized {
            print("Not Authorized")
        } else {
            print("Bluetooth switched off or not initialized")
        }
    }
    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("Name was found")
                print("")
                print("")
                print(peripheral)
                //            for (key, value) in advertisementData {
                //                print("\(key) -> \(value)")
                //            }

                // Stop scanning
                self.centralManager.stopScan()
                print("Stopped Scanning")
                // Set as the peripheral to use and establish connection
                self.sensorTagPeripheral = peripheral
                self.sensorTagPeripheral.delegate = self
                self.centralManager.connectPeripheral(peripheral, options: nil)
                print("")
                print("")
                print("Connected")
                print("")
            }
            else {
                print("NOPE.EXE")
            }
        }
    }

    //    // 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 service in peripheral.services! {
            let thisService = service as CBService
            print("Discovered Service: \(thisService.description)")
            print("Discovered Characteristic: \(thisService.characteristics)")
        }
    }
    func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
        if(error != nil) {
            print(error?.description)
        }
        for characteristic in service.characteristics! {
            print("Characteristic found: \(characteristic)")
            let one = "1"
            let data = one.dataUsingEncoding(NSUTF8StringEncoding)
            peripheral.writeValue(data!, forCharacteristic: characteristic, type: .WithoutResponse)
            if(String(characteristic.UUID) == kBlunoService) {
                print("Found")
            }
        }
    }

    func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
        print("Did connect to peripheral.", terminator:"")
        peripheral.delegate = self
        peripheral.discoverServices(nil)
        print(peripheral)

    }
    func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("Failed to connect to peripheral.")
    }
    //    func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
    //        print("CONNECTION FAILED")
    //    }
    func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("CONNECTION WAS DISCONNECTED")
    }
}

1 ответ

Решение

Удалось заставить это работать. Код можно найти здесь.

Другие вопросы по тегам