diff --git a/services/api.ts b/services/api.ts index bed0e8f..edaaa58 100644 --- a/services/api.ts +++ b/services/api.ts @@ -1782,6 +1782,65 @@ class ApiService { } } + /** + * Attach device to deployment via Legacy API + * Uses set_deployment endpoint to link a WP sensor to a beneficiary's deployment + * + * @param deploymentId - The deployment ID to attach the device to + * @param wellId - The device's well_id (from BLE scan, e.g., 497) + * @param ssid - WiFi network SSID + * @param password - WiFi network password + */ + async attachDeviceToDeployment( + deploymentId: number, + wellId: number, + ssid: string, + password: string + ): Promise> { + try { + const creds = await this.getLegacyWebViewCredentials(); + if (!creds) { + return { ok: false, error: { message: 'Not authenticated with Legacy API', code: 'UNAUTHORIZED' } }; + } + + // Call set_deployment to attach device + const formData = new URLSearchParams({ + function: 'set_deployment', + user_name: creds.userName, + token: creds.token, + deployment: deploymentId.toString(), + devices: JSON.stringify([wellId]), + wifis: JSON.stringify([`${ssid}|${password}`]), + reuse_existing_devices: '1', + }); + + console.log('[API] attachDeviceToDeployment: deployment=', deploymentId, 'wellId=', wellId, 'ssid=', ssid); + + const response = await fetch(API_BASE_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: formData.toString(), + }); + + if (!response.ok) { + return { ok: false, error: { message: 'Failed to attach device to deployment' } }; + } + + const data = await response.json(); + + if (data.status !== '200 OK') { + console.error('[API] attachDeviceToDeployment failed:', data); + return { ok: false, error: { message: data.message || 'Failed to attach device' } }; + } + + console.log('[API] attachDeviceToDeployment success'); + return { ok: true, data: { success: true } }; + } catch (error: any) { + console.error('[API] attachDeviceToDeployment error:', error); + return { ok: false, error: { message: error.message || 'Network error', code: 'NETWORK_ERROR' } }; + } + } + /** * Detach device from beneficiary */