WellNuo/docs/MQTT_NOTIFICATIONS_ARCHITECTURE.md
Sergei 1dd7eb8289 Remove hardcoded credentials and use environment variables
- Remove hardcoded database credentials from all scripts
- Remove hardcoded Legacy API tokens from backend scripts
- Remove hardcoded MQTT credentials from mqtt-test.js
- Update backend/.env.example with DB_HOST, DB_USER, DB_PASSWORD, DB_NAME
- Update backend/.env.example with LEGACY_API_TOKEN and MQTT credentials
- Add dotenv config to all scripts requiring credentials
- Create comprehensive documentation:
  - scripts/README.md - Root scripts usage
  - backend/scripts/README.md - Backend scripts documentation
  - MQTT_TESTING.md - MQTT testing guide
  - SECURITY_CREDENTIALS_CLEANUP.md - Security changes summary

All scripts now read credentials from backend/.env instead of hardcoded values.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-29 12:13:32 -08:00

524 lines
16 KiB
Markdown

# WellNuo MQTT & Notifications Architecture
## Overview
This document describes the notification system architecture for WellNuo app.
**Key insight**: There are TWO parallel notification systems:
1. **MQTT** — Real sensor data from IoT devices → WellNuo Backend → Process & Notify
2. **eluxnetworks API** — Direct notification sending via `send_walarm` function
---
## 1. System Architecture
### Two Notification Paths
```
PATH 1: MQTT (Real Sensor Data)
┌────────────────────┐ ┌──────────────────────────────────┐ ┌─────────────────────┐
│ IoT Sensors │ ──▶ │ MQTT Broker │ ──▶ │ WellNuo Backend │
│ (eluxnetworks) │ │ mqtt.eluxnetworks.net:1883 │ │ (subscribes) │
└────────────────────┘ └──────────────────────────────────┘ └──────────────────────┘
┌─────────────────────┐
│ Process Alert │
│ → Find Users │
│ → Send Notifications│
└─────────────────────┘
PATH 2: eluxnetworks API (Direct Notification)
┌────────────────────┐ ┌──────────────────────────────────┐ ┌─────────────────────┐
│ API Call │ ──▶ │ https://eluxnetworks.net/ │ ──▶ │ eluxnetworks │
│ (send_walarm) │ │ function/well-api/api │ │ Backend │
└────────────────────┘ └──────────────────────────────────┘ └──────────────────────┘
┌─────────────────────┐
│ Send via: │
│ MSG, EMAIL, │
│ SMS, PHONE │
└─────────────────────┘
```
### Important: These are SEPARATE systems!
- **MQTT** sends data to WellNuo Backend which then processes and sends notifications
- **send_walarm API** sends notifications DIRECTLY through eluxnetworks infrastructure
- `send_walarm` does NOT generate MQTT messages — it's a direct notification API
---
## 2. MQTT System (Path 1)
### Connection Details
- **Broker**: `mqtt://mqtt.eluxnetworks.net:1883`
- **Username**: `anandk`
- **Password**: `anandk_8`
### Topic Format
```
/well_{deployment_id}
```
Example: `/well_21`, `/well_29`, `/well_38`
### Message Format
```json
{
"Command": "REPORT",
"body": "alert text describing what happened",
"time": 1706000000
}
```
### Command Types
| Command | Description |
|---------|-------------|
| `REPORT` | Sensor alert - needs processing |
| `CREDS` | Device credentials - ignore |
### MQTT → WellNuo Backend Flow
```
1. Sensor sends MQTT message
2. WellNuo Backend receives message (mqtt.js)
3. Save to `mqtt_alerts` table
4. Classify alert type (EMERGENCY vs ACTIVITY)
5. Find users with access to this deployment
6. Check user notification settings
7. Send notifications (Push, Email, SMS, Phone)
8. Log to `notification_history` table
```
---
## 3. eluxnetworks API (Path 2)
### API Endpoint
```
POST https://eluxnetworks.net/function/well-api/api
```
### Authentication
**Step 1: Get Token**
```bash
curl -X POST "https://eluxnetworks.net/function/well-api/api" \
--data-urlencode "function=credentials" \
--data-urlencode "user_name=robster" \
--data-urlencode "ps=rob2" \
--data-urlencode "clientId=001" \
--data-urlencode "nonce=111"
# Response: {"token": "eyJhbGc...", "ok": 1, "status": "200 OK"}
```
**Step 2: Use Token for API calls**
### Available Functions
| Function | Description |
|----------|-------------|
| `credentials` | Login, get JWT token |
| `send_walarm` | Send notification via specific channel |
| `store_alarms` | Update device alarm configuration |
| `alarm_on_off` | Enable/disable alarms |
| `get_alarm_state` | Get current alarm state |
### send_walarm Parameters
| Parameter | Required | Description |
|-----------|----------|-------------|
| `function` | ✅ | Always `send_walarm` |
| `token` | ✅ | JWT token from credentials |
| `user_name` | ✅ | Username (robster) |
| `deployment_id` | ✅ | Target deployment (e.g., 21) |
| `method` | ✅ | MSG, EMAIL, SMS, or PHONE |
| `content` | ✅ | Alert message text |
| `location` | ❌ | Room/area name |
| `feature` | ❌ | Alert type (stuck, absent, temperature, etc.) |
| `test_only` | ❌ | `true` = dry run, `false` = send real |
| `action` | ❌ | `send_to_me` or `send_to_all` |
### ✅ API Testing Results (2026-01-27)
All notification methods tested and **WORKING**:
```bash
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
# MSG (Push notification) ✅ WORKS
curl -X POST "https://eluxnetworks.net/function/well-api/api" \
--data-urlencode "function=send_walarm" \
--data-urlencode "token=$TOKEN" \
--data-urlencode "user_name=robster" \
--data-urlencode "deployment_id=21" \
--data-urlencode "method=MSG" \
--data-urlencode "content=Test push notification" \
--data-urlencode "test_only=false" \
--data-urlencode "action=send_to_me"
# Response: {"ok": 1, "status": "200 OK"}
# EMAIL ✅ WORKS
# Same request with method=EMAIL
# SMS ✅ WORKS
# Same request with method=SMS
# PHONE ✅ WORKS
# Same request with method=PHONE
```
**Important**: These notifications go through eluxnetworks infrastructure, NOT through WellNuo backend!
---
## 4. Alert Types (from devices table)
The legacy system defines these alert types in `devices.alert_details`:
### Alert Categories
| # | Type | Description | Warning → Alarm Flow |
|---|------|-------------|---------------------|
| 0 | **STUCK** | Person not moving for too long | Warning (7h) → Alarm (10h) |
| 1 | **ABSENT** | Person not detected | Warning (20min) → Alarm |
| 2 | **TEMP_HIGH** | High temperature | Warning (80°F) → Alarm (90°F) |
| 3 | **TEMP_LOW** | Low temperature | Warning (60°F) → Alarm (50°F) |
| 4 | **RADAR** | Movement detected | Immediate |
| 5 | **PRESSURE** | Pressure sensor (bed?) | Threshold-based |
| 6 | **LIGHT** | Light sensor | Threshold-based |
| 7 | **SMELL** | Smell/gas detection | Immediate |
### Example device_alarms configuration:
```json
{
"enabled_alarms": "000110101010",
"stuck_minutes_warning": 420,
"stuck_warning_method_0": "SMS",
"stuck_minutes_alarm": 600,
"stuck_alarm_method_1": "PHONE",
"absent_minutes_warning": 20,
"absent_warning_method_2": "SMS",
"absent_minutes_alarm": 30,
"absent_alarm_method_3": "PHONE",
"temperature_high_warning": "80",
"temperature_high_warning_method_4": "SMS",
"temperature_high_alarm": "90",
"temperature_high_alarm_method_5": "PHONE",
"temperature_low_warning": "60",
"temperature_low_warning_method_6": "SMS",
"temperature_low_alarm": "50",
"temperature_low_alarm_method_7": "PHONE",
"radar_alarm_method_8": "MSG",
"pressure_threshold": "15.0",
"pressure_alarm_method_9": "MSG",
"light_threshold": "150.0",
"light_alarm_method_10": "MSG",
"smell_alarm_method_11": "EMAIL",
"rearm_policy": "1H",
"filter": "6"
}
```
---
## 5. Notification Channels
### Available Methods
| Method | Description | eluxnetworks API | WellNuo Backend |
|--------|-------------|------------------|-----------------|
| `MSG` | Push notification | ✅ Works | ✅ Implemented (Expo Push) |
| `EMAIL` | Email notification | ✅ Works | ⚠️ SMTP configured, not connected |
| `SMS` | Text message | ✅ Works | ❌ Need Twilio |
| `PHONE` | Voice call | ✅ Works | ❌ Need Twilio/LiveKit |
### Key Difference
- **eluxnetworks API** (`send_walarm`) — all 4 channels work NOW
- **WellNuo Backend** — only Push works, others need implementation
---
## 6. User Roles
From `user_access` table:
| Role | Permissions | Notifications |
|------|-------------|---------------|
| **Custodian** | Full rights, owner, can delete | ✅ Receives all |
| **Guardian** | High rights, can manage & invite | ✅ Receives all |
| **Caretaker** | View only | ✅ Receives all |
**All roles receive notifications!**
---
## 7. WellNuo Classification Logic
### Simplified for WellNuo App
| Classification | Alert Types | Behavior |
|---------------|-------------|----------|
| **EMERGENCY** | fall, sos, emergency, stuck_alarm, absent_alarm | ALL channels, ALL users, ignore settings |
| **ACTIVITY** | Everything else | Per user settings, respect quiet hours |
### Body text → Classification mapping
```javascript
const bodyLower = alert.body.toLowerCase();
if (bodyLower.includes('emergency') ||
bodyLower.includes('fall') ||
bodyLower.includes('sos') ||
bodyLower.includes('stuck') ||
bodyLower.includes('absent')) {
return 'EMERGENCY';
}
return 'ACTIVITY';
```
---
## 8. Notification Settings
### Current: Global per user
Table: `notification_settings`
- `push_enabled`
- `email_enabled`
- `sms_enabled`
- `quiet_hours_enabled`
- `quiet_hours_start`
- `quiet_hours_end`
### Needed: Per user + per beneficiary
**New table**: `user_beneficiary_notification_prefs`
| Column | Type | Default | Description |
|--------|------|---------|-------------|
| user_id | UUID | - | User reference |
| beneficiary_id | UUID | - | Beneficiary reference |
| push_enabled | boolean | true | Push notifications |
| email_enabled | boolean | true | Email notifications |
| sms_enabled | boolean | true | SMS notifications |
| call_enabled | boolean | false | Phone calls (only emergency) |
| quiet_hours_enabled | boolean | false | Enable quiet hours |
| quiet_hours_start | time | 22:00 | Quiet period start |
| quiet_hours_end | time | 07:00 | Quiet period end |
**Created automatically** when user gets access to beneficiary.
---
## 9. Notification Flows
### EMERGENCY Flow
```
Alert received (fall, sos, stuck, absent)
Find ALL users with access to beneficiary
For EACH user (ignore settings!):
├── Send Push immediately
├── Send Email immediately
├── Send SMS immediately
└── Make Phone Call immediately
Log all results to notification_history
```
### ACTIVITY Flow
```
Alert received (other types)
Find ALL users with access to beneficiary
For EACH user:
├── Check quiet_hours → if active, SKIP (except emergency)
├── Check push_enabled → if ON, send Push
├── Check email_enabled → if ON, send Email
└── Check sms_enabled → if ON, send SMS
Log all results to notification_history
```
---
## 10. Testing
### Test MQTT (Sensor Simulation)
```bash
cd ~/Desktop/WellNuo
# Monitor deployment 21 (Ferdinand)
node mqtt-test.js
# Monitor specific deployment
node mqtt-test.js 42
# Send test alert (simulates sensor)
node mqtt-test.js send "Test emergency alert"
node mqtt-test.js send "fall detected"
```
### Test eluxnetworks API (Direct Notification)
**Step 1: Get token**
```bash
curl -s -X POST "https://eluxnetworks.net/function/well-api/api" \
--data-urlencode "function=credentials" \
--data-urlencode "user_name=robster" \
--data-urlencode "ps=rob2" \
--data-urlencode "clientId=001" \
--data-urlencode "nonce=111" | jq -r '.token'
```
**Step 2: Send notification**
```bash
TOKEN="your_token_here"
curl -X POST "https://eluxnetworks.net/function/well-api/api" \
--data-urlencode "function=send_walarm" \
--data-urlencode "token=$TOKEN" \
--data-urlencode "user_name=robster" \
--data-urlencode "deployment_id=21" \
--data-urlencode "method=MSG" \
--data-urlencode "content=Test alert" \
--data-urlencode "test_only=false" \
--data-urlencode "action=send_to_me"
```
### Postman Collection
File: `/api/Wellnuo_API.postman_collection.json`
Pre-configured requests:
- `credentials` - Login
- `send_walarm` - Send alert
- `alarm_on_off` - Enable/disable alarms
- `get_alarm_state` - Get current state
- `store_alarms` - Update configuration
---
## 11. Database Tables
### WellNuo Backend Tables
| Table | Purpose |
|-------|---------|
| `users` | User accounts |
| `beneficiaries` | People being monitored |
| `user_access` | Who has access to whom (roles) |
| `beneficiary_deployments` | Links beneficiary to deployment_id |
| `notification_settings` | User notification preferences |
| `push_tokens` | Device push tokens |
| `notification_history` | Log of sent notifications |
| `mqtt_alerts` | Raw MQTT messages received |
### Legacy Tables (eluxnetworks)
| Table | Purpose |
|-------|---------|
| `deployments` | Deployment configurations |
| `deployment_details` | Deployment metadata |
| `devices` | IoT devices with alert_details |
---
## 12. Known Issues
### Issue 1: Users without push tokens excluded
**Location**: `backend/src/services/mqtt.js:201`
```sql
-- Current query excludes users without push tokens entirely
WHERE bd.legacy_deployment_id = $1
AND pt.token IS NOT NULL -- ❌ Problem: users without tokens don't get other channels
```
**Fix needed**: Remove this filter, send via other channels even if no push token.
### Issue 2: Email not connected to alert flow
Email service exists (`backend/src/services/email.js`) but is not called from MQTT alert processing.
### Issue 3: SMS and Phone not implemented
Need Twilio integration for SMS and Phone calls in WellNuo backend.
---
## 13. Implementation TODO
### Phase 1: Fix current MQTT system
- [ ] Remove push token filter from user query
- [ ] Connect Email service to MQTT alert flow
- [ ] Create proper alert email template
- [ ] Test Push notifications end-to-end
### Phase 2: Add missing channels to WellNuo backend
- [ ] Integrate Twilio for SMS
- [ ] Integrate Twilio Voice (or LiveKit) for calls
- [ ] Add In-App UI notifications (WebSocket/polling)
### Phase 3: Per-beneficiary settings
- [ ] Create `user_beneficiary_notification_prefs` table
- [ ] Auto-create settings when user gets access
- [ ] Update notification service to check per-beneficiary settings
- [ ] Add settings UI in app
### Phase 4: Advanced features
- [ ] Quiet hours per beneficiary
- [ ] Escalation logic (if no response → next channel)
- [ ] Daily/weekly digest emails
---
## 14. Schema Diagram
Interactive diagram:
**https://diagrams.love/canvas?schema=cmkwvuljj0005llchm69ln8no**
---
## 15. Credentials Reference
### MQTT Broker
- **Host**: `mqtt.eluxnetworks.net`
- **Port**: `1883`
- **Username**: `anandk`
- **Password**: `anandk_8`
### eluxnetworks API
- **URL**: `https://eluxnetworks.net/function/well-api/api`
- **Username**: `robster`
- **Password**: `rob2`
### WellNuo Database
- **Host**: `eluxnetworks.net`
- **Port**: `5432`
- **Database**: `wellnuo_app`
- **User**: `sergei`
- **Password**: `W31153Rg31`
---
## References
- MQTT Service: `backend/src/services/mqtt.js`
- Notification Service: `backend/src/services/notifications.js`
- Email Service: `backend/src/services/email.js`
- Postman Collection: `api/Wellnuo_API.postman_collection.json`
- Legacy alarms UI: https://eluxnetworks.net/shared/alarms.html