IoT Agents API - arilonUK/iotagentmesh GitHub Wiki

IoT Agents API

The IoT Agents API provides comprehensive management of IoT device agents within the IoT Agent Mesh platform. This includes device registration, configuration management, status monitoring, and lifecycle operations.

Overview

IoT Agents represent physical or virtual devices that collect, process, and transmit data. Each agent has:

  • Unique identification and authentication credentials
  • Configurable data collection parameters
  • Real-time status and health monitoring
  • Flexible metadata and tagging system
  • Integration with telemetry and alert systems

Base Endpoint

/rest/v1/agents

Authentication

All endpoints require JWT authentication with appropriate organization access permissions.

Required Headers:

Authorization: Bearer YOUR_JWT_TOKEN
apikey: YOUR_SUPABASE_ANON_KEY
Content-Type: application/json

Endpoints

List IoT Agents

Get all IoT agents within the authenticated user's organization.

GET /rest/v1/agents

Query Parameters

Parameter Type Required Description
select string No Columns to return (default: *)
order string No Sort order (e.g., created_at.desc, name.asc)
limit integer No Number of results (default: 20, max: 1000)
offset integer No Number of results to skip
status string No Filter by status (online, offline, error)
type string No Filter by agent type
location string No Filter by location

Rate limits are per authenticated user per organization.

# IoT Agents API

The IoT Agents API provides comprehensive management of IoT device agents within the IoT Agent Mesh platform. This includes device registration, configuration management, status monitoring, and lifecycle operations.

Overview

IoT Agents represent physical or virtual devices that collect, process, and transmit data. Each agent has:

  • Unique identification and authentication credentials
  • Configurable data collection parameters
  • Real-time status and health monitoring
  • Flexible metadata and tagging system
  • Integration with telemetry and alert systems

Base Endpoint

/rest/v1/agents

Authentication

All endpoints require JWT authentication with appropriate organization access permissions.

Required Headers:

Authorization: Bearer YOUR_JWT_TOKEN
apikey: YOUR_SUPABASE_ANON_KEY
Content-Type: application/json

Endpoints

List IoT Agents

Get all IoT agents within the authenticated user's organization.

GET /rest/v1/agents

Query Parameters

Parameter Type Required Description
select string No Columns to return (default: *)
order string No Sort order (e.g., created_at.desc, name.asc)
limit integer No Number of results (default: 20, max: 1000)
offset integer No Number of results to skip
status string No Filter by status (online, offline, error)
type string No Filter by agent type
location string No Filter by location

Advanced Filtering

# Filter by status
GET /rest/v1/agents?status=eq.online

# Filter by type and location
GET /rest/v1/agents?type=eq.sensor&configuration->>location=eq.warehouse-a

# Search by name (case-insensitive)
GET /rest/v1/agents?name=ilike.*temperature*

# Filter by last seen (agents active in last hour)
GET /rest/v1/agents?last_seen=gte.2024-07-23T15:00:00Z

Response

{
  "data": [
    {
      "id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "organization_id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Temperature Sensor 01",
      "description": "Main warehouse temperature monitoring sensor",
      "type": "sensor",
      "status": "online",
      "configuration": {
        "sensor_type": "temperature",
        "sampling_rate": 60000,
        "location": "warehouse-a",
        "zone": "loading-dock",
        "calibration": {
          "offset": 0.5,
          "scale": 1.0
        },
        "thresholds": {
          "min_temp": -10,
          "max_temp": 40,
          "alert_threshold": 35
        }
      },
      "metadata": {
        "hardware_version": "v2.1",
        "firmware_version": "1.4.2",
        "manufacturer": "SensorTech Inc",
        "model": "ST-TEMP-PRO",
        "serial_number": "ST2024070001"
      },
      "tags": ["warehouse", "temperature", "critical"],
      "last_seen": "2024-07-23T16:45:00Z",
      "last_telemetry": "2024-07-23T16:45:00Z",
      "health_score": 98.5,
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-07-23T16:45:00Z"
    },
    {
      "id": "agent_02H8K2M3N4P5Q6R7S8T9U0V1W3",
      "organization_id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Gateway Hub Alpha",
      "description": "Primary IoT gateway for warehouse network",
      "type": "gateway",
      "status": "online",
      "configuration": {
        "network": {
          "protocol": "LoRaWAN",
          "frequency": "868MHz",
          "spreading_factor": 7
        },
        "connected_devices": 25,
        "max_devices": 100,
        "location": "warehouse-a"
      },
      "metadata": {
        "hardware_version": "v3.0",
        "firmware_version": "2.1.0",
        "manufacturer": "GatewayTech",
        "model": "GT-HUB-1000"
      },
      "tags": ["gateway", "lorawan", "primary"],
      "last_seen": "2024-07-23T16:46:00Z",
      "last_telemetry": "2024-07-23T16:46:00Z",
      "health_score": 95.2,
      "created_at": "2024-01-20T14:15:00Z",
      "updated_at": "2024-07-23T16:46:00Z"
    }
  ],
  "count": 245,
  "status": 200,
  "statusText": "OK"
}

Code Examples

JavaScript/TypeScript:

// Get all agents
const { data: agents, error } = await supabase
  .from('agents')
  .select('*')
  .order('last_seen', { ascending: false })

// Filter by status and type
const { data: onlineSensors } = await supabase
  .from('agents')
  .select('*')
  .eq('status', 'online')
  .eq('type', 'sensor')

// Search by name
const { data: temperatureSensors } = await supabase
  .from('agents')
  .select('*')
  .ilike('name', '%temperature%')

Python:

# Get all agents with pagination
response = supabase.table('agents')\
    .select('*')\
    .order('last_seen', desc=True)\
    .limit(50)\
    .execute()

agents = response.data

cURL:

curl -X GET \
  "https://your-project-id.supabase.co/rest/v1/agents?status=eq.online&order=last_seen.desc" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "apikey: YOUR_SUPABASE_ANON_KEY"

Get IoT Agent

Retrieve detailed information about a specific IoT agent.

GET /rest/v1/agents?id=eq.{agent_id}

Path Parameters

Parameter Type Required Description
agent_id string Yes Unique agent identifier

Response

{
  "data": [
    {
      "id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "organization_id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Temperature Sensor 01",
      "description": "Main warehouse temperature monitoring sensor",
      "type": "sensor",
      "status": "online",
      "configuration": {
        "sensor_type": "temperature",
        "sampling_rate": 60000,
        "location": "warehouse-a",
        "zone": "loading-dock",
        "calibration": {
          "offset": 0.5,
          "scale": 1.0
        },
        "thresholds": {
          "min_temp": -10,
          "max_temp": 40,
          "alert_threshold": 35
        },
        "communication": {
          "protocol": "MQTT",
          "topic_prefix": "sensors/temperature",
          "qos": 1,
          "retain": false
        }
      },
      "metadata": {
        "hardware_version": "v2.1",
        "firmware_version": "1.4.2",
        "manufacturer": "SensorTech Inc",
        "model": "ST-TEMP-PRO",
        "serial_number": "ST2024070001",
        "installation_date": "2024-01-15",
        "warranty_expires": "2026-01-15"
      },
      "tags": ["warehouse", "temperature", "critical"],
      "credentials": {
        "api_key": "sk_agent_01H8K2M3N4P5Q6R7S8T9U0V1W2_abc123",
        "mqtt_username": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
        "created_at": "2024-01-15T10:30:00Z",
        "last_rotated": "2024-06-15T10:30:00Z"
      },
      "statistics": {
        "total_telemetry_points": 125000,
        "uptime_percentage": 99.2,
        "avg_response_time_ms": 45,
        "last_24h_data_points": 1440
      },
      "last_seen": "2024-07-23T16:45:00Z",
      "last_telemetry": "2024-07-23T16:45:00Z",
      "health_score": 98.5,
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-07-23T16:45:00Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

const { data: agent, error } = await supabase
  .from('agents')
  .select('*')
  .eq('id', agentId)
  .single()

if (error) throw error
console.log('Agent details:', agent)

Register IoT Agent

Register a new IoT agent with the system.

POST /rest/v1/agents

Request Body

{
  "name": "Humidity Sensor 05",
  "description": "Warehouse humidity monitoring sensor",
  "type": "sensor",
  "configuration": {
    "sensor_type": "humidity",
    "sampling_rate": 300000,
    "location": "warehouse-b",
    "zone": "storage-area",
    "calibration": {
      "offset": 0.0,
      "scale": 1.0
    },
    "thresholds": {
      "min_humidity": 30,
      "max_humidity": 70,
      "alert_threshold": 65
    },
    "communication": {
      "protocol": "HTTP",
      "endpoint": "/api/v1/telemetry",
      "method": "POST",
      "headers": {
        "Content-Type": "application/json"
      }
    }
  },
  "metadata": {
    "hardware_version": "v1.8",
    "firmware_version": "1.2.1",
    "manufacturer": "SensorTech Inc",
    "model": "ST-HUM-BASIC",
    "serial_number": "ST2024070025",
    "installation_date": "2024-07-23"
  },
  "tags": ["warehouse", "humidity", "monitoring"]
}

Request Schema

Field Type Required Description
name string Yes Agent display name (2-100 chars)
description string No Agent description (max 500 chars)
type string Yes Agent type (sensor, gateway, controller, actuator)
configuration object Yes Agent-specific configuration
metadata object No Hardware and deployment metadata
tags array No Array of string tags for categorization

Response

{
  "data": [
    {
      "id": "agent_03H8K2M3N4P5Q6R7S8T9U0V1W4",
      "organization_id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Humidity Sensor 05",
      "description": "Warehouse humidity monitoring sensor",
      "type": "sensor",
      "status": "offline",
      "configuration": {
        "sensor_type": "humidity",
        "sampling_rate": 300000,
        "location": "warehouse-b",
        "zone": "storage-area",
        "calibration": {
          "offset": 0.0,
          "scale": 1.0
        },
        "thresholds": {
          "min_humidity": 30,
          "max_humidity": 70,
          "alert_threshold": 65
        },
        "communication": {
          "protocol": "HTTP",
          "endpoint": "/api/v1/telemetry",
          "method": "POST",
          "headers": {
            "Content-Type": "application/json"
          }
        }
      },
      "metadata": {
        "hardware_version": "v1.8",
        "firmware_version": "1.2.1",
        "manufacturer": "SensorTech Inc",
        "model": "ST-HUM-BASIC",
        "serial_number": "ST2024070025",
        "installation_date": "2024-07-23"
      },
      "tags": ["warehouse", "humidity", "monitoring"],
      "credentials": {
        "api_key": "sk_agent_03H8K2M3N4P5Q6R7S8T9U0V1W4_xyz789",
        "agent_secret": "as_secret_03H8K2M3N4P5Q6R7S8T9U0V1W4_def456",
        "created_at": "2024-07-23T17:00:00Z"
      },
      "health_score": null,
      "last_seen": null,
      "last_telemetry": null,
      "created_at": "2024-07-23T17:00:00Z",
      "updated_at": "2024-07-23T17:00:00Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

const { data: agent, error } = await supabase
  .from('agents')
  .insert({
    name: 'Humidity Sensor 05',
    description: 'Warehouse humidity monitoring sensor',
    type: 'sensor',
    configuration: {
      sensor_type: 'humidity',
      sampling_rate: 300000,
      location: 'warehouse-b',
      thresholds: {
        min_humidity: 30,
        max_humidity: 70,
        alert_threshold: 65
      }
    },
    metadata: {
      manufacturer: 'SensorTech Inc',
      model: 'ST-HUM-BASIC',
      serial_number: 'ST2024070025'
    },
    tags: ['warehouse', 'humidity', 'monitoring']
  })
  .select()
  .single()

if (error) throw error
console.log('Registered agent:', agent)

Python:

agent_data = {
    "name": "Humidity Sensor 05",
    "description": "Warehouse humidity monitoring sensor",
    "type": "sensor",
    "configuration": {
        "sensor_type": "humidity",
        "sampling_rate": 300000,
        "location": "warehouse-b",
        "thresholds": {
            "min_humidity": 30,
            "max_humidity": 70,
            "alert_threshold": 65
        }
    },
    "metadata": {
        "manufacturer": "SensorTech Inc",
        "model": "ST-HUM-BASIC",
        "serial_number": "ST2024070025"
    },
    "tags": ["warehouse", "humidity", "monitoring"]
}

response = supabase.table('agents').insert(agent_data).execute()
agent = response.data[0]

Update IoT Agent

Update an existing IoT agent's configuration and metadata.

PATCH /rest/v1/agents?id=eq.{agent_id}

Request Body

{
  "name": "Temperature Sensor 01 - Updated",
  "description": "Main warehouse temperature monitoring sensor - Updated description",
  "configuration": {
    "sensor_type": "temperature",
    "sampling_rate": 30000,
    "location": "warehouse-a",
    "zone": "loading-dock",
    "calibration": {
      "offset": 0.8,
      "scale": 1.02
    },
    "thresholds": {
      "min_temp": -15,
      "max_temp": 45,
      "alert_threshold": 40
    }
  },
  "metadata": {
    "firmware_version": "1.5.0",
    "last_maintenance": "2024-07-20"
  },
  "tags": ["warehouse", "temperature", "critical", "upgraded"]
}

Response

{
  "data": [
    {
      "id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "name": "Temperature Sensor 01 - Updated",
      "description": "Main warehouse temperature monitoring sensor - Updated description",
      "configuration": {
        "sensor_type": "temperature",
        "sampling_rate": 30000,
        "location": "warehouse-a",
        "zone": "loading-dock",
        "calibration": {
          "offset": 0.8,
          "scale": 1.02
        },
        "thresholds": {
          "min_temp": -15,
          "max_temp": 45,
          "alert_threshold": 40
        }
      },
      "metadata": {
        "hardware_version": "v2.1",
        "firmware_version": "1.5.0",
        "manufacturer": "SensorTech Inc",
        "model": "ST-TEMP-PRO",
        "serial_number": "ST2024070001",
        "installation_date": "2024-01-15",
        "last_maintenance": "2024-07-20"
      },
      "tags": ["warehouse", "temperature", "critical", "upgraded"],
      "updated_at": "2024-07-23T17:15:00Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

const { data: agent, error } = await supabase
  .from('agents')
  .update({
    configuration: {
      ...existingConfig,
      sampling_rate: 30000,
      thresholds: {
        min_temp: -15,
        max_temp: 45,
        alert_threshold: 40
      }
    },
    tags: ['warehouse', 'temperature', 'critical', 'upgraded']
  })
  .eq('id', agentId)
  .select()
  .single()

if (error) throw error
console.log('Updated agent:', agent)

Delete IoT Agent

Remove an IoT agent from the system. This will also delete all associated telemetry data.

DELETE /rest/v1/agents?id=eq.{agent_id}

Response

{
  "data": [],
  "status": 204,
  "statusText": "No Content"
}

⚠️ Warning

Deleting an agent will permanently remove:

  • All telemetry data collected by the agent
  • All alerts associated with the agent
  • All configuration and metadata
  • Agent credentials and authentication

Code Examples

JavaScript/TypeScript:

const { error } = await supabase
  .from('agents')
  .delete()
  .eq('id', agentId)

if (error) throw error
console.log('Agent deleted successfully')

Agent Status Management

Get Agent Status

Retrieve detailed status information for an agent.

GET /functions/v1/agent-status?agent_id={agent_id}

Response

{
  "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
  "status": "online",
  "last_seen": "2024-07-23T16:45:00Z",
  "last_telemetry": "2024-07-23T16:45:00Z",
  "health_score": 98.5,
  "uptime": {
    "percentage": 99.2,
    "last_24h": 23.8,
    "last_7d": 167.5,
    "last_30d": 714.2
  },
  "connectivity": {
    "signal_strength": -65,
    "network_type": "WiFi",
    "ip_address": "192.168.1.45",
    "last_ping": "2024-07-23T16:44:30Z",
    "response_time_ms": 45
  },
  "performance": {
    "cpu_usage": 12.5,
    "memory_usage": 34.2,
    "battery_level": 87,
    "temperature": 42.3
  },
  "errors": {
    "last_24h": 0,
    "last_7d": 2,
    "last_error": {
      "timestamp": "2024-07-21T10:15:00Z",
      "code": "SENSOR_CALIBRATION_WARNING",
      "message": "Sensor reading outside expected range"
    }
  }
}

Update Agent Status

Manually update an agent's status (typically used by the agent itself).

POST /functions/v1/agent-heartbeat

Request Body

{
  "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
  "status": "online",
  "performance": {
    "cpu_usage": 15.2,
    "memory_usage": 38.7,
    "battery_level": 85,
    "temperature": 43.1
  },
  "connectivity": {
    "signal_strength": -62,
    "response_time_ms": 42
  }
}

Bulk Operations

Bulk Agent Registration

Register multiple agents in a single request.

POST /functions/v1/agents-bulk-register

Request Body

{
  "agents": [
    {
      "name": "Sensor Array 01",
      "type": "sensor",
      "configuration": { "sensor_type": "temperature", "location": "zone-a" },
      "tags": ["temperature", "zone-a"]
    },
    {
      "name": "Sensor Array 02",
      "type": "sensor", 
      "configuration": { "sensor_type": "humidity", "location": "zone-a" },
      "tags": ["humidity", "zone-a"]
    }
  ]
}

Bulk Configuration Update

Update configuration for multiple agents matching criteria.

POST /functions/v1/agents-bulk-update

Request Body

{
  "filter": {
    "type": "sensor",
    "tags": ["warehouse"]
  },
  "updates": {
    "configuration": {
      "sampling_rate": 60000
    },
    "tags": ["warehouse", "updated"]
  }
}

Error Responses

Common Error Codes

HTTP Code Error Code Description
400 VALIDATION_ERROR Invalid request parameters or configuration
401 UNAUTHORIZED Missing or invalid JWT token
403 FORBIDDEN Insufficient permissions for agent operation
404 NOT_FOUND Agent not found
409 CONFLICT Agent name already exists in organization
422 UNPROCESSABLE_ENTITY Invalid agent configuration
429 RATE_LIMIT_EXCEEDED Too many requests

Example Error Response

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid agent configuration",
    "details": {
      "field": "configuration.sampling_rate",
      "value": -1000,
      "reason": "Sampling rate must be a positive integer"
    }
  },
  "status": 400
}

Best Practices

Agent Configuration

  1. Naming Conventions: Use descriptive names that include location and function
  2. Configuration Validation: Always validate configuration parameters
  3. Tag Management: Use consistent tagging schemes for easy filtering
  4. Metadata: Include hardware and deployment information for troubleshooting

Performance Optimization

  1. Batch Operations: Use bulk endpoints for multiple agent operations
  2. Status Monitoring: Implement regular health checks and status updates
  3. Configuration Caching: Cache agent configurations to reduce API calls
  4. Efficient Filtering: Use specific filters to reduce data transfer

Security Considerations

  1. Credential Management: Rotate agent credentials regularly
  2. Access Control: Verify agent ownership before operations
  3. Configuration Security: Avoid storing sensitive data in configuration
  4. Audit Logging: Track all agent configuration changes

Related Resources

  • [Telemetry API](API-Telemetry.md) - Collecting and managing agent telemetry data
  • [Alerts API](API-Alerts.md) - Setting up alerts for agent conditions
  • [Real-time API](API-Realtime.md) - Real-time agent status monitoring
  • [Organizations API](API-Organizations.md) - Organization-level agent management

Rate Limits

Operation Rate Limit Window
List Agents 200 requests 1 minute
Get Agent 500 requests 1 minute
Register Agent 20 requests 1 minute
Update Agent 100 requests 1 minute
Delete Agent 10 requests 1 minute
Agent Status 1000 requests 1 minute
Bulk Operations 5 requests 1 minute

Rate limits are per authenticated user per organization.

⚠️ **GitHub.com Fallback** ⚠️