### Create ESPDevice Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Demonstrates how to create an ESPDevice instance by specifying the transport type and security type. This is a common starting point for device provisioning. ```java ESPDevice device = manager.createESPDevice( ESPConstants.TransportType.TRANSPORT_BLE, ESPConstants.SecurityType.SECURITY_2 ); ``` -------------------------------- ### Start Camera Preview (No Parameters) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Starts the camera preview using a previously set camera source. Requires CAMERA permission. ```java @RequiresPermission(Manifest.permission.CAMERA) public void start() throws IOException, SecurityException ``` -------------------------------- ### Complete Provisioning Flow Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-listeners.md An example of an Android Activity implementing various listeners to handle the complete ESP-IDF provisioning flow, including QR code scanning, device detection, WiFi configuration, and provisioning status updates. ```java public class ProvisioningActivity extends AppCompatActivity implements QRCodeScanListener, ProvisionListener, WiFiScanListener { private ESPDevice espDevice; private ESPProvisionManager provisionManager; @Override public void qrCodeScanned() { // QR code detected, show loading UI progressDialog.show(); } @Override public void deviceDetected(ESPDevice device) { // Device found, ready to connect this.espDevice = device; espDevice.setProofOfPossession(device.getProofOfPossession()); espDevice.connectToDevice(); } @Override public void onFailure(Exception e) { Toast.makeText(this, "QR code scan failed", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Exception e, String data) { Toast.makeText(this, "Invalid QR code format", Toast.LENGTH_SHORT).show(); } // WiFi scan callback @Override public void onWifiListReceived(ArrayList wifiList) { // User selects network from list WiFiAccessPoint selectedAp = wifiList.get(0); espDevice.provision(selectedAp.getWifiName(), userEnteredPassword, this); } @Override public void onWiFiScanFailed(Exception e) { Log.e(TAG, "WiFi scan failed", e); } // Provisioning callbacks @Override public void createSessionFailed(Exception e) { progressDialog.dismiss(); Toast.makeText(this, "Session creation failed", Toast.LENGTH_SHORT).show(); } @Override public void wifiConfigSent() { Log.d(TAG, "Config sent"); } @Override public void wifiConfigFailed(Exception e) { progressDialog.dismiss(); Toast.makeText(this, "Failed to send WiFi config", Toast.LENGTH_SHORT).show(); } @Override public void wifiConfigApplied() { Log.d(TAG, "Config applied"); } @Override public void wifiConfigApplyFailed(Exception e) { progressDialog.dismiss(); Toast.makeText(this, "Device failed to apply config", Toast.LENGTH_SHORT).show(); } @Override public void provisioningFailedFromDevice(ESPConstants.ProvisionFailureReason reason) { progressDialog.dismiss(); Toast.makeText(this, "Device error: " + reason.toString(), Toast.LENGTH_SHORT).show(); } @Override public void deviceProvisioningSuccess() { progressDialog.dismiss(); Toast.makeText(this, "Device provisioned successfully!", Toast.LENGTH_SHORT).show(); } @Override public void onProvisioningFailed(Exception e) { progressDialog.dismiss(); Toast.makeText(this, "Provisioning failed: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } ``` -------------------------------- ### Start Camera Preview with CameraSource Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Starts displaying the camera preview using a provided CameraSource. This method is used by ESPProvisionManager.scanQRCode(). Requires CAMERA permission. ```java @RequiresPermission(Manifest.permission.CAMERA) public void start(CameraSource cameraSource) throws IOException, SecurityException ``` -------------------------------- ### BLETransport connect Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-transport.md Example demonstrating how to connect to a BLE device using BLETransport and listen for connection events via EventBus. ```java BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); UUID serviceUuid = UUID.fromString("0000ff50-0000-1000-8000-00805f9b34fb"); BLETransport transport = new BLETransport(context); transport.connect(device, serviceUuid); // Listen for connection result EventBus.getDefault().register(this); ``` -------------------------------- ### Start Camera Preview with Graphic Overlay Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Starts the camera preview and allows for drawing detection results on the preview using a GraphicOverlay. Requires CAMERA permission. ```java @RequiresPermission(Manifest.permission.CAMERA) public void start(CameraSource cameraSource, GraphicOverlay overlay) throws IOException, SecurityException ``` -------------------------------- ### CameraSourcePreview.start (no parameters) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Starts the previously configured camera source for the preview. Requires CAMERA permission. ```APIDOC ## start (no parameters) ### Description Starts the previously configured camera source for the preview. Requires CAMERA permission. ### Method public void start() throws IOException, SecurityException ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Custom Data Exchange with LED Control Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/MANIFEST.txt Shows how to send JSON data to custom endpoints and parse responses, including an example for LED control. This pattern involves approximately 50 lines of code. ```Java // Example code for custom data exchange (Pattern 4) // This snippet is a placeholder as the actual code is concise (50 lines) // and would typically be found in usage-patterns.md. ``` -------------------------------- ### Manual BLE Device Provisioning Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/MANIFEST.txt Illustrates the BLE device discovery, connection, and provisioning flow. This pattern involves over 200 lines of code. ```Java // Example code for manual BLE device provisioning (Pattern 2) // This snippet is a placeholder as the actual code is extensive (200+ lines) // and would typically be found in usage-patterns.md. ``` -------------------------------- ### CameraSourcePreview.start (with overlay) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Starts displaying the camera preview with an optional GraphicOverlay for drawing detection results. Requires CAMERA permission. ```APIDOC ## start (with overlay) ### Description Starts displaying the camera preview with an optional GraphicOverlay for drawing detection results. Requires CAMERA permission. ### Method public void start(CameraSource cameraSource, GraphicOverlay overlay) throws IOException, SecurityException ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### WiFi SoftAP Provisioning Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/MANIFEST.txt Demonstrates direct WiFi connection to a device using SoftAP provisioning, supporting both Q+ and legacy APIs. Includes network selection and security detection. This pattern involves over 250 lines of code. ```Java // Example code for WiFi SoftAP provisioning (Pattern 3) // This snippet is a placeholder as the actual code is extensive (250+ lines) // and would typically be found in usage-patterns.md. ``` -------------------------------- ### DeviceConnectionEvent Usage Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Illustrates how to register for and handle DeviceConnectionEvent using EventBus. This example shows how to react to different connection states like connected, connection failed, and disconnected, and includes proper unregistration in onDestroy. ```java EventBus.getDefault().register(this); @Subscribe public void onDeviceConnectionEvent(DeviceConnectionEvent event) { switch (event.getEventType()) { case ESPConstants.EVENT_DEVICE_CONNECTED: Log.d(TAG, "Device connected successfully"); break; case ESPConstants.EVENT_DEVICE_CONNECTION_FAILED: Log.e(TAG, "Connection failed"); break; case ESPConstants.EVENT_DEVICE_DISCONNECTED: Log.d(TAG, "Device disconnected"); break; } } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } ``` -------------------------------- ### Complete Activity Wrapper Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/MANIFEST.txt Presents a reusable ProvisioningManager component using a state machine pattern and listener-based UI updates. This pattern involves over 300 lines of code. ```Java // Example code for a complete Activity wrapper (Pattern 6) // This snippet is a placeholder as the actual code is extensive (300+ lines) // and would typically be found in usage-patterns.md. ``` -------------------------------- ### CameraSourcePreview.start (with CameraSource) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Starts displaying the camera preview using a provided CameraSource. This method is used internally by ESPProvisionManager.scanQRCode(). Requires CAMERA permission. ```APIDOC ## start (with CameraSource) ### Description Starts displaying the camera preview using a provided CameraSource. This method is used internally by ESPProvisionManager.scanQRCode(). Requires CAMERA permission. ### Method public void start(CameraSource cameraSource) throws IOException, SecurityException ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### WiFiAccessPoint Usage Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Demonstrates how to create and populate a WiFiAccessPoint object with network credentials and then use these credentials for device provisioning. Ensure to use appropriate ESPConstants for security types. ```java WiFiAccessPoint ap = new WiFiAccessPoint(); ap.setWifiName("MyNetwork"); ap.setRssi(-50); ap.setSecurity(ESPConstants.WIFI_WPA2_PSK); ap.setPassword("mypassword"); // Later, provision device with these credentials device.provision(ap.getWifiName(), ap.getPassword(), provisionListener); ``` -------------------------------- ### Usage Patterns Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/MANIFEST.txt Provides practical examples and workflows for using the library, such as the QR code scanning flow. ```APIDOC ## Usage Patterns ### Description Illustrates common usage scenarios and provides production-ready code examples for integrating the library. ### QR Code Scanning Flow - **Scenario**: Complete activity demonstrating device discovery via QR code, network selection, and provisioning. - **Features**: Includes progress dialogs and error handling. - **Code Example**: Over 250 lines of production-ready code. ``` -------------------------------- ### Example QR Code Data Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md A concrete example of a JSON payload for a SoftAP transport with security level 2. ```json {"ver":"v1","name":"PROV_CE03C0","pop":"abcd1234","transport":"softap","security":2} ``` -------------------------------- ### Set Security Type Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Shows how to set the security type for an ESPDevice instance. This is crucial for establishing a secure connection with the device. ```java device.setSecurityType(ESPConstants.SecurityType.SECURITY_2); ``` -------------------------------- ### QR Code Scanning Flow Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/MANIFEST.txt This snippet demonstrates a complete QR code scanning flow for device discovery and provisioning. It includes device discovery via QR code, network selection, provisioning, progress dialogs, and error handling. This is production-ready code. ```java /* * Copyright 2019 Espressif Systems (Shanghai) PTE LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.espressif.provisioning.utils; import android.content.Context; import android.content.Intent; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.espressif.provisioning.DeviceConnectionEvent; import com.espressif.provisioning.DeviceProvisioningHelper; import com.espressif.provisioning.ProvisionListener; import com.espressif.provisioning.R; import com.espressif.provisioning.SecurityType; import com.espressif.provisioning.TransportType; import com.espressif.provisioning.WiFiAccessPoint; import com.espressif.provisioning.WiFiScanListener; import com.espressif.provisioning.exceptions.ProvisionException; import com.espressif.provisioning.listeners.QRCodeScanListener; import org.json.JSONException; import org.json.JSONObject; import java.util.List; public class QRCodeProvisioning { private static final String TAG = "QRCodeProvisioning"; private static final int PROVISIONING_REQUEST_CODE = 100; private Context context; private DeviceProvisioningHelper provisioningHelper; private QRCodeScanListener qrCodeScanListener; private ProvisionListener provisionListener; private WiFiScanListener wiFiScanListener; public QRCodeProvisioning(@NonNull Context context) { this.context = context; this.provisioningHelper = new DeviceProvisioningHelper(context); } public void setQrCodeScanListener(QRCodeScanListener qrCodeScanListener) { this.qrCodeScanListener = qrCodeScanListener; } public void setProvisionListener(ProvisionListener provisionListener) { this.provisionListener = provisionListener; } public void setWiFiScanListener(WiFiScanListener wiFiScanListener) { this.wiFiScanListener = wiFiScanListener; } public void startQRCodeScan(@NonNull AppCompatActivity activity) { Intent intent = new Intent(activity, com.espressif.provisioning.QRCodeScanActivity.class); activity.startActivityForResult(intent, PROVISIONING_REQUEST_CODE); } public void handleProvisioningResult(@NonNull AppCompatActivity activity, int requestCode, @Nullable Intent data) { if (requestCode == PROVISIONING_REQUEST_CODE) { if (data != null) { String qrCodeData = data.getStringExtra(com.espressif.provisioning.QRCodeScanActivity.QR_CODE_EXTRA); if (qrCodeData != null) { try { JSONObject json = new JSONObject(qrCodeData); String ssid = json.getString("ssid"); String password = json.getString("password"); String security = json.getString("security"); String ipAddr = json.optString("ip_addr", null); if (qrCodeScanListener != null) { qrCodeScanListener.onQRCodeScanned(ssid, password, security, ipAddr); } provisionDevice(ssid, password, security, ipAddr); } catch (JSONException e) { Log.e(TAG, "Error parsing QR code data", e); if (qrCodeScanListener != null) { qrCodeScanListener.onQRCodeScanError(new ProvisionException("Invalid QR code format", e)); } } } else { Log.w(TAG, "QR code data is null."); if (qrCodeScanListener != null) { qrCodeScanListener.onQRCodeScanError(new ProvisionException("QR code data is null.")); } } } else { Log.w(TAG, "Intent data is null."); if (qrCodeScanListener != null) { qrCodeScanListener.onQRCodeScanError(new ProvisionException("Intent data is null.")); } } } } private void provisionDevice(String ssid, String password, String security, @Nullable String ipAddr) { if (provisionListener == null) { Log.e(TAG, "ProvisionListener is not set."); return; } provisioningHelper.setProvisionListener(provisionListener); try { SecurityType securityType = SecurityType.valueOf(security.toUpperCase()); TransportType transportType = (ipAddr != null) ? TransportType.TRANSPORT_WIFI : TransportType.TRANSPORT_BLE; if (transportType == TransportType.TRANSPORT_WIFI) { provisioningHelper.provision(ssid, password, securityType, ipAddr); } else { provisioningHelper.provision(ssid, password, securityType); } } catch (IllegalArgumentException e) { Log.e(TAG, "Invalid security type: " + security, e); provisionListener.onError(new ProvisionException("Invalid security type: " + security, e)); } catch (Exception e) { Log.e(TAG, "Provisioning failed", e); provisionListener.onError(new ProvisionException("Provisioning failed", e)); } } public void startWiFiScan() { if (wiFiScanListener == null) { Log.e(TAG, "WiFiScanListener is not set."); return; } provisioningHelper.setWiFiScanListener(wiFiScanListener); provisioningHelper.startWiFiScan(); } public void stopWiFiScan() { provisioningHelper.stopWiFiScan(); } public void disconnect() { provisioningHelper.disconnect(); } public void release() { provisioningHelper.release(); } } ``` -------------------------------- ### Configure WiFi SoftAP Device with Security v1 Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/configuration.md This example shows how to configure an ESPDevice for WiFi SoftAP transport with Security v1. It includes setting the device name, proof of possession, and WiFi access point details. ```java ESPDevice device = manager.createESPDevice( ESPConstants.TransportType.TRANSPORT_SOFTAP, ESPConstants.SecurityType.SECURITY_1 ); device.setDeviceName("PROV_XYZ789"); device.setProofOfPossession("test1234"); WiFiAccessPoint ap = new WiFiAccessPoint(); ap.setWifiName("PROV_XYZ789"); ap.setPassword(""); device.setWifiDevice(ap); device.connectWiFiDevice("PROV_XYZ789", ""); ``` -------------------------------- ### WiFi SoftAP Provisioning Flow Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/usage-patterns.md Initiates WiFi provisioning by prompting the user for the network password and then starting the provisioning process. Handles user input and displays progress. ```java .setTitle("WiFi Password") .setMessage("Enter password for: " + network.getWifiName()) .setView(passwordInput) .setPositiveButton("Connect", (dialog, which) -> { String password = passwordInput.getText().toString(); startProvisioning(network.getWifiName(), password); }) .setNegativeButton("Cancel", null) .show(); } } private void startProvisioning(String ssid, String password) { ProgressDialog progress = new ProgressDialog(this); progress.setTitle("Provisioning"); progress.setMessage("Connecting device to WiFi..."); progress.setCancelable(false); progress.show(); espDevice.provision(ssid, password, new ProvisionListener() { @Override public void createSessionFailed(Exception e) { progress.dismiss(); showErrorDialog("Session Error", "Failed to establish session: " + e.getMessage()); } @Override public void wifiConfigSent() { progress.setMessage("Credentials sent to device..."); } @Override public void wifiConfigFailed(Exception e) { progress.dismiss(); showErrorDialog("Config Error", "Failed to send configuration"); } @Override public void wifiConfigApplied() { progress.setMessage("Waiting for device to connect..."); } @Override public void wifiConfigApplyFailed(Exception e) { progress.dismiss(); showErrorDialog("Apply Error", "Device failed to apply configuration"); } @Override public void provisioningFailedFromDevice(ESPConstants.ProvisionFailureReason reason) { progress.dismiss(); String message = ""; switch (reason) { case AUTH_FAILED: message = "Incorrect WiFi password. Please check and retry."; break; case NETWORK_NOT_FOUND: message = "WiFi network not found. Check SSID and try again."; break; case DEVICE_DISCONNECTED: message = "Device disconnected. Please restart device."; break; case UNKNOWN: message = "Unknown error occurred."; break; } showErrorDialog("Provisioning Failed", message); } @Override public void deviceProvisioningSuccess() { progress.dismiss(); showSuccessDialog("Provisioning Complete", "Device has been successfully provisioned!"); } @Override public void onProvisioningFailed(Exception e) { progress.dismiss(); showErrorDialog("Provisioning Error", e.getMessage()); } }); } private void showErrorDialog(String title, String message) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton("OK", null) .show(); } private void showSuccessDialog(String title, String message) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton("OK", (dialog, which) -> finish()) .show(); } @Override protected void onDestroy() { super.onDestroy(); if (espDevice != null) { espDevice.disconnectDevice(); } EventBus.getDefault().unregister(this); } } ``` -------------------------------- ### searchBleEspDevices (Prefix filter) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts BLE device scanning with a filter for device names that start with a specified prefix. This method also requires Bluetooth permissions. ```APIDOC ## searchBleEspDevices (Prefix filter) ### Description Starts BLE device scanning with a device name prefix filter. ### Method ```java public void searchBleEspDevices(String prefix, BleScanListener bleScannerListener) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **prefix** (String) - Required - Device name prefix to filter results (e.g., "PROV_") - **bleScannerListener** (BleScanListener) - Required - Callback listener for scan events ### Permissions Required - `android.permission.BLUETOOTH_ADMIN` - `android.permission.BLUETOOTH` ### Example ```java manager.searchBleEspDevices("PROV_", bleScanListener); ``` ``` -------------------------------- ### searchWiFiEspDevices (Default) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts Wi-Fi device scanning to find available access points. Requires CHANGE_WIFI_STATE and ACCESS_WIFI_STATE permissions. ```APIDOC ## searchWiFiEspDevices (Overload 1: Default) Starts Wi-Fi device scanning to find available access points. ### Method public void searchWiFiEspDevices(WiFiScanListener wiFiDeviceScanListener) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **wiFiDeviceScanListener** (WiFiScanListener) - Required - Callback listener for WiFi scan results ### Permissions Required - `android.permission.CHANGE_WIFI_STATE` - `android.permission.ACCESS_WIFI_STATE` ### Example ```java manager.searchWiFiEspDevices(new WiFiScanListener() { @Override public void onWifiListReceived(ArrayList wifiList) { // Process list of found networks } @Override public void onWiFiScanFailed(Exception e) { // Handle scan failure } }); ``` ``` -------------------------------- ### Handle Successful Device Provisioning Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-listeners.md This callback is invoked when the device has been successfully provisioned, indicating a successful WiFi connection and completion of the setup. Use it to finalize the process, such as saving device information. ```java @Override public void deviceProvisioningSuccess() { Log.d(TAG, "Device provisioning completed successfully!"); // Show success UI, save device info, etc. } ``` -------------------------------- ### Start BLE Device Scanning (Prefix Filter) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts a BLE device scan, filtering results by a specified device name prefix. This method requires BLUETOOTH and BLUETOOTH_ADMIN permissions. Provide a BleScanListener to manage scan callbacks. ```java manager.searchBleEspDevices("PROV_", bleScanListener); ``` -------------------------------- ### ESPProvisionManager Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-index.md Singleton class to manage device provisioning. Provides methods to get the instance, create ESPDevice objects, and initiate scanning operations. ```APIDOC ## ESPProvisionManager ### Description A singleton class that acts as the entry point for device provisioning operations. It allows users to obtain an instance of the manager, create ESPDevice objects for interaction, and initiate various scanning processes. ### Methods - **getInstance()** → ESPProvisionManager: Returns the singleton instance of ESPProvisionManager. - **createESPDevice()** → ESPDevice: Creates a new ESPDevice object for interacting with a specific device. - **scanQRCode()** — Initiates QR code scanning. - **searchBleEspDevices()** — Initiates BLE scanning for Espressif devices. - **searchWiFiEspDevices()** — Initiates WiFi scanning for Espressif devices. - **stopBleScan()** — Stops the ongoing BLE scanning process. ``` -------------------------------- ### Start BLE Scan with Scan Settings Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Initiates a BLE device scan using specified ScanSettings. Requires BLUETOOTH_ADMIN and BLUETOOTH permissions. ```java public void searchBleEspDevices(ScanSettings scanSettings, BleScanListener bleScannerListener) ``` -------------------------------- ### Complete Session Workflow in Java Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-session.md This Java code illustrates the entire session workflow, including transport and security setup, session establishment, network scanning, Wi-Fi configuration, and applying the configuration. It handles different security types and transport mechanisms. ```java public class DeviceProvisioner { private ESPDevice device; private Session session; public void setupAndProvision() { // Create transport and security Transport transport = device.transportType == TRANSPORT_BLE ? new BLETransport(context) : new SoftAPTransport(); Security security; switch (device.securityType) { case SECURITY_0: security = new Security0(); break; case SECURITY_1: security = new Security1(device.getProofOfPossession()); break; case SECURITY_2: security = new Security2(device.getUserName(), device.getProofOfPossession()); break; } // Create session session = new Session(transport, security); // Establish session session.init(null, new Session.SessionListener() { @Override public void OnSessionEstablished() { onSessionReady(); } @Override public void OnSessionEstablishFailed(Exception e) { Log.e(TAG, "Session failed: " + e.getMessage()); provisionListener.createSessionFailed(e); } }); } private void onSessionReady() { // Session established, now scan networks scanNetworks(); } private void scanNetworks() { byte[] scanRequest = createNetworkScanRequest(); session.sendDataToDevice(ESPConstants.HANDLER_PROV_SCAN, scanRequest, new ResponseListener() { @Override public void onSuccess(byte[] returnData) { ArrayList networks = parseNetworks(returnData); provisionListener.networksScanned(networks); } @Override public void onFailure(Exception e) { Log.e(TAG, "Network scan failed", e); provisionListener.onProvisioningFailed(e); } }); } public void provisionWithWiFi(String ssid, String password) { if (!session.isEstablished()) { setupAndProvision(); return; } byte[] configData = createWiFiConfig(ssid, password); session.sendDataToDevice(ESPConstants.HANDLER_PROV_CONFIG, configData, new ResponseListener() { @Override public void onSuccess(byte[] returnData) { // Config sent, now apply it applyConfig(); } @Override public void onFailure(Exception e) { Log.e(TAG, "Config send failed", e); provisionListener.wifiConfigFailed(e); } }); } private void applyConfig() { byte[] applyRequest = createApplyRequest(); session.sendDataToDevice(ESPConstants.HANDLER_PROV_CTRL, applyRequest, new ResponseListener() { @Override public void onSuccess(byte[] returnData) { Log.d(TAG, "WiFi configuration applied"); provisionListener.wifiConfigApplied(); } @Override public void onFailure(Exception e) { Log.e(TAG, "Apply failed", e); provisionListener.wifiConfigApplyFailed(e); } }); } } ``` -------------------------------- ### Start BLE Scan with Filters and Scan Settings Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Initiates a BLE device scan using both ScanFilter and ScanSettings. Requires BLUETOOTH_ADMIN and BLUETOOTH permissions. ```java public void searchBleEspDevices(List filters, ScanSettings scanSettings, BleScanListener bleScannerListener) ``` -------------------------------- ### Check WiFi Security Type Example Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Illustrates how to iterate through a list of WiFi access points and check their security type, specifically identifying WPA2 secured networks. ```java for (WiFiAccessPoint ap : wifiList) { if (ap.getSecurity() == ESPConstants.WIFI_WPA2_PSK) { Log.d(TAG, "WPA2 secured network: " + ap.getWifiName()); } } ``` -------------------------------- ### searchWiFiEspDevices (Prefix Filter) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts Wi-Fi device scanning with an SSID prefix filter. Requires CHANGE_WIFI_STATE and ACCESS_WIFI_STATE permissions. ```APIDOC ## searchWiFiEspDevices (Overload 2: Prefix filter) Starts Wi-Fi device scanning with SSID prefix filter. ### Method public void searchWiFiEspDevices(String prefix, WiFiScanListener wiFiDeviceScanListener) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **prefix** (String) - Required - SSID prefix filter (e.g., "PROV_") - **wiFiDeviceScanListener** (WiFiScanListener) - Required - Callback listener for WiFi scan results ### Permissions Required - `android.permission.CHANGE_WIFI_STATE` - `android.permission.ACCESS_WIFI_STATE` ### Example ```java manager.searchWiFiEspDevices("PROV_", wiFiScanListener); ``` ``` -------------------------------- ### Device Connection Event Handling Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/types.md Example of how to subscribe to device connection events using EventBus and handle different event types, such as device connected. ```java EventBus.getDefault().register(this); @Subscribe public void onDeviceConnectionEvent(DeviceConnectionEvent event) { if (event.getEventType() == ESPConstants.EVENT_DEVICE_CONNECTED) { // Device connected } } ``` -------------------------------- ### Get ESPProvisionManager Instance Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Retrieves the singleton instance of ESPProvisionManager. Requires an Android application context. ```java ESPProvisionManager manager = ESPProvisionManager.getInstance(context); ``` -------------------------------- ### Start BLE Scan with Filters Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Initiates a BLE device scan using a provided list of ScanFilter objects. Requires BLUETOOTH_ADMIN and BLUETOOTH permissions. ```java public void searchBleEspDevices(List filters, BleScanListener bleScannerListener) ``` ```java List filters = new ArrayList<>(); manager.searchBleEspDevices(filters, bleScanListener); ``` -------------------------------- ### searchBleEspDevices (Default) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts BLE device scanning with default settings and no filters. This method requires Bluetooth permissions. ```APIDOC ## searchBleEspDevices (Default) ### Description Starts BLE device scanning with default settings and no filters. ### Method ```java public void searchBleEspDevices(BleScanListener bleScannerListener) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **bleScannerListener** (BleScanListener) - Required - Callback listener for scan events ### Permissions Required - `android.permission.BLUETOOTH_ADMIN` - `android.permission.BLUETOOTH` ### Example ```java manager.searchBleEspDevices(new BleScanListener() { @Override public void scanStartFailed() { // Handle scan start failure } @Override public void onPeripheralFound(BluetoothDevice device, ScanResult scanResult) { // Device found } @Override public void scanCompleted() { // Scan completed } @Override public void onFailure(Exception e) { // Scan failed } }); ``` ``` -------------------------------- ### searchBleEspDevices (ScanSettings only) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts BLE device scanning using specified scan settings. This overload allows for customization of the scanning process itself. ```APIDOC ## searchBleEspDevices (Overload 2: ScanSettings only) ### Description Starts BLE device scanning with scan settings. ### Method ```java public void searchBleEspDevices(ScanSettings scanSettings, BleScanListener bleScannerListener) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **scanSettings** (ScanSettings) - Required - Bluetooth scan settings - **bleScannerListener** (BleScanListener) - Required - Callback listener for scan events ### Permissions Required - `android.permission.BLUETOOTH_ADMIN` - `android.permission.BLUETOOTH` ``` -------------------------------- ### SoftAPTransport Constructor Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-transport.md Initializes a new instance of the SoftAPTransport class. No specific context or setup is required as it utilizes the system's WiFi connection. ```java public SoftAPTransport() ``` -------------------------------- ### Search Wi-Fi Devices (Default) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts scanning for Wi-Fi access points. Requires CHANGE_WIFI_STATE and ACCESS_WIFI_STATE permissions. The results are returned via the provided WiFiScanListener. ```java manager.searchWiFiEspDevices(new WiFiScanListener() { @Override public void onWifiListReceived(ArrayList wifiList) { // Process list of found networks } @Override public void onWiFiScanFailed(Exception e) { // Handle scan failure } }); ``` -------------------------------- ### Get ESPDevice Instance Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Retrieves the previously created or detected ESPDevice instance. Returns null if no device has been created or detected. ```java public ESPDevice getEspDevice() ``` ```java ESPDevice device = manager.getEspDevice(); ``` -------------------------------- ### searchBleEspDevices (Filters + ScanSettings) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts BLE device scanning with both custom filters and scan settings, providing the most control over the discovery process. ```APIDOC ## searchBleEspDevices (Overload 3: Filters + ScanSettings) ### Description Starts BLE device scanning with both filters and settings. ### Method ```java public void searchBleEspDevices(List filters, ScanSettings scanSettings, BleScanListener bleScannerListener) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **filters** (List) - Required - List of BLE scan filters - **scanSettings** (ScanSettings) - Required - Bluetooth scan settings - **bleScannerListener** (BleScanListener) - Required - Callback listener for scan events ### Permissions Required - `android.permission.BLUETOOTH_ADMIN` - `android.permission.BLUETOOTH` ``` -------------------------------- ### Start BLE Device Scanning (Default) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Initiates a BLE device scan using default settings without any name filters. Requires BLUETOOTH and BLUETOOTH_ADMIN permissions. Implement the BleScanListener to handle scan events like device discovery, completion, or failure. ```java manager.searchBleEspDevices(new BleScanListener() { @Override public void scanStartFailed() { // Handle scan start failure } @Override public void onPeripheralFound(BluetoothDevice device, ScanResult scanResult) { // Device found } @Override public void scanCompleted() { // Scan completed } @Override public void onFailure(Exception e) { // Scan failed } }); ``` -------------------------------- ### Custom Serial Transport Implementation Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-transport.md Implement a custom transport using a serial port. This example shows how to send configuration data over a serial connection and handle responses. Requires a `SerialPort` class and `ResponseListener` interface. ```java public class SerialTransport implements Transport { private SerialPort port; public SerialTransport(String portName, int baudRate) { port = new SerialPort(portName, baudRate); } @Override public void sendConfigData(String path, byte[] data, ResponseListener listener) { try { // Send path as prefix port.write(path.getBytes()); // Send data port.write(data); // Read response byte[] response = port.read(); listener.onSuccess(response); } catch (Exception e) { listener.onFailure(e); } } public void close() { port.close(); } } // Usage: Transport transport = new SerialTransport("/dev/ttyUSB0", 115200); Security security = new Security2(); Session session = new Session(transport, security); ``` -------------------------------- ### searchBleEspDevices (Filters only) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts BLE device scanning using a provided list of scan filters. This overload is useful when you need to specify criteria for the devices to discover. ```APIDOC ## searchBleEspDevices (Overload 1: Filters only) ### Description Starts BLE device scanning with scan filters. ### Method ```java public void searchBleEspDevices(List filters, BleScanListener bleScannerListener) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **filters** (List) - Required - List of BLE scan filters - **bleScannerListener** (BleScanListener) - Required - Callback listener for scan events ### Permissions Required - `android.permission.BLUETOOTH_ADMIN` - `android.permission.BLUETOOTH` ### Example ```java List filters = new ArrayList<>(); manager.searchBleEspDevices(filters, bleScanListener); ``` ``` -------------------------------- ### BLE Scan Start Failed Callback Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-listeners.md This method is called when BLE scanning fails to start, for instance, if Bluetooth is turned off. It's a place to prompt the user to enable Bluetooth. ```Java void scanStartFailed() { // Prompt user to enable Bluetooth } ``` -------------------------------- ### Search Wi-Fi Devices (SSID Prefix Filter) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espprovisionmanager.md Starts scanning for Wi-Fi access points with a specific SSID prefix. Requires CHANGE_WIFI_STATE and ACCESS_WIFI_STATE permissions. The results are returned via the provided WiFiScanListener. ```java manager.searchWiFiEspDevices("PROV_", wiFiScanListener); ``` -------------------------------- ### Get Username Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the configured username used for authentication. ```java public String getUserName() ``` -------------------------------- ### Get Device Name Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the currently configured device name or SSID. ```java public String getDeviceName() ``` -------------------------------- ### Connect to Wi-Fi Device (With Credentials) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Initiates a Wi-Fi connection with provided SSID and password. Requires CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, and ACCESS_NETWORK_STATE permissions. ```java @RequiresPermission(allOf = {Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE}) public void connectWiFiDevice(String ssid, String password) ``` ```java device.connectWiFiDevice("PROV_12345678", ""); ``` -------------------------------- ### Handle Device Provisioning Failure by Reason Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-listeners.md Implement this method to react to specific provisioning failure reasons reported by the device, such as authentication failures or network issues. This allows for targeted error handling. ```java @Override public void provisioningFailedFromDevice(ESPConstants.ProvisionFailureReason failureReason) { switch (failureReason) { case AUTH_FAILED: Log.e(TAG, "Device failed to authenticate with WiFi network"); break; case NETWORK_NOT_FOUND: Log.e(TAG, "Device could not find the specified WiFi network"); break; case DEVICE_DISCONNECTED: Log.e(TAG, "Device disconnected during provisioning"); break; case UNKNOWN: Log.e(TAG, "Unknown provisioning failure"); break; } } ``` -------------------------------- ### Get Primary Service UUID Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the primary BLE service UUID for the device. ```java public String getPrimaryServiceUuid() ``` -------------------------------- ### Get Bluetooth Device Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the configured BluetoothDevice object used for BLE connections. ```java public BluetoothDevice getBluetoothDevice() ``` -------------------------------- ### init Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-session.md Initiates the session establishment process, including the security handshake with the device. ```APIDOC ## init Initiates the session establishment process, including the security handshake with the device. ### Signature ```java public void init(byte[] response, final SessionListener sessionListener) throws RuntimeException ``` ### Parameters #### Path Parameters - **response** (byte[]) - Optional - Initial response from device (null for first call) - **sessionListener** (SessionListener) - Required - Callback for session establishment result ### Throws - RuntimeException if handshake fails fatally ### Behavior 1. Calls `security.getNextRequestInSession(response)` to get the next handshake message 2. If request is null, session is established and `sessionListener.OnSessionEstablished()` is called 3. If request is not null, sends request to device via `transport.sendConfigData()` and recursively calls `init()` with the device response ### Example ```java session.init(null, new Session.SessionListener() { @Override public void OnSessionEstablished() { Log.d(TAG, "Secure session established"); // Now safe to send encrypted data to device } @Override public void OnSessionEstablishFailed(Exception e) { Log.e(TAG, "Session establishment failed", e); } }); ``` ``` -------------------------------- ### connectWiFiDevice (Overload 2: With credentials) Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Initiates Wi-Fi connection with SSID and password. Requires CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, and ACCESS_NETWORK_STATE permissions. ```APIDOC ## connectWiFiDevice (Overload 2: With credentials) ### Description Initiates Wi-Fi connection with SSID and password. ### Method void ### Parameters #### Path Parameters - **ssid** (String) - Yes - Network SSID (device AP name) - **password** (String) - No - Network password (empty string for open networks) ### Permissions Required - `android.permission.CHANGE_WIFI_STATE` - `android.permission.ACCESS_WIFI_STATE` - `android.permission.ACCESS_NETWORK_STATE` ### Request Example ```java device.connectWiFiDevice("PROV_12345678", ""); ``` ``` -------------------------------- ### Get WiFi Access Point Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the currently configured WiFiAccessPoint. Returns null if not configured. ```java public WiFiAccessPoint getWifiDevice() ``` -------------------------------- ### Get Proof of Possession Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the currently configured proof of possession (PoP) value from the device. ```java public String getProofOfPossession() ``` -------------------------------- ### resetWifiStatus Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Resets the WiFi provisioning status on the device. This is useful for re-initiating the WiFi setup process. ```APIDOC ## resetWifiStatus Resets the WiFi provisioning status on the device. ```java public void resetWifiStatus(final ResponseListener listener) ``` ### Parameters #### Path Parameters - **listener** (ResponseListener) - Required - Callback for reset result ### Request Example ```java device.resetWifiStatus(new ResponseListener() { @Override public void onSuccess(byte[] returnData) { Log.d(TAG, "WiFi status reset successful"); } @Override public void onFailure(Exception e) { Log.e(TAG, "Reset failed", e); } }); ``` ``` -------------------------------- ### QR Code Provisioning Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-index.md Use this method to initialize the manager and scan a QR code for device provisioning. Implement the QRCodeScanListener to handle scan results and device detection. ```java ESPProvisionManager manager = ESPProvisionManager.getInstance(context); manager.scanQRCode(previewView, activity, new QRCodeScanListener() { @Override public void qrCodeScanned() { // Show loading } @Override public void deviceDetected(ESPDevice device) { // Device found, connect device.connectToDevice(); } @Override public void onFailure(Exception e) { // Show error } @Override public void onFailure(Exception e, String data) { // Invalid QR code } }); ``` -------------------------------- ### BLETransport Constructor Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-transport.md Initializes the BLETransport with an Android application context. Required for BLE communication setup. ```java public BLETransport(Context context) ``` -------------------------------- ### Import Camera Preview and Graphics Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-index.md Import classes for camera preview functionalities, specifically for QR code scanning, and graphic overlay components. ```java // Camera Preview (QR code scanning) import com.espressif.provisioning.CameraSourcePreview; import com.espressif.provisioning.GraphicOverlay; ``` -------------------------------- ### Get Transport Type Source: https://github.com/espressif/esp-idf-provisioning-android/blob/master/_autodocs/api-reference-espdevice.md Retrieves the configured transport type for the device connection. Possible values are TRANSPORT_BLE or TRANSPORT_SOFTAP. ```java public ESPConstants.TransportType getTransportType() ```