ThingsPanel Documentation

repository·main·Indexed 20 days ago

https://github.com/thingspanel/thingspanel-backend-community

A lightweight, componentized open-source IoT application support platform. This documentation covers the platform's plugin architecture, MQTT device data concepts (telemetry, attributes, events, and commands), and device integration specifications. It also includes detailed guides for the iot-platform-autotest framework, an automated testing tool for verifying MQTT connections, data reporting, and command execution for both direct and gateway devices.

Tokens
73.1K
Snippets
159
Records
305
Agent score
69%

What's inside ThingsPanel

  1. Overview of IoT Platform Automation Test Framework

    main
    The iot-platform-autotest is an automated testing framework for the ThingsPanel IoT platform. It is designed to verify core functionalities including MQTT device connection, data reporting (telemetry, attributes, and events), and command execution (platform-to-device control and attribute settings). It also includes automatic database verification to ensure data is correctly persisted.
  2. Understand the ThingsPanel project structure

    main

    The backend project follows this directory structure:

    • main.go: The main entry point of the application.
    • middleware/: Contains middleware components.
      • response/: Handles API response formatting. Includes middleware.go and response.go (defines response structs).
    • pkg/: Public/shared packages.
      • errcode/: Error code management (constants, definitions, manager, and validator).
      • metrics/: Performance monitoring and metrics definitions.
    • config/: Configuration files.
      • config.yaml: Main application configuration.
      • messages.yaml: Configuration for error messages.
    • go.mod: Go module definition.
  3. Understand the ThingsPanel backend project structure

    main

    The ThingsPanel backend follows a layered architecture designed to separate concerns between API handling, business logic, and data access. Understanding this structure is essential for navigating the codebase and implementing new features.

    Core Layers

    • cmd/: The entry points for the application.
    • internal/: Private application and library code, organized into functional layers:
      • api/: The API interface layer (e.g., ./internal/apisys_user.go).
      • service/: The business logic layer (e.g., ./internal/service/user_service.go).
      • dal/: The Data Access Layer (e.g., ./internal/dal/user_dal.go).
      • model/: Data model definitions (e.g., ./internal/model/user.go).
      • query/: Query builders, typically generated (e.g., ./internal/query/user_query.go).
      • middleware/: Middleware components (e.g., ./internal/middleware/auth.go).
      • app/: Application-specific code.
    • router/: HTTP route configurations.
    • pkg/: Publicly usable libraries and utilities:
      • utils/: General utility functions.
      • metrics/: Metrics collection.
      • global/: Global variables and configurations.
      • errcode/: Error code definitions.
      • constant/: Constant definitions.
      • common/: Common code.

    Infrastructure and Resources

    • configs/: Configuration files.
    • sql/: SQL scripts and migration files.
    • initialize/: Application initialization logic.
    • third_party/: Third-party service integrations (including mqtt/).
    • static/: Static assets.
    • files/: File storage directory.
  4. Understand the ThingsPanel Backend directory structure

    main

    ThingsPanel Backend follows a modular, layered architecture designed for IoT workloads. Use this overview to locate specific components of the system:

    Core Directories

    • cmd/: CLI tools, including GORM code generation (gen/), automated testing (iot-platform-autotest/), and virtual sensor simulations (virtual_sensor/).
    • configs/: Runtime configuration files (conf.yml, conf-dev.yml), internationalization files (messages*.yaml), and RSA keys (rsa_key/).
    • docs/: Project documentation, API specifications, and Swagger assets.
    • initialize/: System startup logic, including database (pg_init.go), cache (alarm_cache.go), Redis (redis_init.go), and security (casbin_init.go) initialization.
    • internal/: The core business logic, organized by layer:
      • api/: HTTP interface handling.
      • service/: Business service layer.
      • dal/: Data access layer.
      • model/: Data models (contains auto-generated .gen.go files).
      • uplink/ & downlink/: Message processing buses for incoming and outgoing IoT data.
      • adapter/: MQTT adaptation and message bridging.
    • mqtt/: MQTT client logic, including publish/subscribe implementations and simulation tools.
    • pkg/: Shared libraries, including constant/, errcode/, and global/ configuration.
    • router/: HTTP and SSE (Server-Sent Events) route initialization.
    • sql/: Database schema and migration scripts.
    • third_party/: Wrappers for external services like gRPC clients.

    Root Files

    • main.go: The primary application entry point.
    • Dockerfile: Containerization instructions.
  5. ThingsPanel Core Features Overview

    main

    ThingsPanel provides a comprehensive suite of IoT management features:

    • Device Management: Project creation, grouping, device plugin integration, gateway/sub-device support, and protocol support (Modbus RTU/TCP, TCP, GB28181, and custom protocols).
    • Monitoring & Visualization: Dashboard creation, device monitoring charts, device maps, and advanced visualization (3D, Three.js, and large-screen configurations).
    • Product & Firmware: Product lifecycle management (creation, QR codes, manual activation) and OTA firmware upgrades.
    • Automation & Rules Engine: Scenario linkage (scene triggering), scheduled tasks, device-triggered actions, and data forwarding/transformation via a rules engine.
    • Alerting & Notifications: Alarm management by project/group and multiple notification channels (SMS, Email, Phone, Webhook).
    • Data Gateway: OpenAPI support, SQL-to-HTTP conversion, and third-party system integration with IP/data range restrictions.
    • User & Multi-tenancy: Super admin management, tenant account/user management, and granular permission control (Casbin-based).
  6. Explore the IoT Platform Automation Test Framework design

    main

    The IoT Platform Automation Test Framework is designed to validate the platform's capabilities through several testing dimensions. Users can extend the framework to perform:

    • Performance Testing: Validating concurrency (multiple devices/gateways reporting simultaneously), stress testing (high-volume data reporting), and performance benchmarking.
    • Stability Testing: Simulating network anomalies, testing disconnection and reconnection logic, and conducting long-duration stability runs.
    • Functional Extensions: Implementing OTA (Over-the-Air) upgrade tests, testing deeper gateway hierarchies (3+ layers), and integrating with CI/CD pipelines.
  7. Key architectural features of ThingsPanel

    main

    ThingsPanel is built with the following design principles:

    • Modular Design: Functional modules are relatively independent, allowing for easier maintenance and updates.
    • Extensibility: A plugin mechanism is provided to support different protocols and additional services.
    • High Performance: Leverages Redis for caching and TimescaleDB for efficient time-series data management.
    • Real-time Capability: Achieves low-latency data transmission and status updates using MQTT and WebSocket.
    • Security: Implements security via JWT-based authentication and RBAC (Role-Based Access Control).
  8. Understand the ThingsPanel Device Data Ingestion Architecture

    main

    ThingsPanel uses a five-layer architecture to handle device data flow, ensuring protocol independence and high performance through asynchronous processing.

    Uplink Data Flow (Device to Database): DeviceAdapter LayerUplink LayerProcessor LayerStorage LayerDatabase (with an optional Forwarder for data dispatch).

    Downlink Data Flow (Platform to Device): API/ScenarioDownlink LayerAdapter LayerDevice.

    Core Principles:

    • Protocol Isolation: The Adapter layer masks protocol differences so upper layers handle unified data.
    • Message-Driven: Layers communicate via a Bus (Message Bus) to decouple components.
    • Asynchronous Processing: Uses a producer-consumer pattern based on Go Channels.
    • Interface Abstraction: Components depend on interfaces rather than concrete implementations, facilitating testing and extensibility.
  9. Future expansion of the Marketplace authentication design

    main

    The current authentication design (Device Flow with instance binding) is architected to allow several future upgrades without breaking existing integrations:

    • Authorization Code + PKCE: The system supports coexistence with the Authorization Code flow using PKCE. Because the binding mechanism and token consumption are decoupled, you can replace the token acquisition step with a redirect-based flow once an instance has a stable public domain or reverse proxy. All existing components like TokenProvider and MarketClient are reusable.
    • Organizational Management: The instance_bindings table includes an org_id field, enabling future support for managing multiple instances under a single organization, sharing quotas/credits at the org level, and batch revoking bindings when members change.
    • Subscription and Billing Integration: The binding relationship serves as the anchor for billing. Subscription levels can be attached to instance_bindings to control marketplace access, and the existing market-service credit system can be used to meter usage based on both user_id and instance_id.
    • Advanced Authentication (MFA/SSO): Since authentication occurs on the Horizon page, adding MFA, GitHub/WeChat login, or Enterprise SSO (SAML/OIDC) requires zero changes to the ThingsPanel backend.
    • Observability and Remote Revocation: The last_seen_at field allows the Horizon backend to track active instances, perform remote revocation of abnormal instances, and generate version distribution statistics.
    • Offline Installation Support: For isolated intranet environments, the system is designed to support exporting signed resource packages from a bound instance on a connected machine, which can then be imported into an isolated environment using signature verification instead of online tokens.
  10. Use cases for the data_identifier field

    main

    The data_identifier field is used to improve topic conversion precision in the following scenarios:

    1. Precise Matching: Configure specific topic conversion rules for specific data identifiers (e.g., temperature, humidity).
    2. Rule Filtering: Combine the data identifier with topic matching to select the most appropriate rule.
    3. Business Association: Link topic conversion rules directly to data identifiers within the device model for easier management.

    Note: The field is optional and can be null. It serves as a business-level identifier and does not change the core underlying topic matching logic.

  11. Understand the user authority and tenant isolation model

    main

    ThingsPanel implements a multi-tenant architecture with three distinct user authority levels. Data isolation is enforced using a tenant_id field in the database tables.

    User Authority Levels

    • SYS_ADMIN: System Administrator. Can create tenants and tenant administrators.
    • TENANT_ADMIN: Tenant Administrator. Can create tenant users within their specific tenant.
    • TENANT_USER: Tenant User. Restricted to data within their tenant.

    Data Isolation Logic

    When a request is made by a TENANT_ADMIN or TENANT_USER, the backend must filter all queries by the user's tenant_id to ensure they only access data belonging to their own tenant.

  12. Understand device diagnostic metrics and formulas

    main

    The device diagnostic panel tracks three core performance indicators to help troubleshoot IoT connectivity and data integrity issues:

    • Uplink Success Rate: (uplink_total - uplink_failed) / uplink_total × 100%. Measures message processing success (Adapter + Processor stages).
    • Downlink Success Rate: (downlink_total - downlink_failed) / downlink_total × 100%. Measures command delivery success.
    • Storage Success Rate: (uplink_total - storage_failed) / uplink_total × 100%. Measures data persistence success (writing to the database).