Connecting a Swift IOS app I am working on with an ESP32 Microcontroller

Viewed 37

I am creating an app for a school project that is supposed to connect to an ESP32 microcontroller that my teammate is coding. The app is written in Swift using storyboard. I have stored the service and characteristic UUID in a separate file within the same Xcode project. I know that the app runs up until it needs to handle the discovery of the ESP32 bluetooth. I confirmed the ESP32 is transmitting Bluetooth using a BLE Scanner app that is able to see and connect to the ESP32. A code snippet and the terminal output is shown below. I've been trying to get this to work with two different microcontrollers the past few months with no success. Any help is greatly appreciated.

Terminal output

View Loaded
Central state update
Scanning for 603f5963-d799-44f5-b942-027a489c0991
Testing 1
Testing 2

'''

    //Handles initial Bluetooth scan
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        print("Central state update")
        if central.state != .poweredOn{
            print("Bluetooth is not enabled on this iPhone")
        }
        
        else{
            print("Scanning for", Penbot.penbotServiceUUID);
            centralManager.scanForPeripherals(withServices: [Penbot.penbotServiceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey : false])
            print("Testing 1")
        }
        print("Testing 2")
    }

    //Handles results of the Bluetooth scan
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        //Stop scan once devices are found
        print("Testing 3")
        self.centralManager.stopScan()
        
        //Copy the peripheral instance so that the peripheral persists throughtout the app
        self.peripheral = peripheral
        peripheral.delegate = self
        
        //Connect to Penbot
        self.centralManager.connect(self.peripheral, options: nil)
    }
    
    //Handles the scenario when a connection is succesful
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Testing 4")
        if peripheral == self.peripheral{
            print("Connected to the Penbot")
            peripheral.discoverServices([Penbot.penbotServiceUUID])
        }
    }
0 Answers
Related