Files
spore/docs/API.md
2025-09-24 21:12:22 +02:00

634 lines
17 KiB
Markdown

# SPORE API Documentation
The SPORE system provides a comprehensive RESTful API for monitoring and controlling the embedded device. All endpoints return JSON responses and support standard HTTP status codes.
## Quick Reference
### Task Management API
| Endpoint | Method | Description | Parameters | Response |
|----------|--------|-------------|------------|----------|
| `/api/tasks/status` | GET | Get comprehensive status of all tasks and system information | None | Task status overview with system metrics |
| `/api/tasks/control` | POST | Control individual task operations | `task`, `action` | Operation result with task details |
### System Status API
| Endpoint | Method | Description | Response |
|----------|--------|-------------|----------|
| `/api/node/status` | GET | System resource information | System metrics |
| `/api/node/endpoints` | GET | API endpoints and parameters | Detailed endpoint specifications |
| `/api/cluster/members` | GET | Cluster membership and node health information | Cluster topology and health status |
| `/api/node/update` | POST | Handle firmware updates via OTA | Update progress and status |
| `/api/node/restart` | POST | Trigger system restart | Restart confirmation |
### Monitoring API
| Endpoint | Method | Description | Response |
|----------|--------|-------------|----------|
| `/api/monitoring/resources` | GET | CPU, memory, filesystem, and uptime | System resource metrics |
### Network Management API
| Endpoint | Method | Description | Response |
|----------|--------|-------------|----------|
| `/api/network/status` | GET | WiFi and network status information | Network configuration and status |
| `/api/network/wifi/scan` | GET | Get available WiFi networks | List of discovered networks |
| `/api/network/wifi/scan` | POST | Trigger WiFi network scan | Scan initiation confirmation |
| `/api/network/wifi/config` | POST | Configure WiFi connection | Connection status and result |
### Hardware Services API
| Endpoint | Method | Description | Response |
|----------|--------|-------------|----------|
| `/api/neopixel/status` | GET | NeoPixel LED strip status | LED configuration and state |
| `/api/neopixel` | POST | NeoPixel pattern and color control | Control confirmation |
| `/api/neopixel/patterns` | GET | Available LED patterns | List of supported patterns |
| `/api/relay/status` | GET | Relay state and configuration | Relay pin and state |
| `/api/relay` | POST | Relay control (on/off/toggle) | Control result |
| `/api/neopattern/status` | GET | NeoPattern service status | Pattern configuration |
| `/api/neopattern` | POST | Advanced LED pattern control | Control confirmation |
| `/api/neopattern/patterns` | GET | Available pattern types | List of supported patterns |
## Detailed API Reference
### Task Management
#### GET /api/tasks/status
Returns comprehensive status information for all registered tasks, including system resource metrics and task execution details.
**Response Fields:**
| Field | Type | Description |
|-------|------|-------------|
| `summary.totalTasks` | integer | Total number of registered tasks |
| `summary.activeTasks` | integer | Number of currently enabled tasks |
| `tasks[].name` | string | Unique task identifier |
| `tasks[].interval` | integer | Execution frequency in milliseconds |
| `tasks[].enabled` | boolean | Whether task is currently enabled |
| `tasks[].running` | boolean | Whether task is actively executing |
| `tasks[].autoStart` | boolean | Whether task starts automatically |
| `system.freeHeap` | integer | Available RAM in bytes |
| `system.uptime` | integer | System uptime in milliseconds |
**Example Response:**
```json
{
"summary": {
"totalTasks": 6,
"activeTasks": 5
},
"tasks": [
{
"name": "discovery_send",
"interval": 1000,
"enabled": true,
"running": true,
"autoStart": true
}
],
"system": {
"freeHeap": 48748,
"uptime": 12345
}
}
```
#### POST /api/tasks/control
Controls the execution state of individual tasks. Supports enabling, disabling, starting, stopping, and getting detailed status for specific tasks.
**Parameters:**
- `task` (required): Name of the task to control
- `action` (required): Action to perform
**Available Actions:**
| Action | Description | Use Case |
|--------|-------------|----------|
| `enable` | Enable a disabled task | Resume background operations |
| `disable` | Disable a running task | Pause resource-intensive tasks |
| `start` | Start a stopped task | Begin task execution |
| `stop` | Stop a running task | Halt task execution |
| `status` | Get detailed status for a specific task | Monitor individual task health |
**Example Response:**
```json
{
"success": true,
"message": "Task enabled",
"task": "heartbeat",
"action": "enable"
}
```
**Task Status Response:**
```json
{
"success": true,
"message": "Task status retrieved",
"task": "discovery_send",
"action": "status",
"taskDetails": {
"name": "discovery_send",
"enabled": true,
"running": true,
"interval": 1000,
"system": {
"freeHeap": 48748,
"uptime": 12345
}
}
}
```
### System Status
#### GET /api/node/status
Returns comprehensive system resource information including memory usage and chip details. For a list of available API endpoints, use `/api/node/endpoints`.
**Response Fields:**
- `freeHeap`: Available RAM in bytes
- `chipId`: ESP8266 chip ID
- `sdkVersion`: ESP8266 SDK version
- `cpuFreqMHz`: CPU frequency in MHz
- `flashChipSize`: Flash chip size in bytes
- `labels`: Node labels and metadata (if available)
- `api`: Array of registered API endpoints
**Example Response:**
```json
{
"freeHeap": 48748,
"chipId": 12345678,
"sdkVersion": "3.1.2",
"cpuFreqMHz": 80,
"flashChipSize": 1048576,
"labels": {
"location": "kitchen",
"type": "sensor"
}
}
```
#### GET /api/node/endpoints
Returns detailed information about all available API endpoints, including their parameters, types, and validation rules. Methods are returned as strings (e.g., "GET", "POST").
**Response Fields:**
- `endpoints[]`: Array of endpoint capability objects
- `uri`: Endpoint URI path
- `method`: HTTP method (GET, POST, etc.)
- `params[]`: Parameter specifications (if applicable)
- `name`: Parameter name
- `location`: Parameter location (body, query, etc.)
- `required`: Whether parameter is required
- `type`: Parameter data type
- `values[]`: Allowed values (for enums)
- `default`: Default value
**Example Response:**
```json
{
"endpoints": [
{
"uri": "/api/tasks/control",
"method": "POST",
"params": [
{
"name": "task",
"location": "body",
"required": true,
"type": "string"
},
{
"name": "action",
"location": "body",
"required": true,
"type": "string",
"values": ["enable", "disable", "start", "stop", "status"]
}
]
}
]
}
```
#### GET /api/cluster/members
Returns information about all nodes in the cluster, including their health status, resources, and API endpoints.
**Response Fields:**
- `members[]`: Array of cluster node information
- `hostname`: Node hostname
- `ip`: Node IP address
- `lastSeen`: Timestamp of last communication
- `latency`: Network latency in milliseconds
- `status`: Node health status (ACTIVE, INACTIVE, DEAD)
- `resources`: System resource information
- `api`: Available API endpoints
### System Management
#### POST /api/node/update
Initiates an over-the-air firmware update. The firmware file should be uploaded as multipart/form-data.
**Parameters:**
- `firmware`: Firmware binary file (.bin)
#### POST /api/node/restart
Triggers a system restart. The response will be sent before the restart occurs.
### Monitoring
#### GET /api/monitoring/resources
Returns real-time system resource metrics.
Response Fields:
- `cpu.current_usage`: Current CPU usage percent
- `cpu.average_usage`: Average CPU usage percent
- `cpu.max_usage`: Max observed CPU usage
- `cpu.min_usage`: Min observed CPU usage
- `cpu.measurement_count`: Number of measurements
- `cpu.is_measuring`: Whether measurement is active
- `memory.free_heap`: Free heap bytes
- `memory.total_heap`: Total heap bytes (approximate)
- `memory.heap_fragmentation`: Fragmentation percent (0 on ESP8266)
- `filesystem.total_bytes`: LittleFS total bytes
- `filesystem.used_bytes`: Used bytes
- `filesystem.free_bytes`: Free bytes
- `filesystem.usage_percent`: Usage percent
- `system.uptime_ms`: Uptime in milliseconds
Example Response:
```json
{
"cpu": {
"current_usage": 3.5,
"average_usage": 2.1,
"max_usage": 15.2,
"min_usage": 0.0,
"measurement_count": 120,
"is_measuring": true
},
"memory": {
"free_heap": 48748,
"total_heap": 81920,
"heap_fragmentation": 0
},
"filesystem": {
"total_bytes": 65536,
"used_bytes": 10240,
"free_bytes": 55296,
"usage_percent": 15.6
},
"system": {
"uptime_ms": 123456
}
}
```
### Network Management
#### GET /api/network/status
Returns comprehensive WiFi and network status information.
**Response Fields:**
- `wifi.connected`: Whether WiFi is connected
- `wifi.mode`: WiFi mode (STA or AP)
- `wifi.ssid`: Connected network SSID
- `wifi.ip`: Local IP address
- `wifi.mac`: MAC address
- `wifi.hostname`: Device hostname
- `wifi.rssi`: Signal strength
- `wifi.ap_ip`: Access point IP (if in AP mode)
- `wifi.ap_mac`: Access point MAC (if in AP mode)
- `wifi.stations_connected`: Number of connected stations (if in AP mode)
**Example Response:**
```json
{
"wifi": {
"connected": true,
"mode": "STA",
"ssid": "MyNetwork",
"ip": "192.168.1.100",
"mac": "AA:BB:CC:DD:EE:FF",
"hostname": "spore-node-1",
"rssi": -45
}
}
```
#### GET /api/network/wifi/scan
Returns a list of available WiFi networks discovered during the last scan.
**Response Fields:**
- `access_points[]`: Array of discovered networks
- `ssid`: Network name
- `rssi`: Signal strength
- `channel`: WiFi channel
- `encryption_type`: Security type
- `hidden`: Whether network is hidden
- `bssid`: Network MAC address
**Example Response:**
```json
{
"access_points": [
{
"ssid": "MyNetwork",
"rssi": -45,
"channel": 6,
"encryption_type": 4,
"hidden": false,
"bssid": "AA:BB:CC:DD:EE:FF"
}
]
}
```
#### POST /api/network/wifi/scan
Initiates a new WiFi network scan.
**Response:**
```json
{
"status": "scanning",
"message": "WiFi scan started"
}
```
#### POST /api/network/wifi/config
Configures WiFi connection with new credentials.
**Parameters:**
- `ssid` (required): Network SSID
- `password` (required): Network password
- `connect_timeout_ms` (optional): Connection timeout in milliseconds (default: 10000)
- `retry_delay_ms` (optional): Retry delay in milliseconds (default: 500)
**Response:**
```json
{
"status": "success",
"message": "WiFi configuration updated",
"connected": true,
"ip": "192.168.1.100"
}
```
### Hardware Services
#### NeoPixel LED Control
##### GET /api/neopixel/status
Returns current NeoPixel LED strip status and configuration.
**Response Fields:**
- `pin`: GPIO pin number
- `count`: Number of LEDs in strip
- `interval_ms`: Update interval in milliseconds
- `brightness`: Current brightness (0-255)
- `pattern`: Current pattern name
**Example Response:**
```json
{
"pin": 2,
"count": 16,
"interval_ms": 100,
"brightness": 50,
"pattern": "rainbow"
}
```
##### GET /api/neopixel/patterns
Returns list of available LED patterns.
**Response:**
```json
["off", "color_wipe", "rainbow", "rainbow_cycle", "theater_chase", "theater_chase_rainbow"]
```
##### POST /api/neopixel
Controls NeoPixel LED strip patterns and colors.
**Parameters:**
- `pattern` (optional): Pattern name
- `interval_ms` (optional): Update interval in milliseconds
- `brightness` (optional): Brightness level (0-255)
- `color` (optional): Primary color (hex value)
- `r`, `g`, `b` (optional): RGB color values
- `color2` (optional): Secondary color (hex value)
- `r2`, `g2`, `b2` (optional): Secondary RGB values
**Example Request:**
```bash
curl -X POST http://192.168.1.100/api/neopixel \
-d "pattern=rainbow&brightness=100&interval_ms=50"
```
#### Relay Control
##### GET /api/relay/status
Returns current relay status and configuration.
**Response Fields:**
- `pin`: GPIO pin number
- `state`: Current state (on/off)
- `uptime`: System uptime in milliseconds
**Example Response:**
```json
{
"pin": 5,
"state": "off",
"uptime": 12345
}
```
##### POST /api/relay
Controls relay state.
**Parameters:**
- `state` (required): Desired state (on, off, toggle)
**Example Request:**
```bash
curl -X POST http://192.168.1.100/api/relay \
-d "state=on"
```
#### NeoPattern Service
##### GET /api/neopattern/status
Returns NeoPattern service status and configuration.
**Response Fields:**
- `pin`: GPIO pin number
- `count`: Number of LEDs
- `interval_ms`: Update interval
- `brightness`: Current brightness
- `pattern`: Current pattern name
- `total_steps`: Pattern step count
- `color1`: Primary color
- `color2`: Secondary color
##### GET /api/neopattern/patterns
Returns available pattern types.
**Response:**
```json
["off", "rainbow_cycle", "theater_chase", "color_wipe", "scanner", "fade", "fire"]
```
##### POST /api/neopattern
Controls advanced LED patterns.
**Parameters:**
- `pattern` (optional): Pattern name
- `interval_ms` (optional): Update interval
- `brightness` (optional): Brightness level
- `color`, `color2` (optional): Color values
- `r`, `g`, `b`, `r2`, `g2`, `b2` (optional): RGB values
- `total_steps` (optional): Pattern step count
- `direction` (optional): Pattern direction (forward/reverse)
## HTTP Status Codes
| Code | Description | Use Case |
|------|-------------|----------|
| 200 | Success | Operation completed successfully |
| 400 | Bad Request | Invalid parameters or action |
| 404 | Not Found | Task or endpoint not found |
| 500 | Internal Server Error | System error occurred |
## OpenAPI Specification
A complete OpenAPI 3.0 specification is available in the [`api/`](../api/) folder. This specification can be used to:
- Generate client libraries in multiple programming languages
- Create interactive API documentation
- Validate API requests and responses
- Generate mock servers for testing
- Integrate with API management platforms
See [`api/README.md`](../api/README.md) for detailed usage instructions.
## Usage Examples
### Basic Task Status Check
```bash
curl -s http://10.0.1.60/api/tasks/status | jq '.'
```
### Task Control
```bash
# Disable a task
curl -X POST http://10.0.1.60/api/tasks/control \
-d "task=heartbeat&action=disable"
# Get detailed status
curl -X POST http://10.0.1.60/api/tasks/control \
-d "task=discovery_send&action=status"
```
### System Monitoring
```bash
# Check system resources
curl -s http://10.0.1.60/api/node/status | jq '.freeHeap'
# Monitor cluster health
curl -s http://10.0.1.60/api/cluster/members | jq '.members[].status'
```
## Integration Examples
### Python Client
```python
import requests
# Get task status
response = requests.get('http://10.0.1.60/api/tasks/status')
tasks = response.json()
# Check active tasks
active_count = tasks['summary']['activeTasks']
print(f"Active tasks: {active_count}")
# Control a task
control_data = {'task': 'heartbeat', 'action': 'disable'}
response = requests.post('http://10.0.1.60/api/tasks/control', data=control_data)
```
### JavaScript Client
```javascript
// Get task status
fetch('http://10.0.1.60/api/tasks/status')
.then(response => response.json())
.then(data => {
console.log(`Total tasks: ${data.summary.totalTasks}`);
console.log(`Active tasks: ${data.summary.activeTasks}`);
});
// Control a task
fetch('http://10.0.1.60/api/tasks/control', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'task=heartbeat&action=disable'
});
```
## Task Management Examples
### Monitoring Task Health
```bash
# Check overall task status
curl -s http://10.0.1.60/api/tasks/status | jq '.'
# Monitor specific task
curl -s -X POST http://10.0.1.60/api/tasks/control \
-d "task=heartbeat&action=status" | jq '.'
# Watch for low memory conditions
watch -n 5 'curl -s http://10.0.1.60/api/tasks/status | jq ".system.freeHeap"'
```
### Task Control Workflows
```bash
# Temporarily disable discovery to reduce network traffic
curl -X POST http://10.0.1.60/api/tasks/control \
-d "task=discovery_send&action=disable"
# Check if it's disabled
curl -s -X POST http://10.0.1.60/api/tasks/control \
-d "task=discovery_send&action=status" | jq '.taskDetails.enabled'
# Re-enable when needed
curl -X POST http://10.0.1.60/api/tasks/control \
-d "task=discovery_send&action=enable"
```
### Cluster Health Monitoring
```bash
# Monitor all nodes in cluster
for ip in 10.0.1.60 10.0.1.61 10.0.1.62; do
echo "=== Node $ip ==="
curl -s "http://$ip/api/tasks/status" | jq '.summary'
done
```