All files / services espProvisioning.ts

0% Statements 0/77
0% Branches 0/37
0% Functions 0/13
0% Lines 0/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * ESP32 WiFi Provisioning Service
 *
 * Handles BLE communication with WellNuo ESP32 sensors (WP_xxx_xxxxxx)
 * for WiFi configuration and provisioning.
 *
 * Uses @orbital-systems/react-native-esp-idf-provisioning which wraps
 * Espressif's official provisioning libraries.
 *
 * NOTE: This module requires a development build. In Expo Go, a mock
 * implementation is used that returns empty results.
 */
 
import { Platform, PermissionsAndroid, Alert } from 'react-native';
import Constants from 'expo-constants';
 
// Check if we're running in Expo Go (no native modules available)
const isExpoGo = Constants.appOwnership === 'expo';
 
// WellNuo device prefix (matches WP_xxx_xxxxxx pattern)
const WELLNUO_DEVICE_PREFIX = 'WP_';
 
export interface WellNuoDevice {
  name: string;
  device: any; // ESPDevice when native module available
  wellId?: string;      // Extracted from name: WP_<wellId>_<mac>
  macPart?: string;     // Last part of MAC address
}
 
export interface WifiNetwork {
  ssid: string;
  rssi: number;
  auth: string;
}
 
// Dynamic import types - will be null in Expo Go
let ESPProvisionManager: any = null;
let ESPTransport: any = null;
let ESPSecurity: any = null;
 
// Try to load native module only in development builds
if (!isExpoGo) {
  try {
    const espModule = require('@orbital-systems/react-native-esp-idf-provisioning');
    ESPProvisionManager = espModule.ESPProvisionManager;
    ESPTransport = espModule.ESPTransport;
    ESPSecurity = espModule.ESPSecurity;
  } catch (e) {
    // Native provisioning module not available
  }
}
 
class ESPProvisioningService {
  private connectedDevice: any | null = null;
  private isScanning = false;
 
  /**
   * Check if ESP provisioning is available (development build only)
   */
  isAvailable(): boolean {
    return ESPProvisionManager !== null;
  }
 
  /**
   * Request necessary permissions for BLE on Android
   */
  async requestPermissions(): Promise<boolean> {
    if (!this.isAvailable()) {
      return false;
    }
 
    if (Platform.OS !== 'android') {
      return true;
    }
 
    try {
      const granted = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      ]);
 
      const allGranted = Object.values(granted).every(
        (status) => status === PermissionsAndroid.RESULTS.GRANTED
      );
 
      return allGranted;
    } catch (error) {
      return false;
    }
  }
 
  /**
   * Scan for WellNuo ESP32 devices
   * Returns list of devices matching WP_xxx_xxxxxx pattern
   */
  async scanForDevices(timeoutMs = 10000): Promise<WellNuoDevice[]> {
    if (!this.isAvailable()) {
      Alert.alert(
        'Development Build Required',
        'WiFi provisioning requires a development build. This feature is not available in Expo Go.',
        [{ text: 'OK' }]
      );
      return [];
    }
 
    if (this.isScanning) {
      return [];
    }
 
    const hasPermissions = await this.requestPermissions();
    if (!hasPermissions) {
      throw new Error('Bluetooth permissions not granted');
    }
 
    this.isScanning = true;
 
    try {
      const devices = await ESPProvisionManager.searchESPDevices(
        WELLNUO_DEVICE_PREFIX,
        ESPTransport.ble,
        ESPSecurity.unsecure
      );
 
      return devices.map((device: any) => {
        // Parse device name: WP_<wellId>_<macPart>
        const parts = device.name?.split('_') || [];
        return {
          name: device.name || 'Unknown',
          device,
          wellId: parts[1],
          macPart: parts[2],
        };
      });
    } catch (error) {
      throw error;
    } finally {
      this.isScanning = false;
    }
  }
 
  /**
   * Connect to a WellNuo device
   * @param device - The device to connect to
   * @param proofOfPossession - Optional PoP for secure devices
   */
  async connect(
    device: any,
    proofOfPossession?: string
  ): Promise<boolean> {
    if (!this.isAvailable()) {
      return false;
    }
 
    if (this.connectedDevice) {
      await this.disconnect();
    }
 
    try {
      // Try without PoP first (unsecure mode)
      await device.connect(proofOfPossession || null);
      this.connectedDevice = device;
      return true;
    } catch (error) {
      throw error;
    }
  }
 
  /**
   * Scan for available WiFi networks through connected device
   */
  async scanWifiNetworks(): Promise<WifiNetwork[]> {
    if (!this.isAvailable()) {
      return [];
    }
 
    if (!this.connectedDevice) {
      throw new Error('Not connected to any device');
    }
 
    try {
      const wifiList = await this.connectedDevice.scanWifiList();
 
      return wifiList.map((wifi: any) => ({
        ssid: wifi.ssid,
        rssi: wifi.rssi,
        auth: this.getAuthModeName(wifi.auth),
      }));
    } catch (error) {
      throw error;
    }
  }
 
  /**
   * Provision device with WiFi credentials
   * @param ssid - WiFi network name
   * @param password - WiFi password
   */
  async provisionWifi(ssid: string, password: string): Promise<boolean> {
    if (!this.isAvailable()) {
      return false;
    }
 
    if (!this.connectedDevice) {
      throw new Error('Not connected to any device');
    }
 
    try {
      await this.connectedDevice.provision(ssid, password);
      return true;
    } catch (error) {
      throw error;
    }
  }
 
  /**
   * Disconnect from current device
   */
  async disconnect(): Promise<void> {
    if (!this.connectedDevice) {
      return;
    }
 
    try {
      this.connectedDevice.disconnect();
      this.connectedDevice = null;
    } catch (error) {
      this.connectedDevice = null;
    }
  }
 
  /**
   * Check if currently connected to a device
   */
  isConnected(): boolean {
    return this.connectedDevice !== null;
  }
 
  /**
   * Get currently connected device name
   */
  getConnectedDeviceName(): string | null {
    return this.connectedDevice?.name || null;
  }
 
  /**
   * Convert auth mode number to human-readable string
   */
  private getAuthModeName(authMode: number): string {
    const modes: Record<number, string> = {
      0: 'Open',
      1: 'WEP',
      2: 'WPA2 Enterprise',
      3: 'WPA2 PSK',
      4: 'WPA PSK',
      5: 'WPA/WPA2 PSK',
    };
    return modes[authMode] || `Unknown (${authMode})`;
  }
}
 
// Export singleton instance
export const espProvisioning = new ESPProvisioningService();
 
// Export types for components
export type ESPDevice = any;