WellNuo/docs/SENSORS_SYSTEM.md
Sergei 9f9124fdab feat(sensors): Batch sensor setup with progress UI and error handling
- Add updateDeviceMetadata and attachDeviceToDeployment API methods
- Device Settings: editable location/description fields with save
- Equipment screen: location placeholder and quick navigation to settings
- Add Sensor: multi-select with checkboxes, select all/deselect all
- Setup WiFi: batch processing of multiple sensors sequentially
- BatchSetupProgress: animated progress bar, step indicators, auto-scroll
- SetupResultsScreen: success/failed/skipped summary with retry options
- Error handling: modal with Retry/Skip/Cancel All buttons
- Documentation: SENSORS_SYSTEM.md with full BLE protocol and flows

Implemented via Ralphy CLI autonomous agent in ~43 minutes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-19 23:24:22 -08:00

14 KiB

WellNuo Sensors System Documentation

Overview

This document describes the architecture and user flows for managing BLE/WiFi sensors in the WellNuo app. Sensors monitor elderly people (beneficiaries) and send activity data via WiFi.


Table of Contents

  1. Entities
  2. Data Storage
  3. Entity Relationships
  4. User Flows
  5. BLE Protocol
  6. Legacy API Endpoints
  7. UI Screens
  8. Batch Sensor Setup
  9. Error Handling
  10. Open Questions

Entities

User (Caregiver)

The person who uses the app to monitor beneficiaries.

  • Can have multiple beneficiaries
  • Stored in: WellNuo API

Beneficiary

An elderly person being monitored.

  • Has profile data (name, avatar, date of birth)
  • Linked to exactly one Deployment
  • One user can have multiple beneficiaries (e.g., 5)
  • Stored in: WellNuo API

Deployment

A "household" in Legacy API where the beneficiary lives.

  • Contains address, timezone
  • Contains array of devices
  • One beneficiary = one deployment
  • Stored in: Legacy API

Device (WP Sensor)

Physical BLE/WiFi sensor installed in beneficiary's home.

  • Measures activity, temperature, etc.
  • Sends data via WiFi to Legacy API
  • Up to 5 sensors per beneficiary
  • Stored in: Legacy API

Data Storage

Data Storage Notes
User profile WellNuo API Our database
Beneficiary profile WellNuo API Our database
Beneficiary.deploymentId WellNuo API Links to Legacy
Deployment Legacy API External service
Device Legacy API External service
Sensor readings Legacy API External service

Important: We do NOT have access to Legacy API source code. We only use their API endpoints.


Entity Relationships

User (WellNuo API)
 │
 ├── Beneficiary 1
 │    └── deploymentId: 22 ──► Deployment 22 (Legacy API)
 │                              ├── Device (WP_497)
 │                              ├── Device (WP_498)
 │                              ├── Device (WP_499)
 │                              ├── Device (WP_500)
 │                              └── Device (WP_501)
 │
 ├── Beneficiary 2
 │    └── deploymentId: 23 ──► Deployment 23 (Legacy API)
 │                              ├── Device (WP_510)
 │                              └── Device (WP_511)
 │
 ├── Beneficiary 3
 │    └── deploymentId: 24 ──► Deployment 24 (Legacy API)
 │                              └── (no devices yet)
 │
 └── ... up to N beneficiaries

Key Points

  1. Each beneficiary has their own deployment
  2. Devices are attached to deployment, not directly to beneficiary
  3. When adding sensors, user must first select which beneficiary
  4. Sensors found via BLE scan could belong to ANY beneficiary's home

User Flows

Flow 1: View Sensors for a Beneficiary

1. User opens Beneficiaries list
2. User taps on a specific beneficiary (e.g., "Maria")
3. User navigates to Equipment tab
4. App fetches:
   a. GET /me/beneficiaries/{id} → get deploymentId
   b. POST Legacy API device_list_by_deployment → get devices
5. App displays sensor list with status (online/warning/offline)

Flow 2: Add Sensors (Batch)

Prerequisites:

  • User has selected a specific beneficiary
  • User is physically at that beneficiary's location
  • Sensors are powered on
1. User is on Equipment screen for "Maria"
2. User taps "Add Sensor"
3. App shows instructions
4. User taps "Scan for Sensors"
5. App performs BLE scan (10 seconds)
6. App filters devices with name starting with "WP_"
7. App shows list with checkboxes (all selected by default)
8. User can uncheck sensors they don't want to add
9. User taps "Add Selected (N)"
10. App shows WiFi selection screen
11. User selects WiFi network (from sensor's scan)
12. User enters WiFi password
13. User taps "Connect All"
14. App performs batch setup (see Batch Sensor Setup section)
15. App shows results screen
16. User taps "Done"

Flow 3: Edit Sensor Location/Description

TODO: Not implemented yet. Needs UI.

1. User taps on a sensor in Equipment list
2. App shows Device Settings screen
3. User can edit:
   - location (text field, e.g., "Bedroom, near bed")
   - description (text field)
4. User taps "Save"
5. App calls Legacy API device_form to update

Flow 4: Detach Sensor

1. User taps detach button on a sensor
2. App shows confirmation dialog
3. User confirms
4. App calls Legacy API device_form with deployment_id=0
5. Sensor is unlinked from this beneficiary
6. Sensor can now be attached to another beneficiary

BLE Protocol

Service UUID

4fafc201-1fb5-459e-8fcc-c5c9c331914b

Characteristic UUID

beb5483e-36e1-4688-b7f5-ea07361b26a8

Device Name Format

WP_{wellId}_{mac6chars}

Example: WP_497_81a14c
- wellId: 497
- mac last 6 chars: 81a14c

Commands

Command Format Description
PIN Unlock pin|7856 Unlock device for configuration
Get WiFi List w Request available WiFi networks
Set WiFi W|SSID,PASSWORD Configure WiFi connection
Get WiFi Status a Get current WiFi connection
Reboot s Restart the sensor
Disconnect D Disconnect BLE

WiFi List Response Format

SSID1,-55;SSID2,-70;SSID3,-80

Where -55, -70, -80 are RSSI values in dBm.

Timeouts

  • Scan: 10 seconds
  • Command response: 5 seconds

WiFi Status Response (command a)

When connected via BLE, you can query current WiFi status:

Command: a

Response format:

{ssid},{rssi},{connected}

Example: Home_Network,-62,1
- ssid: "Home_Network"
- rssi: -62 dBm
- connected: 1 (true) or 0 (false)

Use cases:

  • Show which WiFi network the sensor is connected to
  • Display WiFi signal strength
  • Diagnose connectivity issues

Legacy API Endpoints

Base URL: https://eluxnetworks.net/function/well-api/api

Authentication: Form-encoded POST with user_name and token

device_list_by_deployment

Get all devices for a deployment.

Request:

function=device_list_by_deployment
user_name={username}
token={token}
deployment_id={id}
first=0
last=100

Response:

{
  "result_list": [
    [deviceId, wellId, mac, lastSeenTimestamp, location, description],
    [1, 497, "142B2F81A14C", 1705426800, "Bedroom", "Main sensor"],
    [2, 498, "142B2F82B25D", 1705426700, "", ""]
  ]
}

device_form

Create or update a device.

Request:

function=device_form
user_name={username}
token={token}
well_id={wellId}
device_mac={mac}
location={location}
description={description}
deployment_id={deploymentId}

request_devices

Get online devices (with fresh=true filter).

Request:

function=request_devices
user_name={username}
token={token}
deployment_id={id}
group_id=All
location=All
fresh=true

UI Screens

Equipment Screen

Path: /(tabs)/beneficiaries/:id/equipment

Features:

  • Summary card (total/online/warning/offline counts)
  • List of connected sensors
  • BLE scan button for nearby sensors
  • Detach sensor button

Current limitations:

  • No editing of location/description

Add Sensor Screen

Path: /(tabs)/beneficiaries/:id/add-sensor

Features:

  • Instructions (4 steps)
  • Scan button
  • List of found devices with RSSI

TODO: Add checkbox selection for batch setup

Setup WiFi Screen

Path: /(tabs)/beneficiaries/:id/setup-wifi

Features:

  • WiFi network list (from sensor)
  • Password input
  • Connect button

TODO: Support batch setup (multiple sensors, one WiFi config)

Device Settings Screen

Path: /(tabs)/beneficiaries/:id/device-settings/:deviceId

Features:

  • View Well ID, MAC, Deployment ID
  • Current WiFi status
  • Change WiFi button
  • Reboot button

TODO: Add location/description editing


Batch Sensor Setup

Overview

When adding multiple sensors (up to 5), the app should:

  1. Allow selecting multiple sensors from BLE scan
  2. Configure WiFi once for all sensors
  3. Process sensors sequentially with progress UI
  4. Handle errors gracefully

Sensor States During Setup

pending      — waiting in queue
connecting   — BLE connection in progress
unlocking    — sending PIN command
setting_wifi — configuring WiFi
attaching    — calling Legacy API to link to deployment
rebooting    — restarting sensor
success      — completed successfully
error        — failed (with error message)
skipped      — user chose to skip after error

Progress UI

Connecting sensors to WiFi "Home_Network"...

WP_497_81a14c
  ✓ Connected
  ✓ Unlocked
  ✓ WiFi configured
  ✓ Attached to Maria
  ● Rebooting...

WP_498_82b25d
  ✓ Connected
  ✓ Unlocked
  ● Setting WiFi...

WP_499_83c36e
  ○ Waiting...

WP_500_84d47f
  ✗ Error: Could not connect
    [Retry] [Skip]

Results Screen

Setup Complete

Successfully connected:
  ✓ WP_497_81a14c
  ✓ WP_498_82b25d
  ✓ WP_499_83c36e

Failed:
  ✗ WP_500_84d47f — Connection timeout
    [Retry This Sensor]

[Done]

Error Handling

Possible Errors

Error Cause User Message Actions
BLE Connect Failed Sensor too far, off, or busy "Could not connect. Move closer or check if sensor is on." Retry, Skip
PIN Unlock Failed Wrong PIN (unlikely) "Could not unlock sensor." Retry, Skip
WiFi Set Failed Command timeout "Could not configure WiFi." Retry, Skip
API Attach Failed No internet, server down "Could not register sensor. Check internet." Retry, Skip
Timeout Sensor not responding "Sensor not responding." Retry, Skip

Error Recovery Options

When an error occurs on sensor N:

  1. Pause the batch process
  2. Show error with options:
    • [Retry] — try this sensor again
    • [Skip] — move to next sensor
    • [Cancel All] — abort entire process
  3. Continue based on user choice

All Sensors Failed

Setup Failed

Could not connect any sensors.

Possible reasons:
• Sensors are too far away
• Sensors are not powered on
• Bluetooth is disabled

[Try Again] [Cancel]

Logging

For debugging, log all operations:

[BLE] Starting batch setup for 5 sensors
[BLE] [1/5] WP_497 — connecting...
[BLE] [1/5] WP_497 — connected (took 1.2s)
[BLE] [1/5] WP_497 — sending PIN...
[BLE] [1/5] WP_497 — unlocked
[BLE] [1/5] WP_497 — setting WiFi "Home"...
[BLE] [1/5] WP_497 — WiFi configured
[API] [1/5] WP_497 — attaching to deployment 22...
[API] [1/5] WP_497 — attached (device_id: 1)
[BLE] [1/5] WP_497 — rebooting...
[BLE] [1/5] WP_497 — SUCCESS (total: 8.5s)

[BLE] [2/5] WP_498 — connecting...
[BLE] [2/5] WP_498 — ERROR: connection timeout after 5s

Sensor Activity & Status

Status Calculation

Sensor status is calculated based on lastSeen timestamp from Legacy API:

Time since last signal Status Color Meaning
< 5 minutes online Green Sensor is working normally
5-60 minutes warning Yellow Possible issue, check sensor
> 60 minutes offline Red Sensor is not sending data

Activity Display in UI

Equipment Screen shows for each sensor:

  • Sensor name (WP_497_81a14c)
  • Status badge (Online/Warning/Offline)
  • Last activity time ("5 min ago", "2 hours ago")
  • Location label (if set)

Detailed WiFi Status (via BLE)

When user opens Device Settings for an ONLINE sensor, app can:

  1. Connect to sensor via BLE
  2. Send command a (Get WiFi Status)
  3. Display:
    • WiFi network name
    • Signal strength (RSSI in dBm or as Excellent/Good/Fair/Weak)
    • Connection status

WiFi Signal Strength Interpretation:

RSSI Quality
-50 or better Excellent
-50 to -60 Good
-60 to -70 Fair
-70 or worse Weak

This helps diagnose connectivity issues — if sensor goes offline, user can check if WiFi signal is weak.


Open Questions

Q1: Multiple Beneficiaries Context

Question: User has 5 beneficiaries. When scanning BLE, sensors from different locations might appear. How to handle?

Decision: Trust the user. They select beneficiary first, then add sensors. If they make a mistake, they can detach and reattach to correct beneficiary. No confirmation needed.

Q2: WiFi Configuration Timing

Question: When should user set sensor location label?

Options:

  • A) During initial setup (add step after WiFi)
  • B) Later, in Device Settings screen
  • C) Both (optional during setup, editable later)

Q3: Background Processing

Question: If user closes app during batch setup, what happens?

Options:

  • A) Continue in background (complex)
  • B) Cancel everything (simple, but frustrating)
  • C) Pause and resume when app reopens

Q4: Sensor Already Attached

Question: What if scanned sensor is already attached to ANOTHER beneficiary (different deployment)?

Options:

  • A) Show error: "This sensor is already in use"
  • B) Offer to move it: "Move to Maria's home?"
  • C) Just attach it (will detach from previous)

File References

File Description
services/ble/BLEManager.ts BLE operations
services/ble/types.ts BLE types
services/ble/MockBLEManager.ts Mock for simulator
contexts/BLEContext.tsx BLE React context
services/api.ts API methods
types/index.ts WPSensor type (lines 47-59)
app/(tabs)/beneficiaries/[id]/equipment.tsx Equipment screen
app/(tabs)/beneficiaries/[id]/add-sensor.tsx Add sensor screen
app/(tabs)/beneficiaries/[id]/setup-wifi.tsx WiFi setup screen
app/(tabs)/beneficiaries/[id]/device-settings/[deviceId].tsx Device settings

Revision History

Date Author Changes
2026-01-19 Claude Initial documentation