1.4.1 Bluetooth® Low Energy UART Framework Integration and Usage

Download the framework from the following link: MBD_Framework_v2.1.0

  1. Import the framework:
    1. Open Xcode and create a simple project.
    2. In the project navigator, open the project settings.
    3. Select the target, and then open the "General" tab.
    4. Navigate to Frameworks>Libraries>Embedded Content settings.
    5. Add "MchpBLELib.xcframework."
      Figure 1-23. Import Framework to Project
  2. First, import the MchpBLELib library and conform to the BleUARTDelegate protocol in the ViewController. This protocol defines several delegate methods that must be implemented to handle Bluetooth Low Energy events.
    import MchpBLELib
     
    class ViewController: UIViewController, BleUARTDelegate {
     
        func bleConnecting(bleScanState:Bool, discoveredPeripherals:[Any]){}
         
        func bleDidConnect(peripheralName: String) {}
         
        func bleDidDisconnect(error: String) {}
         
        func bleDidUpdateStatus(status: String) {}
         
        func didWriteRawData(data: Data) {}
         
        func didUpdateRawData(data: Data) {}
         
        func bleThroughputUpdate(Downlink: String?, Uplink: String?) {}
         
        func didEnableRemoteControlMode() {}
    }
  3. Initialization: Initialize the BleUART object and set its delegate to your ViewController. This is typically done in the viewDidLoad method.
    var bleUart : BleUART?
     
    override func viewDidLoad() {
            super.viewDidLoad()
             
            if bleUart == nil{
                bleUart = BleUART.sharedInstance(option: .Normal)
                bleUart.delegate = self
            }
    }
  4. Scanning the Devices: To scan for Bluetooth Low Energy devices, call the bleScan method on the BleUART object. Specify a scan timeout, scan configuration, and a filter to narrow down the devices of interest.
    /**
    Scans for BLE peripheral with a timer. If timeout, stop scanning the peripherals
     
    - parameter scanTimeout: BLE scan time. default is 60 seconds
    - parameter scanConfig: Scan option
    - parameter filter: BLE scanner wil use this to filter advertising packets. The list of filtered devices is return by the bleUARTDelegate bleConnecting method
    - returns: None
    */
    self.bleUart?.bleScan(scanTimeout: 10,filter: [.FilterBySpecificString:self.DeviceFilter!])
  5. When the bleUartController discovers a peripheral, it calls the bleConnecting(bleScanState:discoveredPeripherals:) method of its delegate object.
    typealias peripheralInfo = (String, NSNumber)
     
    func bleConnecting(bleScanState:Bool, discoveredPeripherals:[Any]){
             
            for peripheral in discoveredPeripherals{
                if peripheral is peripheralInfo{
                    let peripheralInfo = peripheral as! peripheralInfo
                    print("peripheral name & rssi = \(peripheralInfo)")
                }
            }
        }
  6. Connecting the Device: Once the Bluetooth Low Energy is connected, bleUartController calls the bleDidConnect(peripheralName:) method of its delegate object.
    bleUart?.bleConnect(deviceName: "BLE_UART_XXXX")
     
    func bleDidConnect(peripheralName: String) {
        print("callback: bleDidConnect. \(peripheralName)")
    }
  7. Disconnecting the Device: To disconnect from a Bluetooth Low Energy device, call the bleDisconnect method on the BleUART object with the device's UUID.
    bleUart?.bleDisconnect(peripheralUUID: "9BCE-XXXX-XXXX-XYXY....")
  8. Data exchange:
    • Sending Data: The application sends a text file (for example, 500.txt).

    • Receiving Data: The bleUartController calls the didUpdateRawData(data:) method of its delegate object.

    • To send data to the Bluetooth Low Energy device, use the BurstTransmit method for Burst Transmission or the TransmitData method for regular data transmission.
      • Burst Transmission:
        func WriteData() {
            let bundle = Bundle.main
            let fileUrl = bundle.url(forResource: "500k", withExtension: "txt")
         
            if (fileUrl != nil) {
                /// BLE UART burst transmission
                ///
                /// - Parameters:
                ///   - peripheralUUID: The UUID of the target peripheral
                ///   - profile: BLE UART transparent profile. TRP or TRCBP
                ///   - mode: Operation mode. UART,Checksum,Loopback,FixedPattern
                ///   - fileurl: The URL of BLE UART test file. 10k.txt,100k.txt,200k.txt,500k.txt
                ///   - completion: completion handler is called with the execution result and an optional error
                bleUart?.BurstTransmit(profile: .TRP, mode: .go_through_uart, fileurl: fileUrl!, completion: {(error) in
                    if error != nil {
                        print("error = \(error!)")
                    } else {
                     print("Burst Transmit Complete.")
                    }
                }
            }
        }
         
        func didUpdateRawData(data: Data) {}
      • Regular Transmission:
        /**
        BLE UART data transmission
         
        - parameter peripheralUUID: UUID of the target peripheral
        - parameter profile: BLE UART transparent profile. TRP or TRCBP
        - parameter mode: Operation mode. UART or Loopback mode
        - parameter data: Data to be send
        - parameters:
        - completion: completion handler is called with the execution result and an optional error
        */
        bleUart?.TransmitData(profile: .TRP, mode: ble_uart_mode, data: dat, completion: { [self] error in
            if(error != nil){
                print("Fail, error = \(error!)")
            }else{}
        )
      • Cancel Transmission:
        /// Cancel the data transmission
        /// - Parameter peripheralUUID: The UUID of the target peripheral
        bleUart?.CancelTransmission()
  9. Changing Transparent Profile:
    /**
       Change the BLE UART transparent profile
     
       - parameter peripheralUUID: The UUID of the target peripheral
       - parameter profile: BLE UART transparent profile. TRP or TRCBP
       - completion: completion handler is called with the execution result and an optional error
    */
    bleUart?.ChangeProfile(peripheralUUID: deviceUUID, profile: .TRP, completion: { error in
        if(error != nil){
            print("Error")
        }
    })