Connecting Devices

Connecting devices in Android

📝 Source code

For the source code of connecting devices in Android, please refer to book-esp32c3-iot-projects/phone_app/app_android/app/src/main/java/com/espressif/ui/activites/BLEProvisionLanding.java.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //Code Omitted
    EventBus.getDefault().register(this)
}

@Override
protected void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(DeviceConnectionEvent event) {
    handler.removeCallbacks(disconnectDeviceTask);
    switch (event.getEventType()) {
        case ESPConstants.EVENT_DEVICE_CONNECTED:
        //Code Omitted
        break;

        case ESPConstants.EVENT_DEVICE_DISCONNECTED:`
        //Code Omitted
        break;

        case ESPConstants.EVENT_DEVICE_CONNECTION_FAILED:
        //Code Omitted
        break;
    }
}

In Android, EventBus is used to notify activities when Bluetooth LE connection status changes, so it is necessary to register a callback function in activities. After the device has been discovered, we should first create a device instance as shown in the code above, and then call the connection API as follows, so that the smartphone app can initiate a connection request to the device.

public void deviceClick(int deviceClickedPosition) {
    stopScan();
    isConnecting = true;
    isDeviceConnected = false;
    btnScan.setVisibility(View.GONE);
    rvBleDevices.setVisibility(View.GONE);
    progressBar.setVisibility(View.VISIBLE);
    this.position = deviceClickedPosition;
    BleDevice bleDevice = deviceList.get(deviceClickedPosition);
    String uuid = bluetoothDevices.get(bleDevice.getBluetoothDevice());

    if (ActivityCompat.checkSelfPermission(BLEProvisionLanding.this,
                        Manifest. permission.ACCESS_FINE_LOCATION) ==
                        PackageManager.PERMISSION_GRANTED) {
        boolean isSec1 = true;
        if (AppConstants.SECURITY_0.equalsIgnoreCase(BuildConfig.SECURITY)) {
            isSec1 = false;
        }
        if (isSec1) {
            provisionManager.createESPDevice(ESPConstants.TransportType.TRANSPORT_BLE, ESPConstants.SecurityType.SECURITY_1);
        } else {
            provisionManager.createESPDevice(ESPConstants.TransportType.TRANSPORT_BLE, ESPConstants.SecurityType.SECURITY_0);
        }provisionManager.getEspDevice().connectBLEDevice(bleDevice.getBluetoothDevice(), uuid);
        handler.postDelayed(disconnectDeviceTask, DEVICE_CONNECT_TIMEOUT);
    } else {
        Log.e(TAG, "Not able to connect device as Location permission is not granted.");
    }
}

📝 Source code

For the source code of initiating a connection by the smartphone app, please refer to book-esp32c3-iot-projects/phone_app/app_android/app/src/main/java/com/espressif/ui/activites/BLEProvisionLanding.java.

Connecting devices in iOS

The iOS app provides a proxy for the connection callback function, so we can directly call the instance connection interface returned by device scanning and pass the status proxy as a parameter to bleConnectionStatusHandler. The code is as follows:

📝 Source code

The pods folder stores imported third-party libraries. Files in this folder will only be generated once the project is compiled and installed locally. For the source code of connecting devices in iOS, please refer to book-esp32c3-iot-projects/phone_app/pods/espprovision/ESPDevice.swift.

open func connect(delegate: ESPDeviceConnectionDelegate? = nil,
            completionHandler: @escaping (ESPSessionStatus) -> Void) {
    ESPLog.log("Connecting ESPDevice..." )
    self.delegate = delegate
    switch transport {
        case .ble:
            ESPLog.log("Start connecting ble device." )
            bleConnectionStatusHandler = completionHandler
            if espBleTransport == nil {
                espBleTransport = ESPBleTransport(scanTimeout: 0, deviceNamePrefix: "")
            }
            espBleTransport.connect(peripheral: peripheral, withOptions: nil, delegate: self) 
        case .softap:
            ESPLog.log("Start connecting SoftAp device." )
            if espSoftApTransport == nil {
                espSoftApTransport = ESPSoftAPTransport(baseUrl: ESPUtility.baseUrl)
            }
            self.connectToSoftApUsingCredentials(ssid: name, completionHandler: completionHandler)
    }
}