### Clone and Run ThingsPanel via Docker Compose Source: https://github.com/thingspanel/thingspanel-backend-community/blob/main/README.md This snippet shows how to quickly install and run ThingsPanel using Docker Compose. It involves cloning the repository, navigating into the directory, and starting the services. The provided credentials are for initial login after deployment. ```bash git clone https://github.com/ThingsPanel/thingspanel-docker.git cd thingspanel-docker docker-compose -f docker-compose.yml up ``` -------------------------------- ### Initialize and Start ThingsPanel Application (Go) Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt This Go code snippet demonstrates how to initialize and start the ThingsPanel application. It parses command-line flags for configuration path, sets up various application options including configuration files, RSA decryption, logging, database, Redis, storage, flow services, monitoring, MQTT, downlink, gRPC, HTTP, and cron services. The application is then started and waits for termination signals. ```go package main import ( "flag" "fmt" "os" "project/internal/app" "github.com/sirupsen/logrus" ) func main() { configPath := flag.String("config", "", "Path to configuration file") flag.Parse() var configOption app.Option if *configPath != "" { configOption = app.WithConfigFile(*configPath) } else { configOption = app.WithProductionConfig() } application, err := app.NewApplication( configOption, app.WithRsaDecrypt("./configs/rsa_key/private_key.pem"), app.WithLogger(), app.WithDatabase(), app.WithRedis(), app.WithStorageService(), app.WithFlowService(), app.WithHeartbeatMonitor(), app.WithDiagnostics(), app.WithMQTTService(), app.WithDownlinkService(), app.WithGRPCService(), app.WithHTTPService(), app.WithCronService(), ) if err != nil { fmt.Fprintf(os.Stderr, "Application initialization failed: %v\n", err) os.Exit(1) } if err := application.Start(); err != nil { logrus.Fatalf("Failed to start services: %v", err) } application.Wait() defer application.Shutdown() } // Run with: go run . -config ./configs/conf-dev.yml ``` -------------------------------- ### MQTT Device Communication - Go Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Provides Go code examples for implementing MQTT-based device communication within ThingsPanel. It covers publishing telemetry data for individual devices and gateway sub-devices, subscribing to commands from the platform, processing received commands, and sending command responses. This requires the paho.mqtt.golang library. ```go // Device telemetry publishing (device-side code example) package main import ( "encoding/json" "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) func publishTelemetry(client mqtt.Client, deviceNumber string) error { topic := "devices/telemetry" telemetryData := map[string]interface{}{ "device_number": deviceNumber, "temperature": 23.5, "humidity": 45.2, "timestamp": time.Now().Unix(), } payload, err := json.Marshal(telemetryData) if err != nil { return err } token := client.Publish(topic, 0, false, payload) token.Wait() return token.Error() } // Gateway device with sub-devices func publishGatewayTelemetry(client mqtt.Client, gatewayNumber string, subDeviceAddr string) error { topic := "gateway/telemetry/" + gatewayNumber + "/" + subDeviceAddr telemetryData := map[string]interface{}{ "sub_device_addr": subDeviceAddr, "voltage": 220.5, "current": 5.2, "power": 1146.6, "timestamp": time.Now().Unix(), } payload, err := json.Marshal(telemetryData) if err != nil { return err } token := client.Publish(topic, 0, false, payload) token.Wait() return token.Error() } // Receiving commands from platform func subscribeToCommands(client mqtt.Client, deviceNumber string) error { topic := "devices/command/" + deviceNumber + "/+" token := client.Subscribe(topic, 1, func(client mqtt.Client, msg mqtt.Message) { var command struct { Identify string `json:"identify"` Value json.RawMessage `json:"value"` MessageID string `json:"message_id"` } if err := json.Unmarshal(msg.Payload(), &command); err != nil { return } // Process command result := processCommand(command.Identify, command.Value) // Send response responseTopic := "devices/command/response/" + command.MessageID responsePayload, _ := json.Marshal(result) client.Publish(responseTopic, 1, false, responsePayload) }) token.Wait() return token.Error() } func processCommand(identify string, value json.RawMessage) map[string]interface{} { return map[string]interface{}{ "status": "success", "message": "Command executed", "timestamp": time.Now().Unix(), } } ``` -------------------------------- ### Device Management - Get Device Details Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Retrieves comprehensive device information including current status, configuration, and metadata. ```APIDOC ## GET /api/v1/device/detail/{id} ### Description Retrieves comprehensive device information including current status, configuration, and metadata. ### Method GET ### Endpoint /api/v1/device/detail/{id} #### Path Parameters - **id** (string) - Required - The ID of the device to retrieve details for. ### Request Example ```bash curl -X GET "http://localhost:9999/api/v1/device/detail/770e8400-e29b-41d4-a716-446655440002" \ -H "x-token: your-jwt-token" ``` ### Response #### Success Response (200) - **code** (integer) - The response status code. - **message** (string) - A message indicating the success of the operation. - **data** (object) - An object containing the device details. - **id** (string) - The device ID. - **name** (string) - The device name. - **device_number** (string) - The device number. - **voucher** (string) - Device credentials (e.g., username and password) in JSON format. - **protocol** (string) - The communication protocol used by the device. - **is_online** (integer) - Online status of the device (0 for offline, 1 for online). - **activate_flag** (string) - Activation status of the device. - **product_id** (string) - The ID of the product the device belongs to. - **tenant_id** (string) - The ID of the tenant the device belongs to. - **device_config** (object) - The device configuration details. - **id** (string) - The configuration ID. - **name** (string) - The configuration name. - **protocol_type** (string) - The protocol type of the configuration. - **voucher_type** (string) - The voucher type of the configuration. - **created_at** (string) - The timestamp when the device was created. #### Response Example ```json { "code": 200, "message": "success", "data": { "id": "770e8400-e29b-41d4-a716-446655440002", "name": "Temperature Sensor 01", "device_number": "DEV-TEMP-001", "voucher": "{\"username\":\"a1b2c3d4e5f6g7h8i9j0k1\",\"password\":\"m2n3o4p\"}", "protocol": "MQTT", "is_online": 1, "activate_flag": "active", "product_id": "550e8400-e29b-41d4-a716-446655440000", "tenant_id": "tenant-123", "device_config": { "id": "660e8400-e29b-41d4-a716-446655440001", "name": "Standard MQTT Config", "protocol_type": "MQTT", "voucher_type": "BASIC" }, "created_at": "2025-12-06T10:30:00Z" } } ``` ``` -------------------------------- ### Get IoT Device Details (Bash) Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Retrieves detailed information about a specific IoT device, including its ID, name, configuration, and connection status. An authentication token is necessary to access this endpoint. ```bash # GET /api/v1/device/detail/{id} curl -X GET "http://localhost:9999/api/v1/device/detail/770e8400-e29b-41d4-a716-446655440002" \ -H "x-token: your-jwt-token" # Response { "code": 200, "message": "success", "data": { "id": "770e8400-e29b-41d4-a716-446655440002", "name": "Temperature Sensor 01", "device_number": "DEV-TEMP-001", "voucher": "{\"username\":\"a1b2c3d4e5f6g7h8i9j0k1\",\"password\":\"m2n3o4p\"}", "protocol": "MQTT", "is_online": 1, "activate_flag": "active", "product_id": "550e8400-e29b-41d4-a716-446655440000", "tenant_id": "tenant-123", "device_config": { "id": "660e8400-e29b-41d4-a716-446655440001", "name": "Standard MQTT Config", "protocol_type": "MQTT", "voucher_type": "BASIC" }, "created_at": "2025-12-06T10:30:00Z" } } ``` -------------------------------- ### GET /api/v1/command/datas/set/logs Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Retrieves a paginated list of command execution logs for devices, including status and timestamps. Useful for auditing and troubleshooting. ```APIDOC ## GET /api/v1/command/datas/set/logs ### Description Retrieves paginated command execution history with status information. ### Method GET ### Endpoint /api/v1/command/datas/set/logs #### Query Parameters - **device_id** (string) - Required - The unique identifier of the device. - **page** (integer) - Optional - The page number for pagination (default is 1). - **page_size** (integer) - Optional - The number of items per page (default is 10). ### Request Example ```bash curl -X GET "http://localhost:9999/api/v1/command/datas/set/logs?device_id=770e8400-e29b-41d4-a716-446655440002&page=1&page_size=10" \ -H "x-token: your-jwt-token" ``` ### Response #### Success Response (200) - **total** (integer) - The total number of command logs available. - **list** (array) - An array of command log objects. - **id** (string) - The unique identifier of the command log entry. - **device_id** (string) - The identifier of the device. - **identify** (string) - The identifier of the command. - **description** (string) - A description of the command. - **data** (string) - The data payload of the command. - **status** (string) - The execution status (e.g., "success", "failed"). - **created_at** (string) - The timestamp when the command was created. - **response_at** (string) - The timestamp when the command received a response. #### Response Example ```json { "code": 200, "message": "success", "data": { "total": 45, "list": [ { "id": "cmd-001", "device_id": "770e8400-e29b-41d4-a716-446655440002", "identify": "set_temperature_threshold", "description": "Set temperature alert threshold", "data": "{\"threshold\": 25.0}", "status": "success", "created_at": "2025-12-06T12:30:00Z", "response_at": "2025-12-06T12:30:02Z" } ] } } ``` ``` -------------------------------- ### Get Command Execution History Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Retrieves a paginated list of command execution logs for a specific device. Requires device ID, page number, and page size. Returns total count and a list of command log entries. ```bash curl -X GET "http://localhost:9999/api/v1/command/datas/set/logs?device_id=770e8400-e29b-41d4-a716-446655440002&page=1&page_size=10" \ -H "x-token: your-jwt-token" ``` -------------------------------- ### Initialize Charts with ECharts Source: https://github.com/thingspanel/thingspanel-backend-community/blob/main/static/metrics-viewer_en.html Initializes charts using the ECharts library. It creates chart instances for API requests, latency, and errors, associating them with HTML elements in the DOM. This setup is crucial for rendering visualizations of the metrics data. ```javascript let charts = {}; // Initialize charts function initCharts() { charts.requests = echarts.init(document.getElementById('requestsChart')); charts.latency = echarts.init(document.getElementById('latencyChart')); charts.errors = echarts.init(document.getElementById('errorsChart')); } ``` -------------------------------- ### GET /api/v1/telemetry/datas/current/{id} Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Retrieves the latest telemetry data for a specific device. This endpoint is useful for getting the most recent sensor readings. ```APIDOC ## GET /api/v1/telemetry/datas/current/{id} ### Description Retrieves the latest telemetry data for a specific device. ### Method GET ### Endpoint /api/v1/telemetry/datas/current/{id} #### Path Parameters - **id** (string) - Required - The unique identifier of the device. #### Request Example ```bash curl -X GET "http://localhost:9999/api/v1/telemetry/datas/current/770e8400-e29b-41d4-a716-446655440002" \ -H "x-token: your-jwt-token" ``` ### Response #### Success Response (200) - **device_id** (string) - The identifier of the device. - **temperature** (number) - The current temperature reading. - **humidity** (number) - The current humidity reading. - **timestamp** (string) - The timestamp of the telemetry data in ISO 8601 format. #### Response Example ```json { "code": 200, "message": "success", "data": { "device_id": "770e8400-e29b-41d4-a716-446655440002", "temperature": 23.5, "humidity": 45.2, "timestamp": "2025-12-06T12:00:00Z" } } ``` ``` -------------------------------- ### Get Current Telemetry Data Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Retrieves the latest telemetry data for a specific device. Requires a device ID and an authorization token. ```bash curl -X GET "http://localhost:9999/api/v1/telemetry/datas/current/770e8400-e29b-41d4-a716-446655440002" \ -H "x-token: your-jwt-token" ``` -------------------------------- ### GET /api/v1/telemetry/datas/history Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Queries historical telemetry data for a device, with options for time range and data aggregation. Useful for trend analysis and reporting. ```APIDOC ## GET /api/v1/telemetry/datas/history ### Description Queries historical telemetry data with time range and aggregation options. ### Method GET ### Endpoint /api/v1/telemetry/datas/history #### Query Parameters - **device_id** (string) - Required - The unique identifier of the device. - **start_time** (integer) - Required - The start timestamp for the historical data (Unix epoch seconds). - **end_time** (integer) - Required - The end timestamp for the historical data (Unix epoch seconds). - **key** (string) - Optional - The specific telemetry key to retrieve (e.g., "temperature"). - **aggregate** (string) - Optional - The aggregation method to apply (e.g., "avg", "min", "max"). - **interval** (string) - Optional - The time interval for aggregation (e.g., "1h", "1d"). ### Request Example ```bash curl -X GET "http://localhost:9999/api/v1/telemetry/datas/history?device_id=770e8400-e29b-41d4-a716-446655440002&start_time=1733400000&end_time=1733486400&key=temperature&aggregate=avg&interval=1h" \ -H "x-token: your-jwt-token" ``` ### Response #### Success Response (200) - **device_id** (string) - The identifier of the device. - **key** (string) - The telemetry key for the data. - **values** (array) - An array of objects, each containing a timestamp and a value. - **timestamp** (string) - The timestamp of the data point. - **value** (number) - The aggregated or raw telemetry value. #### Response Example ```json { "code": 200, "message": "success", "data": { "device_id": "770e8400-e29b-41d4-a716-446655440002", "key": "temperature", "values": [ {"timestamp": "2025-12-06T00:00:00Z", "value": 22.1}, {"timestamp": "2025-12-06T01:00:00Z", "value": 22.3}, {"timestamp": "2025-12-06T02:00:00Z", "value": 22.0}, {"timestamp": "2025-12-06T03:00:00Z", "value": 21.8} ] } } ``` ``` -------------------------------- ### Get Historical Telemetry Data Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Queries historical telemetry data for a device within a specified time range, with options for aggregation and interval. Requires device ID, start/end times, data key, aggregation method, and interval. ```bash curl -X GET "http://localhost:9999/api/v1/telemetry/datas/history?device_id=770e8400-e29b-41d4-a716-446655440002&start_time=1733400000&end_time=1733486400&key=temperature&aggregate=avg&interval=1h" \ -H "x-token: your-jwt-token" ``` -------------------------------- ### Create Device Template - Go API Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Defines the structure for creating a device template, specifying its physical model and capabilities. The API endpoint is POST /api/v1/device/template. It accepts a JSON body with details like name, description, device type, model configuration (telemetry, attributes, commands), and returns a success response with the template ID and creation timestamp. ```go // POST /api/v1/device/template // Request body example { "name": "Environmental Sensor Template", "description": "Template for temperature and humidity sensors", "device_type": "sensor", "flag": "standard", "model_config": { "telemetry": [ {"key": "temperature", "name": "Temperature", "data_type": "float", "unit": "°C"}, {"key": "humidity", "name": "Humidity", "data_type": "float", "unit": "%"} ], "attributes": [ {"key": "location", "name": "Location", "data_type": "string"}, {"key": "firmware_version", "name": "Firmware Version", "data_type": "string"} ], "commands": [ {"key": "reset", "name": "Reset Device", "params": []}, {"key": "calibrate", "name": "Calibrate Sensor", "params": [{"key": "offset", "data_type": "float"}]} ] } } // Response example { "code": 200, "message": "success", "data": { "id": "template-001", "name": "Environmental Sensor Template", "created_at": "2025-12-06T14:00:00Z" } } ``` -------------------------------- ### Create IoT Device (Go) Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a new IoT device in the ThingsPanel system. It requires device details such as name, product ID, and protocol. The response includes generated credentials and initial device status. ```go // POST /api/v1/device // Request body example { "name": "Temperature Sensor 01", "product_id": "550e8400-e29b-41d4-a716-446655440000", "device_number": "DEV-TEMP-001", "device_config_id": "660e8400-e29b-41d4-a716-446655440001", "protocol": "MQTT", "access_way": "direct", "label": "Building A - Floor 1", "location": "{\"lat\": 40.7128, \"lng\": -74.0060}", "description": "Temperature monitoring sensor for HVAC control", "protocol_config": "{\"sampling_interval\": 60}", "remark1": "Calibration date: 2025-01-15" } // Response example { "code": 200, "message": "success", "data": { "id": "770e8400-e29b-41d4-a716-446655440002", "name": "Temperature Sensor 01", "device_number": "DEV-TEMP-001", "voucher": "{\"username\":\"a1b2c3d4e5f6g7h8i9j0k1\",\"password\":\"m2n3o4p\"}", "is_online": 0, "activate_flag": "active", "tenant_id": "tenant-123", "created_at": "2025-12-06T10:30:00Z" } } ``` -------------------------------- ### Publish Command to Device Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Publishes a command to a device via MQTT for remote control. Requires device ID, command identify, and command value. An optional sub-device address can be provided. ```go // POST /api/v1/command/datas/pub // Request body example { "device_id": "770e8400-e29b-41d4-a716-446655440002", "identify": "set_temperature_threshold", "value": "{\"threshold\": 25.0, \"action\": \"alert\"}", "sub_device_addr": "" } // Response example { "code": 200, "message": "success", "data": null } // MQTT message published to: devices/command/DEV-TEMP-001/{message_id} // Payload: {"identify": "set_temperature_threshold", "value": "{\"threshold\": 25.0, \"action\": \"alert\"}"} ``` -------------------------------- ### Create Scene Automation Rule Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a scene automation rule that triggers actions based on device conditions. Requires a name, description, trigger condition, and a list of actions (e.g., commands, notifications). ```go // POST /api/v1/scene_automations // Request body example { "name": "HVAC Control Automation", "description": "Automatically control HVAC based on temperature", "trigger_condition": { "type": "device", "device_id": "770e8400-e29b-41d4-a716-446655440002", "condition": "{\"key\": \"temperature\", \"operator\": \">\", \"value\": 28.0}" }, "actions": [ { "type": "command", "device_id": "hvac-device-001", "identify": "set_mode", "value": "{\"mode\": \"cooling\", \"target_temp\": 24.0}" }, { "type": "notification", "notification_type": "email", "message": "HVAC cooling activated due to high temperature" } ], "enabled": true } // Response example { "code": 200, "message": "success", "data": { "scene_automation_id": "automation-001" } ``` -------------------------------- ### MQTT Protocol Integration Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Details on how to integrate devices using the MQTT protocol for telemetry, attributes, commands, and events. ```APIDOC ### MQTT Protocol Integration ThingsPanel implements comprehensive MQTT-based device communication with support for telemetry, attributes, commands, and events. #### Device Telemetry Publishing This Go code snippet demonstrates how a device can publish telemetry data to the ThingsPanel platform. ```go package main import ( "encoding/json" "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) // publishTelemetry sends standard device telemetry. func publishTelemetry(client mqtt.Client, deviceNumber string) error { topic := "devices/telemetry" telemetryData := map[string]interface{}{ "device_number": deviceNumber, "temperature": 23.5, "humidity": 45.2, "timestamp": time.Now().Unix(), } payload, err := json.Marshal(telemetryData) if err != nil { return err } token := client.Publish(topic, 0, false, payload) token.Wait() return token.Error() } // publishGatewayTelemetry sends telemetry from a gateway device for its sub-devices. func publishGatewayTelemetry(client mqtt.Client, gatewayNumber string, subDeviceAddr string) error { topic := "gateway/telemetry/" + gatewayNumber + "/" + subDeviceAddr telemetryData := map[string]interface{}{ "sub_device_addr": subDeviceAddr, "voltage": 220.5, "current": 5.2, "power": 1146.6, "timestamp": time.Now().Unix(), } payload, err := json.Marshal(telemetryData) if err != nil { return err } token := client.Publish(topic, 0, false, payload) token.Wait() return token.Error() } #### Receiving Commands This Go code snippet shows how a device can subscribe to command topics and process incoming commands from the platform. ```go // subscribeToCommands subscribes to command topics for a specific device. func subscribeToCommands(client mqtt.Client, deviceNumber string) error { topic := "devices/command/" + deviceNumber + "/+" token := client.Subscribe(topic, 1, func(client mqtt.Client, msg mqtt.Message) { var command struct { Identify string `json:"identify"` Value json.RawMessage `json:"value"` MessageID string `json:"message_id"` } if err := json.Unmarshal(msg.Payload(), &command); err != nil { return } // Process command result := processCommand(command.Identify, command.Value) // Send response responseTopic := "devices/command/response/" + command.MessageID responsePayload, _ := json.Marshal(result) client.Publish(responseTopic, 1, false, responsePayload) }) token.Wait() return token.Error() } // processCommand simulates command processing. func processCommand(identify string, value json.RawMessage) map[string]interface{} { return map[string]interface{}{ "status": "success", "message": "Command executed", "timestamp": time.Now().Unix(), } } ``` **Note:** This section only provides Go examples for MQTT interaction. Actual implementation details may vary based on the specific MQTT client library and device environment. ``` -------------------------------- ### Device Management - Create Device Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a new IoT device in the system with automatic credential generation and configuration assignment. ```APIDOC ## POST /api/v1/device ### Description Creates a new IoT device in the system with automatic credential generation and configuration assignment. ### Method POST ### Endpoint /api/v1/device #### Request Body - **name** (string) - Required - The name of the device. - **product_id** (string) - Required - The ID of the product the device belongs to. - **device_number** (string) - Required - A unique identifier for the device. - **device_config_id** (string) - Optional - The ID of the device configuration. - **protocol** (string) - Required - The communication protocol used by the device (e.g., MQTT). - **access_way** (string) - Required - The access method for the device (e.g., direct). - **label** (string) - Optional - A label or tag for the device. - **location** (string) - Optional - Geographic location of the device, usually a JSON string. - **description** (string) - Optional - A detailed description of the device. - **protocol_config** (string) - Optional - Configuration specific to the device's protocol. - **remark1** (string) - Optional - A general remark field. ### Request Example ```json { "name": "Temperature Sensor 01", "product_id": "550e8400-e29b-41d4-a716-446655440000", "device_number": "DEV-TEMP-001", "device_config_id": "660e8400-e29b-41d4-a716-446655440001", "protocol": "MQTT", "access_way": "direct", "label": "Building A - Floor 1", "location": "{\"lat\": 40.7128, \"lng\": -74.0060}", "description": "Temperature monitoring sensor for HVAC control", "protocol_config": "{\"sampling_interval\": 60}", "remark1": "Calibration date: 2025-01-15" } ``` ### Response #### Success Response (200) - **code** (integer) - The response status code. - **message** (string) - A message indicating the success of the operation. - **data** (object) - An object containing the created device information. - **id** (string) - The unique identifier of the created device. - **name** (string) - The name of the device. - **device_number** (string) - The device number. - **voucher** (string) - Device credentials (e.g., username and password) in JSON format. - **is_online** (integer) - Online status of the device (0 for offline, 1 for online). - **activate_flag** (string) - Activation status of the device. - **tenant_id** (string) - The ID of the tenant the device belongs to. - **created_at** (string) - The timestamp when the device was created. #### Response Example ```json { "code": 200, "message": "success", "data": { "id": "770e8400-e29b-41d4-a716-446655440002", "name": "Temperature Sensor 01", "device_number": "DEV-TEMP-001", "voucher": "{\"username\":\"a1b2c3d4e5f6g7h8i9j0k1\",\"password\":\"m2n3o4p\"}", "is_online": 0, "activate_flag": "active", "tenant_id": "tenant-123", "created_at": "2025-12-06T10:30:00Z" } } ``` ``` -------------------------------- ### Create Alarm Rule Configuration Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a new alarm configuration rule for a device. Requires alarm name, device ID, condition details, alarm level, and notification types. Returns the created alarm configuration ID. ```go // POST /api/v1/alarm/config // Request body example { "name": "High Temperature Alert", "device_id": "770e8400-e29b-41d4-a716-446655440002", "condition": "{\"key\": \"temperature\", \"operator\": \">\", \"value\": 30.0}", "alarm_level": "critical", "notification_type": ["email", "webhook"], "description": "Alert when temperature exceeds 30 degrees" } // Response example { "code": 200, "message": "success", "data": { "id": "alarm-config-001", "name": "High Temperature Alert", "tenant_id": "tenant-123", "created_at": "2025-12-06T13:00:00Z" } ``` -------------------------------- ### POST /api/v1/command/datas/pub Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Publishes a command to a specific device via MQTT. This is used for remote control and triggering actions on devices. ```APIDOC ## POST /api/v1/command/datas/pub ### Description Publishes a command to a device via MQTT for remote control operations. ### Method POST ### Endpoint /api/v1/command/datas/pub #### Request Body - **device_id** (string) - Required - The unique identifier of the target device. - **identify** (string) - Required - The identifier of the command to be executed. - **value** (string) - Required - The payload or parameters for the command, typically a JSON string. - **sub_device_addr** (string) - Optional - Address of a sub-device if applicable. ### Request Example ```json { "device_id": "770e8400-e29b-41d4-a716-446655440002", "identify": "set_temperature_threshold", "value": "{\"threshold\": 25.0, \"action\": \"alert\"}", "sub_device_addr": "" } ``` ### Response #### Success Response (200) - **data** (null) - Typically null upon successful command publication. #### Response Example ```json { "code": 200, "message": "success", "data": null } ``` **Note:** The actual message is published to an MQTT topic like `devices/command/DEV-TEMP-001/{message_id}` with a payload containing `identify` and `value`. ``` -------------------------------- ### POST /api/v1/scene_automations Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a scene automation rule, defining triggers and actions to automate device workflows based on specific conditions. ```APIDOC ## POST /api/v1/scene_automations ### Description Creates a scene automation rule with triggers and actions for device workflows. ### Method POST ### Endpoint /api/v1/scene_automations #### Request Body - **name** (string) - Required - The name of the automation rule. - **description** (string) - Optional - A description of the automation. - **trigger_condition** (object) - Required - Defines the condition that triggers the automation. - **type** (string) - Required - The type of trigger (e.g., "device"). - **device_id** (string) - Required if type is "device" - The ID of the device. - **condition** (string) - Required if type is "device" - A JSON string defining the device condition (e.g., `{"key": "temperature", "operator": ">", "value": 28.0}`). - **actions** (array) - Required - A list of actions to perform when the trigger condition is met. - **type** (string) - Required - The type of action (e.g., "command", "notification"). - **device_id** (string) - Required if type is "command" - The target device ID. - **identify** (string) - Required if type is "command" - The command identifier. - **value** (string) - Required if type is "command" - The command payload as a JSON string. - **notification_type** (string) - Required if type is "notification" - The type of notification (e.g., "email"). - **message** (string) - Required if type is "notification" - The notification message. - **enabled** (boolean) - Optional - Whether the automation is currently enabled (default is true). ### Request Example ```json { "name": "HVAC Control Automation", "description": "Automatically control HVAC based on temperature", "trigger_condition": { "type": "device", "device_id": "770e8400-e29b-41d4-a716-446655440002", "condition": "{\"key\": \"temperature\", \"operator\": \">\", \"value\": 28.0}" }, "actions": [ { "type": "command", "device_id": "hvac-device-001", "identify": "set_mode", "value": "{\"mode\": \"cooling\", \"target_temp\": 24.0}" }, { "type": "notification", "notification_type": "email", "message": "HVAC cooling activated due to high temperature" } ], "enabled": true } ``` ### Response #### Success Response (200) - **scene_automation_id** (string) - The unique identifier of the created automation rule. #### Response Example ```json { "code": 200, "message": "success", "data": { "scene_automation_id": "automation-001" } } ``` ``` -------------------------------- ### Create Device Group - Go API Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Enables the creation of hierarchical device groups for organizing devices. The API endpoint is POST /api/v1/device/group. It requires a JSON request body including the group name, optional parent ID, description, and tier. The response confirms the creation with the new group's ID and details. ```go // POST /api/v1/device/group // Request body example { "name": "Building A Sensors", "parent_id": "group-parent-001", "description": "All sensors in Building A", "tier": 2 } // Response example { "code": 200, "message": "success", "data": { "id": "group-001", "name": "Building A Sensors", "parent_id": "group-parent-001", "tier": 2, "created_at": "2025-12-06T15:00:00Z" } } ``` -------------------------------- ### Device Templates - Create Device Template Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a device function template that defines the physical model and capabilities of a device. ```APIDOC ## POST /api/v1/device/template ### Description Creates a device function template defining the physical model and capabilities. ### Method POST ### Endpoint /api/v1/device/template ### Parameters #### Request Body - **name** (string) - Required - The name of the device template. - **description** (string) - Optional - A description for the device template. - **device_type** (string) - Required - The type of the device (e.g., "sensor"). - **flag** (string) - Optional - A flag for the template (e.g., "standard"). - **model_config** (object) - Required - Configuration for the device model. - **telemetry** (array) - Required - List of telemetry data points. - **key** (string) - Required - The unique key for the telemetry. - **name** (string) - Required - The display name for the telemetry. - **data_type** (string) - Required - The data type (e.g., "float"). - **unit** (string) - Optional - The unit of measurement. - **attributes** (array) - Optional - List of device attributes. - **key** (string) - Required - The unique key for the attribute. - **name** (string) - Required - The display name for the attribute. - **data_type** (string) - Required - The data type (e.g., "string"). - **commands** (array) - Optional - List of commands the device can execute. - **key** (string) - Required - The unique key for the command. - **name** (string) - Required - The display name for the command. - **params** (array) - Optional - Parameters for the command. - **key** (string) - Required - The key for the parameter. - **data_type** (string) - Required - The data type of the parameter. ### Request Example ```json { "name": "Environmental Sensor Template", "description": "Template for temperature and humidity sensors", "device_type": "sensor", "flag": "standard", "model_config": { "telemetry": [ {"key": "temperature", "name": "Temperature", "data_type": "float", "unit": "°C"}, {"key": "humidity", "name": "Humidity", "data_type": "float", "unit": "%"} ], "attributes": [ {"key": "location", "name": "Location", "data_type": "string"}, {"key": "firmware_version", "name": "Firmware Version", "data_type": "string"} ], "commands": [ {"key": "reset", "name": "Reset Device", "params": []}, {"key": "calibrate", "name": "Calibrate Sensor", "params": [{"key": "offset", "data_type": "float"}]} ] } } ``` ### Response #### Success Response (200) - **code** (integer) - The status code of the response. - **message** (string) - A message indicating the success of the operation. - **data** (object) - Contains the details of the created device template. - **id** (string) - The unique identifier of the created template. - **name** (string) - The name of the template. - **created_at** (string) - The timestamp when the template was created. #### Response Example ```json { "code": 200, "message": "success", "data": { "id": "template-001", "name": "Environmental Sensor Template", "created_at": "2025-12-06T14:00:00Z" } } ``` ``` -------------------------------- ### POST /api/v1/alarm/config Source: https://context7.com/thingspanel/thingspanel-backend-community/llms.txt Creates a new alarm configuration rule. These rules define conditions under which alarms are triggered for devices. ```APIDOC ## POST /api/v1/alarm/config ### Description Creates an alarm configuration rule for monitoring device conditions. ### Method POST ### Endpoint /api/v1/alarm/config #### Request Body - **name** (string) - Required - The name of the alarm rule. - **device_id** (string) - Required - The identifier of the device to monitor. - **condition** (string) - Required - A JSON string defining the alarm condition (e.g., `{"key": "temperature", "operator": ">", "value": 30.0}`). - **alarm_level** (string) - Required - The severity level of the alarm (e.g., "critical", "warning", "info"). - **notification_type** (array) - Required - A list of notification methods to use (e.g., ["email", "webhook"]). - **description** (string) - Optional - A detailed description of the alarm rule. ### Request Example ```json { "name": "High Temperature Alert", "device_id": "770e8400-e29b-41d4-a716-446655440002", "condition": "{\"key\": \"temperature\", \"operator\": \">\", \"value\": 30.0}", "alarm_level": "critical", "notification_type": ["email", "webhook"], "description": "Alert when temperature exceeds 30 degrees" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created alarm configuration. - **name** (string) - The name of the alarm rule. - **tenant_id** (string) - The identifier of the tenant associated with the rule. - **created_at** (string) - The timestamp when the alarm rule was created. #### Response Example ```json { "code": 200, "message": "success", "data": { "id": "alarm-config-001", "name": "High Temperature Alert", "tenant_id": "tenant-123", "created_at": "2025-12-06T13:00:00Z" } } ``` ``` -------------------------------- ### Initialize on Page Load and Resize Source: https://github.com/thingspanel/thingspanel-backend-community/blob/main/static/metrics-viewer_en.html Initializes the charts and refreshes the data when the page loads. It also handles window resize events to ensure the charts resize accordingly. This function ensures that the metrics are displayed correctly when the page is first loaded and when the browser window changes size. ```javascript // Initialize on page load window.onload = function() { initCharts(); refreshData(); }; // Handle window resize window.onresize = function() { Object.values(charts).forEach(chart => chart.resize()); }; ```