美文网首页
2018-03-28蓝牙部分代码

2018-03-28蓝牙部分代码

作者: 丿沧海一粟丿 | 来源:发表于2018-03-28 11:49 被阅读0次

    `//

    // ViewController.swift

    // ble

    //

    // Created by 千秋万代 on 2018/3/26.

    // Copyright © 2018年 Leehom. All rights reserved.

    //

    import UIKit

    importCoreBluetooth

    class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    fileprivatevarcentralManager:CBCentralManager?
    
    fileprivatevarperipheral:CBPeripheral?
    
    fileprivatevarcharacteristicTx:CBCharacteristic?
    
    fileprivatevarcharacteristicRx:CBCharacteristic?
    
    fileprivatevardiscoveredPeripheralsArr: [CBPeripheral]?
    
    fileprivatevarwriteCharacteristic:CBCharacteristic?
    
    //指定服务UUID
    
    fileprivateletuuid:CBUUID=CBUUID.init(string:"FFF0")
    
    
    
    overridefuncviewDidLoad() {
    
        super.viewDidLoad()
    
        //按钮发送数据
    
        letbtn =UIButton(frame:CGRect(x:120, y:200, width:160, height:40))
    
        btn.setTitleColor(UIColor.red, for: .normal)
    
        btn.setTitle("发送数据", for: .normal)
    
        btn.addTarget(self, action:#selector(btnAction), for: .touchUpInside)
    
        self.view.addSubview(btn)
    
        //初始化并设置代理
    
        self.centralManager=CBCentralManager.init(delegate:self, queue:DispatchQueue.main)
    
    
    
    }
    
    
    
    @objc fileprivate func btnAction() {
    
        varSECRETKEY:String="938E0400080410"
    
        letgetbytes: [UInt8] = [0x93,0x8e,0x04,0x00,0x08,0x04,0x10]
    
        self.writeToPeripheral(bytes: getbytes)
    
    }
    
    
    
    funccentralManagerDidUpdateState(_central:CBCentralManager) {
    
        switchcentral.state{
    
        case.unknown:
    
            print("CBCentralManagerStateUnknown")
    
        case.resetting:
    
            print("CBCentralManagerStateResetting")
    
        case .unsupported:
    
            print("CBCentralManagerStateUnsupported")
    
        case .unauthorized:
    
            print("CBCentralManagerStateUnauthorized")
    
        case.poweredOff:
    
            print("CBCentralManagerStatePoweredOff")
    
            //查看蓝牙状态,开启则搜索外设
    
        case.poweredOn:
    
            print("CBCentralManagerStatePoweredOn")
    
            //蓝牙打开,开始扫描
    
            //第一个参数类型为CBUUID 的数组,可以通过UUID来筛选设备,传nill扫描周围所有设备
    
            self.centralManager?.scanForPeripherals(withServices: [self.uuid], options:nil)
    
        }
    
    }
    
    //找到设备就会调用如下方法
    
    funccentralManager(_central:CBCentralManager, didDiscover peripheral:CBPeripheral, advertisementData: [String:Any], rssi RSSI:NSNumber) {
    
        print(peripheral)
    
        //这里自己去设置下连接规则
    
        //找到服务后进行连接,并设置代理。
    
        if  ((peripheral.name?.contains("HelloWorld"))!){
    

    // 找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!

            self.discoveredPeripheralsArr?.append(peripheral)
    
            self.centralManager= central
    
            self.peripheral= peripheral
    
            central.connect(self.peripheral!, options:nil)
    
        }
    
    }
    
    
    
    //已连接代理
    
    funccentralManager(_central:CBCentralManager, didConnect peripheral:CBPeripheral) {
    
        print("已连接")
    
        //停止扫描
    
        self.centralManager?.stopScan()
    
        //先设置代理
    
        peripheral.delegate=self
    
        //然后外设查找service
    
        peripheral.discoverServices(nil)
    
        self.title= peripheral.name
    
    }
    
    
    
    //连接失败
    
    funccentralManager(_central:CBCentralManager, didFailToConnect peripheral:CBPeripheral, error:Error?) {
    
        print("连接失败")
    
    }
    
    
    
    funcperipheral(_peripheral:CBPeripheral, didDiscoverServices error:Error?) {
    
        iferror !=nil{
    
            print("查找services\(String(describing: peripheral.name))报错\(String(describing: error?.localizedDescription))")
    
        }
    
    
    
        forserviceinperipheral.services! {
    
            //需要连接的服务CBCharacteristic的UUID
    
            //此处uuid等于180A和FFF0
    
            ifservice.uuid.uuidString=="FFF0"{
    
                //查找特征
    
                peripheral.discoverCharacteristics(nil, for: service)
    
            }
    
        }
    
    }
    
    
    
    funcperipheral(_peripheral:CBPeripheral, didDiscoverCharacteristicsFor service:CBService, error:Error?) {
    
        iferror !=nil{
    
            print("查找Characteristics\(String(describing: peripheral.name))报错\(String(describing: error?.localizedDescription))")
    
        }
    
        forcinservice.characteristics! {
    
            ifc.uuid.uuidString=="FFF1"{
    
                print("write")
    
                self.writeCharacteristic= c
    
            }
    
            ifc.uuid.uuidString=="FFF4"{
    
                print("read")
    
                peripheral.setNotifyValue(true, for: c)
    
            }
    
        }
    
    }
    
    
    
    //写入后回调
    
    funcperipheral(_peripheral:CBPeripheral, didWriteValueFor characteristic:CBCharacteristic, error:Error?) {
    
        print("数据写完")
    
    }
    
    
    
    //设置特征为正在监听,读取数据
    
    funcperipheral(_peripheral:CBPeripheral, didUpdateNotificationStateFor characteristic:CBCharacteristic, error:Error?) {
    
        iferror !=nil{
    
            print((error?.localizedDescription)!)
    
        }
    
    
    
        ifcharacteristic.isNotifying{
    
            peripheral.readValue(for: characteristic)
    
            print(characteristic.uuid.uuidString)
    
        }
    
    }
    
    
    
    //获取外设数据
    
    funcperipheral(_peripheral:CBPeripheral, didUpdateValueFor characteristic:CBCharacteristic, error:Error?) {
    
        ifcharacteristic.uuid.uuidString=="FFF4"{
    

    // let data:NSData = characteristic.value!

    // print(data)

    // let d = Array(UnsafeBufferPointer(start: UnsafePointer(data.bytes), count: data.length))

    // print(d)

    //

    // let s:String = HexUtil.encodeToString(d)

    // if s != "00" {

    // result += s

    // print(result )

    // print(result.characters.count )

    // }

    //

    // if result.characters.count == 38 {

    // lable.text = result

    // }

        }
    
    }
    
    
    
    //发送指令到设备
    
    fileprivatefuncwriteToPeripheral(bytes: [UInt8]) {
    
        if self.writeCharacteristic != nil {
    
            letdata:Data=dataWithHexstring(bytes: bytes)
    
            self.peripheral?.writeValue(data, for:self.writeCharacteristic!, type: .withResponse)
    
        }else{
    
    
    
        }
    
    }
    
    
    
    //将[UInt8]数组转换为NSData
    
    fileprivatefuncdataWithHexstring(bytes: [UInt8]) ->Data{
    
        letdata =Data(bytes: bytes, count: bytes.count)
    
        returndata
    
    }
    

    }`

    相关文章

      网友评论

          本文标题:2018-03-28蓝牙部分代码

          本文链接:https://www.haomeiwen.com/subject/sqyycftx.html