A Home Assistant-based third-party smart home device integration system and method

By using the OAuth 2.0 authorization code mode and device entity status synchronization mechanism, the problems of insufficient integration depth, low security and low synchronization efficiency in the integration of third-party smart home devices with Home Assistant are solved, and efficient and secure device management and status synchronization are achieved.

CN122179232APending Publication Date: 2026-06-09NANJING TECH UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
NANJING TECH UNIV
Filing Date
2026-04-24
Publication Date
2026-06-09

Smart Images

  • Figure CN122179232A_ABST
    Figure CN122179232A_ABST
Patent Text Reader

Abstract

The application discloses a kind of third-party smart home equipment integration system and method based on Home Assistant, it is related to smart home technical field.The system includes: authentication authorization module, for completing third-party cloud platform authorization based on OAuth 2.0 agreement, obtains and manages token, enters degradation mode when refreshing fails, keeps device entity visibility and disables control function;Device discovery and registration module, for calling device list interface to create device entity;State synchronization module, for periodically polling device state, and state data is cached through coordinator instance, triggers interface refreshing;Instruction conversion and control module, for converting standard control instruction into third-party cloud platform private protocol instruction and sending.The application retains device entity when token is invalid, avoids user repeated configuration, simultaneously realizes state accurate synchronization by coordinator mechanism, improves the robustness and user experience of smart home integration.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of smart home technology, and more specifically, to a third-party smart home device integration system and method based on Home Assistant. Background Technology

[0002] Home Assistant is an open-source smart home platform that allows users to integrate smart devices from different manufacturers. Currently, integrating third-party smart devices into Home Assistant typically involves developing dedicated integration components and using the open APIs of third-party cloud platforms to achieve device discovery, status synchronization, and control command delivery.

[0003] Existing integration solutions have the following technical problems in practical applications: First, the integration depth is insufficient. Traditional integration only implements basic function mapping and cannot call device-specific functions. At the same time, it is highly dependent and prone to failure. The integration code is tightly coupled with the device API interface. When the device is updated, the original integration components are prone to failure, resulting in high maintenance costs. Second, the authorization process has flaws in terms of security or user experience. Some integration solutions require users to directly enter the account and password of the third-party platform in Home Assistant, which poses a risk of credential leakage; other solutions, although using the OAuth 2.0 authorization process, cannot automatically complete the token exchange, requiring users to manually copy and paste the authorization code, which is cumbersome.

[0004] Third, the token expiration handling mechanism is inadequate. When the access token expires and the refresh token fails, the existing solution usually deletes the added device entity directly. Users need to re-execute the entire device addition process, and the configured automation rules and interface layout are lost, resulting in a poor user experience.

[0005] Fourth, the efficiency of device status synchronization and control command conversion is low. Existing solutions lack a unified scheduling mechanism for status updates and control feedback, which easily leads to inconsistencies between the interface display and the actual device status. At the same time, the parameter mapping between different manufacturers' proprietary protocols and the Home Assistant standard protocol lacks flexible adaptation capabilities, resulting in a large workload for integration development and poor compatibility.

[0006] Therefore, there is an urgent need in this field for a smart home integration system that can deeply, stably, and easily maintain specific brand devices, and can provide intuitive, immersive visual interaction. Summary of the Invention

[0007] To address the aforementioned problems, this invention provides a third-party smart home device integration system and method based on Home Assistant.

[0008] To achieve the above objectives, the present invention provides the following technical solution: In a first aspect, the present invention provides a third-party smart home device integration system based on Home Assistant, comprising: The authentication and authorization module is used to guide users to complete the authorization of the third-party cloud platform based on the OAuth 2.0 protocol, obtain and securely store access tokens and refresh tokens, and automatically use the refresh token to refresh when the access token expires, and enter the degradation mode when the refresh fails. The degradation mode includes: maintaining the interface visibility of the created device entity, while disabling the control function of the device entity. The device discovery and registration module is used to call the device list query interface of the third-party cloud platform after obtaining a valid access token, parse the returned device information, and create the corresponding device entity in the Home Assistant platform based on the parsing results. The status synchronization module is used to obtain the latest status data of all devices by periodically calling the status query interface of the third-party cloud platform, and maintain a coordinator instance for each device entity. The coordinator instance is used to cache the status data of the corresponding device and trigger the corresponding device entity to refresh the interface display when the status data is updated. The command conversion and control module is used to receive standard control commands issued by the Home Assistant platform, parse the control parameters in the commands, convert the standard control commands and parameters into private protocol commands that can be recognized by the third-party cloud platform, send them to the cloud by calling the control interface of the third-party cloud platform, and trigger the status synchronization module to refresh the device status after the command is sent.

[0009] Preferably, the authentication and authorization module includes: The authorization guidance unit is used to generate the URL of the OAuth 2.0 authorization page of the third-party cloud platform, guiding users to access and authorize it; The credential management unit is used to obtain the authorization code via the callback URL and exchange the authorization code for an access token and a refresh token. The token storage unit is used to securely store access tokens, refresh tokens, and their expiration dates. Token refresh unit: Used to automatically request a new access token from a third-party cloud platform and update the token storage unit when the access token is about to expire or has already expired; Degradation processing unit: used to mark the authentication status as requiring re-authentication and enter the degradation mode when the token refresh unit fails to refresh.

[0010] Preferably, the device discovery and registration module includes: The device list acquisition unit is used to call the device list query interface of a third-party cloud platform using a valid access token to obtain device list data under the user account. The device information parsing unit is used to parse the device list data and extract the device unique identifier, device name, device model, online status and device capability set information from each device; The entity creation unit is used to create a device entity that conforms to the platform entity specification for each device in the Home Assistant platform based on the information extracted by the device information parsing unit.

[0011] Preferably, the state synchronization module includes: The status polling unit is used to periodically call the status query interface of the third-party cloud platform according to a preset polling frequency to obtain real-time status data of all devices; The coordinator unit maintains an independent coordinator instance for each device entity. The coordinator instance is used to store the latest status data of the corresponding device and, when the status polling unit obtains updated status data, notifies the corresponding device entity to refresh the interface display.

[0012] Preferably, the instruction conversion and control module includes: The instruction receiving unit is used to listen for and receive service call instructions for device entities issued by the Home Assistant platform; The parameter parsing unit is used to parse the control parameters contained in the service call command; The protocol conversion unit is used to convert service call instructions and control parameters into control commands in the private protocol format of a third-party cloud platform. The conversion includes mapping the standard parameter range of the Home Assistant platform to the parameter range required by the third-party cloud platform. The command sending unit is used to send the converted control commands to the cloud through the control interface of a third-party cloud platform. The status feedback unit is used to trigger the status synchronization module to refresh the status of the corresponding device after the instruction sending unit sends the control command, so as to display the control execution result on the interface.

[0013] Preferably, the protocol conversion unit also supports encapsulating multiple control parameters into a list of key-value pairs, which can be sent to the cloud through a single control interface call to achieve batch parameter control.

[0014] Preferred options also include: The platform adaptation and compatibility module inherits the standard device abstract class of the Home Assistant platform, implements the attribute interfaces and method interfaces required by the platform, and provides format conversion, field mapping and unit conversion functions between third-party cloud platform data and Home Assistant platform standard data.

[0015] Secondly, the present invention provides a visual smart home integration method based on Home Assistant, applied to the aforementioned system, comprising the following steps: The authentication and authorization process guides users to complete the authorization of the third-party cloud platform based on the OAuth 2.0 protocol, obtains and securely stores the access token and refresh token; when the access token expires, the refresh token is automatically used to refresh, and if the refresh fails, the process enters a fallback mode, which includes: maintaining the interface visibility of the created device entity while disabling the control functions of the device entity; The device discovery and registration process involves obtaining a valid access token, calling the device list query interface of the third-party cloud platform, parsing the returned device information, and creating the corresponding device entity in the Home Assistant platform based on the parsing results. The status synchronization step involves periodically calling the status query interface of a third-party cloud platform to obtain the latest status data of all devices, and maintaining a coordinator instance for each device entity. The coordinator instance is used to cache the status data of the corresponding device and trigger the corresponding device entity to refresh the interface display when the status data is updated. The command conversion and control steps involve receiving standard control commands from the Home Assistant platform, parsing the control parameters in the commands, converting the standard control commands and parameters into private protocol commands that can be recognized by the third-party cloud platform, sending them to the cloud by calling the control interface of the third-party cloud platform, and triggering a status synchronization step to refresh the device status after the commands are sent.

[0016] Preferably, the authentication and authorization steps specifically include: Generate the URL of the OAuth 2.0 authorization page for the third-party cloud platform, and guide the user to visit and authorize it; Obtain the authorization code via the callback URL, and then exchange the authorization code for an access token and a refresh token; Securely store the access token, refresh token, and their expiration dates; When the access token is about to expire or has expired, the refresh token is automatically used to request a new access token from the third-party cloud platform. When the refresh fails, the authentication status is marked as requiring re-authentication, and the system enters downgrade mode.

[0017] Preferably, in the instruction conversion and control step, converting standard control instructions and parameters into private protocol instructions that can be recognized by the third-party cloud platform includes: mapping the standard parameter range of the Home Assistant platform to the parameter range required by the third-party cloud platform, and encapsulating multiple control parameters into a list of key-value pairs and sending them to the cloud through a single control interface call.

[0018] Compared to existing technologies, it has the following significant advantages: (1) High security and good user experience. This invention adopts the OAuth 2.0 authorization code mode, and user credentials are not transmitted through this system, avoiding the risk of account password leakage. In the token exchange process, a semi-automatic method of manually pasting authorization codes is supported, which achieves integrated configurability while ensuring security.

[0019] (2) Device entities are retained when tokens expire, improving system robustness. When refreshing the token also expires, this invention does not delete the created device entities, but only disables the control function, and the device remains visible on the Home Assistant interface. Control can be restored after the user re-authenticates, without having to add the device and configure automation rules again, thus avoiding data loss. Compared with traditional solutions, the degradation mode can increase the user configuration retention rate from 0% to 100%; at the same time, control is restored immediately after re-authentication, without having to rediscover and configure the device.

[0020] (3) Accurate and efficient state synchronization. This invention maintains an independent coordinator instance for each device entity, obtains the device status through periodic polling and caches it in the coordinator, and accurately notifies the corresponding device entity to refresh the interface when the status is updated, avoiding the performance overhead of full refresh. The coordinator is triggered to actively refresh immediately after the control command is sent, ensuring that the interface status is quickly consistent with the actual device status. Compared with the traditional polling scheme, the coordination mechanism can reduce network requests by 30-50%.

[0021] (4) Flexible protocol adaptation and strong scalability. This invention maps Home Assistant standard commands to third-party cloud platform private protocols through a protocol conversion unit, supports multi-parameter range conversion and batch packaging of brightness, color temperature and other parameters, and can quickly adapt to the capability sets of devices from different manufacturers, reducing the development cost of new device access. Attached Figure Description

[0022] Figure 1 This is a flowchart illustrating the authentication and authorization process for the Home Assistant-based visualized smart home integration method of this invention. Figure 2 This is a flowchart illustrating the token management and automatic refresh process of the Home Assistant-based visualized smart home integration method of the present invention. Figure 3This diagram illustrates the device discovery and initialization process of the Home Assistant-based visualized smart home integration method of this invention. Figure 4 This is a schematic diagram of the device synchronization mechanism of the visual smart home integration method based on Home Assistant of the present invention.

[0023] Figure 5 A visual login platform diagram for the lipro device added to this invention; Figure 6 This is a customized integrated visualization diagram for this invention. Detailed Implementation

[0024] The technical solutions in the embodiments of the present invention will be clearly and completely described below. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0025] This embodiment provides a third-party smart home device integration system based on Home Assistant, which can be applied to third-party cloud platforms with open APIs, and mainly includes: 1. The authentication and authorization module adopts a cloud-based authentication mechanism based on the OAuth 2.0 authorization code model, including: Authorization Guidance Unit: Generates an authorization URL to guide users to the authorization page of the third-party device manufacturer; Credentials Management Unit: Obtains the authorization code via the callback URL and exchanges it for an access token and a refresh token; Token storage unit: Securely stores access tokens and refresh tokens, and records the token validity period; Token refresh unit: Automatically triggers the refresh process when the access token is about to expire or has expired, uses the refresh token to obtain a new access token from the third-party cloud platform, and updates the token storage unit; Degradation processing unit: When the refresh token also expires or authentication fails, a re-authentication process is triggered, but the created device entity is not deleted. The device is kept visible on the interface, and only the control function is disabled.

[0026] 2. The device discovery and registration module, after obtaining a valid access token, calls the device list query interface of the third-party cloud platform, parses the returned device information, and creates the corresponding device entity in the Home Assistant platform based on the parsing results, including: Device list retrieval unit: Periodically calls the device list query interface of the third-party cloud platform (such as v1 / user / index.do) to retrieve all device information under the user account; Device information parsing unit: Parses the returned JSON data and extracts the device's unique ID, device name, model, online status, and device capability set; Entity Creation Unit: Based on the information extracted by the Device Information Parsing Unit, a device entity conforming to the platform entity specification is created for each device in the Home Assistant platform.

[0027] 3. A status synchronization module periodically calls the status query interface of a third-party cloud platform to obtain the latest status data of all devices. It maintains a coordinator instance for each device entity. The coordinator instance caches the status data of the corresponding device and triggers a refresh of the interface display for the corresponding device entity when the status data is updated. This includes: Status polling unit: Periodically obtains real-time status data of the device through a dedicated status query interface (such as / app / oauth / api / v2 / user / query / devices / group / state.do); Coordinator Unit: Maintains an independent coordinator instance for each device entity. The coordinator instance is used to store the latest status data of the corresponding device and, when the status polling unit obtains updated status data, notifies the corresponding device entity to refresh the interface display.

[0028] 4. Command Conversion and Control Module: Receives standard control commands from the Home Assistant platform, parses the control parameters within the commands, converts the standard control commands and parameters into private protocol commands recognizable by the third-party cloud platform, and sends them to the cloud by calling the third-party cloud platform's control interface. After the commands are sent, it also triggers the status synchronization module to refresh the device status, including: Command receiving unit: Listens for and receives service call commands (such as light.turn_on) issued by the Home Assistant platform for device entities; Parameter parsing unit: Parses the control parameters (such as on / off status, brightness value, color temperature value, etc.) contained in the service call command; Protocol conversion unit: Converts service call commands and control parameters into private protocol commands that can be recognized by the third-party cloud platform, and sends them to the cloud through the control interface (such as / app / oauth / api / v2 / user / control / device / group / command.do); Command sending unit: converts service call commands and control parameters into control commands in the private protocol format of the third-party cloud platform. The conversion includes mapping the standard parameter range of the Home Assistant platform to the parameter range required by the third-party cloud platform. Batch parameter encapsulation unit: Supports carrying multiple control parameters in the same instruction (such as setting brightness and on / off status at the same time), and encapsulates the request data in the form of a key-value pair list; Status feedback unit: After the command is sent, the coordinator triggers a status refresh to ensure that the interface status is consistent with the control result.

[0029] 5. Platform Adaptation and Compatibility Module: This module inherits from the standard device abstract class of the Home Assistant platform, implements the attribute and method interfaces required by the platform, and provides format conversion, field mapping, and unit conversion functions between third-party cloud platform data and Home Assistant platform standard data, including: Basic framework adaptation unit: Inherits the standard device abstract class of the smart home platform and implements various attribute interfaces and method interfaces required by the platform; Data format conversion unit: Handles format differences between third-party platform data and platform standard data, including but not limited to: Device list data structure parsing and field mapping; Status data field name conversion; Numerical range conversion (e.g., mapping between brightness values ​​0-100 and 0-255); Unit conversion (such as direct transfer or range mapping of color temperature values ​​in Kelvin).

[0030] This embodiment provides a visual smart home integration method based on Home Assistant, including the following steps: 1. Authentication and Authorization Process 1.1 Constructing the Authorization URL When a user configures Lipro integration for the first time, the system constructs a complete OAuth 2.0 authorization URL based on the pre-configured client identifier (client_id), authorization endpoint URL, and redirect URI. The redirect URI is a pre-configured callback address, such as https: / / [ha_domain] / api / lipro / callback. This callback address is used to display the authorization code in the browser's address bar.

[0031] The system displays the above authorization URL as a hyperlink in the configuration interface and prompts the user to click to jump to the official Lipro authorization page.

[0032] 1.2 User Authorization The system displays the aforementioned authorization URL as a hyperlink in the Home Assistant configuration interface and prompts the user to click it to redirect to the official Lipro authorization page. After the user logs in and authorizes on the official Lipro page, the Lipro server redirects the user's browser to the redirect URI, including the authorization code (code) in the query parameters of the redirect URL, for example: https: / / [ha_domain] / api / lipro / callback?code=ABC123XYZ; the user manually copies the authorization code from the browser address bar (i.e., the parameter value after code= in the URL). The user returns to the Home Assistant configuration interface, pastes the copied authorization code into the input box, and submits.

[0033] 1.3 Exchange Tokens The system extracts the authorization code (denoted as `code`) entered by the user and generates a 32-byte random hexadecimal string as the device identifier (denoted as `phone_id`). It then constructs a token exchange request conforming to the OAuth 2.0 standard. The request parameters include `grant_type=authorization_code`, `code`, `redirect_uri()`, `client_id`, and `client_secret`. Here, `grant_type` is a fixed value "authorization_code", indicating that this operation is an authorization code exchange; `code` is the temporary credential obtained by the user through the authorization page; `redirect_uri` (a URI exactly the same as the redirect address used in the authorization request, used for server-side verification), and `client_id` and `client_secret` are system-preset fixed parameters used for server-side identity verification. After URL encoding, the above parameters are sent as a POST request to the pre-defined token endpoint via an asynchronous HTTP client. The request body is in the `application / x-www-form-urlencoded` format. Upon receiving the server response, if the status code is 200, the system parses the JSON-formatted response body and extracts the access token, refresh token, and `expires_in` fields. After a successful token exchange, the system retrieves the `expires_in` field returned by the server (representing the access token's validity period in seconds) and calculates the absolute expiration timestamp: `expire_time = current_timestamp + expires_in - 60s`. This absolute expiration time, along with the access token and refresh token, is stored in the configuration entry. Before each subsequent call to the third-party cloud platform API, the system retrieves the current timestamp and compares it with the stored `expire_time` to determine if the access token has expired. If expired, the token refresh process is automatically triggered. The system securely stores both tokens and records the access token's validity period. If the token exchange request fails, the system catches the exception, logs the error, displays an "Authentication Failed" message to the user, keeps the configuration form visible, and allows the user to re-enter the authorization code.

[0034] Token Management and Auto-Refresh 2.1 API Client Initialization In the Home Assistant platform, the system obtains the asynchronous HTTP session object managed by the platform in the following ways: Python from homeassistant.helpers import aiohttp_client # hass is the core object of HomeAssistant, passed in by the framework during integration initialization. session = aiohttp_client.async_get_clientsession(hass) This session object is managed centrally by the Home Assistant platform and features connection pool reuse and timeout configuration. All HTTP requests should be sent through this session object. Subsequently, the system creates an instance of the LiproApi class, passes in the session object and device identifier, and injects the pre-stored access token, refresh token, and expiration timestamp into the instance using the _replace_tokens method.

[0035] 2.2 Token Validity Check Before each call to the Lipro cloud API, the system checks the validity period of the current access token, specifically whether the remaining validity period (remaining validity period = expiration timestamp - current time) is less than 5 seconds. If the token is about to expire (or has already expired), the system automatically uses the stored refresh token to call Lipro's token refresh interface to obtain a new access token and update the storage.

[0036] 2.3 Token Refresh Process First, the system generates a millisecond-level timestamp and constructs a request parameter dictionary containing the following fields: sign: MD5 hash value, calculated by concatenating the device identifier with a fixed salt value (used for request anti-tampering verification; the server calculates the signature using the same algorithm upon receiving the request and compares it; if they do not match, the request is rejected); optFrom: device identifier; optAt: millisecond-level timestamp; vn: client version number; vc: client version code; model: fixed null value, required by the protocol; refreshToken: refresh token, used to obtain a new access token. The system sends a POST request to the pre-configured API gateway address concatenated with the path / v1 / user / token / refresh.do, with the request body in form format (application / x-www-form-urlencoded) and an 8-second timeout limit.

[0037] 2.4 Successful refresh handling When the refresh request succeeds (HTTP 200), the system performs the following operations: Extract the new token from the response: `access_token`: the new access token; `refresh_token`: the new refresh token; `expires_in`: the expiration time (in seconds) of the new token. Call the `_replace_tokens` method to update local storage: update `self._access` for the new access token, and update `self._refresh` for the new refresh token. Recalculate the internal expiration time: self._exp = current time + expires_in - 60s. After the refresh is complete, continue executing the original API call.

[0038] 2.5 Refresh Failure Handling If the refresh request fails (e.g., the refresh token has expired), the system marks the authentication status as "re-authentication required," but does not delete any created device entities. At this point, the device on the user interface displays an "uncontrollable" status and prompts the user to re-authorize and authenticate.

[0039] 3. Device Discovery and Initialization During integration initialization, the system uses a valid access token to call the Lipro cloud platform's device list query interface. In this process, the system first generates a millisecond-level timestamp and constructs a request parameter dictionary containing the following fields: accessToken: the currently valid access token; sign: MD5 hash value, calculated by concatenating the device identifier with a fixed salt value (used for request tamper-proof verification; the server calculates the signature using the same algorithm upon receiving the request and compares it; if inconsistent, the request is rejected); optFrom: device identifier; optAt: millisecond-level timestamp; vn: client version number; vc: client version code; offset: pagination offset; limit: maximum number of requests per request. Subsequently, an HTTP request is sent. A POST request is sent to the pre-configured API gateway address concatenated with the path / v1 / user / index.do, with the request body in form format and an 8-second timeout limit. This interface returns a list of all devices under the user account in JSON array format. The system receives the JSON response and extracts the device list according to the following path: first, it obtains the value field, then retrieves the devices array from it; if any level does not exist, an empty array is returned.

[0040] The system parses the returned JSON data and extracts the following key information for each device: Unique Device ID: A target identifier used for subsequent status queries and control commands; Device Name: The device name defined by the user in the Lipro App; Equipment model: Used to identify the equipment type and capability set; Online status: Whether the device is currently online; Device capability set: Functions supported by the device (such as brightness adjustment, color temperature adjustment, etc.).

[0041] JSON Example {"code": 200,"message": "success","value": {"devices": [{"serial": "LPA123456789","deviceName": "living room ceiling light","type": 6,"group": true, "online": true,"groupId": "G12345","productId": "FF000001"}]}} Iterate through each device object in the device array and retrieve the `type` field value. Only devices whose value equals a predefined type code (e.g., 6 represents a lighting fixture) are retained for subsequent processing. From the filtered device list, take the `deviceName` field of the first device and use it as the display title for the configuration entry. If the device list is empty, use the default name. In subsequent entity creation phases, extract the device's unique identifier from each device object according to priority: Use the serial field first; If serial does not exist, the groupId field will be used; If neither of these two fields exists, the id field will be used.

[0042] Based on the parsed device list, the system creates a corresponding device entity for each device and registers it with the HA platform. The creation of device entities follows the HA entity specification to ensure consistency with the behavior of other HA devices.

[0043] The process of creating the corresponding device entity is as follows: Read the API client instances and device list corresponding to the current configuration entry from the platform's global storage, and perform the following operations on each device in the device list: Check the device's group field and only proceed with further processing if the value of this field is True (indicating that the device is a group device, such as a ceiling light; this process follows the type field check). Group identifiers are retrieved based on priority: the serial field is used first, followed by groupId, and finally the id field; If the group identifier is empty, skip the device.

[0044] Create a separate coordinator instance for each device, passing in the platform instance, API client, and group identifier. The coordinator is responsible for periodically polling the device status and maintaining a status cache.

[0045] The coordinator's `async_config_entry_first_refresh` method is invoked to attempt to retrieve the device's initial state from the cloud. If the refresh fails, the process is logged but the entity creation process is not interrupted, ensuring that the device can still be added.

[0046] Create a LiproCeilingLight entity instance, passing in the coordinator, raw device data, and API client. If the above process does not create any entity, the system will initiate a rollback to detect: Iterate through all devices and actively call the status query interface to detect device status; If the returned status data contains the fields for switch, brightness, or temperature, it is determined to be a lighting device; Create coordinators and entities for eligible devices.

[0047] The platform calls the callback function `add` to register the entity list with the smart home platform. After registration, the platform automatically manages the entity's lifecycle, status updates, and interface display. If no entities are ultimately found, a warning log is logged, and the user is prompted to manually refresh the cache through the service.

[0048] 4. State synchronization mechanism The system periodically retrieves the latest status of all devices through the status polling interface / app / oauth / api / v2 / user / query / devices / group / state.do. The polling frequency can be configured according to the platform specifications, typically striking a balance between ensuring real-time performance and avoiding excessive requests.

[0049] Each device entity is associated with a coordinator instance, which is responsible for: Maintain the latest status data of the equipment; When the status data is updated, the corresponding entity is notified to refresh the interface display; Provides a data access interface for entities to query their current status.

[0050] Once the coordinator receives new status data from the polling interface, it parses the fields (such as powerState for on / off status, brightness for brightness value, and temperature for color temperature value) and updates the status cache in memory. Subsequently, the coordinator triggers the corresponding entity's status update event, and the HA front-end interface refreshes to display the latest status.

[0051] The coordinator in this invention inherits from the base class (DataUpdateCoordinator) of the smart home platform, and its specific implementation is as follows: (a) Initialization logic When the coordinator is created, it first retrieves the configured value for the polling interval. The system supports two configuration methods: you can directly pass in a numerical value or specify it by parameter name. If the user does not configure the polling interval, or the configured value is invalid, the system automatically uses the preset default value (e.g., 5 seconds).

[0052] The coordinator then calls the parent class's constructor, passing the polling interval as a time interval object. Upon receiving this, the parent class starts a background scheduled task that repeatedly performs the data retrieval operation at the set time intervals.

[0053] Finally, the coordinator stores two key pieces of information: API client: Used for subsequent communication with the cloud. Device Identifier: Used to indicate which device's status is being queried (the group identifier mentioned later is actually the device identifier for a group of devices). (ii) Data update method The coordinator overrides the parent class's `_async_update_data` method, which is automatically called on each polling cycle. Internally, the method performs the following operations: Call the async_group_state method of the API client, pass in the group identifier, and send a status query request to the cloud (using the previously saved API client and device identifier to send a status query request to the cloud). The system sends a POST request to the cloud status query interface / app / oauth / api / v2 / user / query / devices / group / state.do. The request body is in JSON format, contains a list of group identifiers, and has an 8-second timeout limit.

[0054] If the request is successful, a dictionary containing status fields is returned (e.g., {"powerState": "ON", "brightness": "80"}). If a ClientError exception (such as a network error, timeout, or HTTP error) is caught, an UpdateFailed exception is thrown.

[0055] (III) Response parsing and field extraction When the request succeeds, the system performs the following parsing steps: 1. Analyze the response structure Receive a JSON response, retrieve the data array from the root response object, take the first element, and extract the properties array.

[0056] 2. Traverse the attribute array Iterate through each element in the properties array, where each element contains a key and a value field.

[0057] 3. Field Mapping Extract the corresponding status based on the key value: key=powerState → Switch status (ON / OFF) key=brightness → Brightness value (0-100) key = temperature → Color temperature value (Kelvin) 4. Construct a state dictionary The extracted fields are assembled into a state dictionary. (iv) Caching and Notification After a successful return of `_async_update_data`, the parent class `DataUpdateCoordinator` automatically stores the returned status dictionary in the `self.data` property. If an `UpdateFailed` exception is thrown, the previously successfully retrieved data is retained. Regardless of success or failure, the parent class will call the `async_update_listeners` method after the update is complete to notify all associated device entities that "data has been updated." The entities then retrieve the latest status by reading `self.coordinator.data` and refresh the interface.

[0058] (v) Active refresh When a user sends a control command through this system, the entity calls the coordinator's async_request_refresh method, forcing the coordinator to immediately perform a data update without waiting for the next polling cycle, ensuring rapid synchronization between the interface state and the actual device state.

[0059] 5. Control command processing flow When a user operates a Lipro light fixture on the HA interface (such as clicking a switch or dragging a brightness bar), the system performs the following steps: Step 1: Command Reception The entity object's control methods (such as async_turn_on) are called, passing in platform-standard control parameters.

[0060] Step 2: Parameter Analysis The system parses the passed parameters, for example: If ATTR_BRIGHTNESS is included, extract the brightness value (HA standard is 0-255). If ATTR_COLOR_TEMP_KELVIN is included, extract the color temperature value (in Kelvin).

[0061] Step 3: Protocol Conversion The system converts the platform's standard control parameters into a format recognizable by the Lipro cloud platform: Switch command: Converted to POWER_ON or POWER_OFF command; Brightness command: Map the HA brightness value (0-255) back to the device brightness value (0-100); Color temperature command: Directly transmit the color temperature value, or map it according to the range supported by the device.

[0062] Specifically: 1. Determine the cloud command word based on the called entity method: When the async_turn_on method is called, the command word is converted to "POWER_ON"; When the `async_turn_off` method is called, the command word is converted to "POWER_OFF". The two methods, async_turn_on and async_turn_off, are standard interface methods defined by the Home Assistant platform.

[0063] 2. If the control command includes brightness parameters, the system performs the following conversion: Extract the platform's standard brightness value, which ranges from 0 to 255. The device brightness value is converted into a 0-100 range that the device can recognize by using the linear transformation formula: device brightness value = floor (platform brightness value × 100 / 255). Use the boundary clipping function max(0, min(100, ...)) to ensure the result is within the valid range; Convert the integer value to a string format and store it in the brightness field of the attribute dictionary.

[0064] 3. If the control command includes a color temperature parameter, the system performs the following operations: Extract the platform's standard color temperature value, in Kelvin; Convert directly to string format without range conversion; Store it in the temperature field of the attribute dictionary.

[0065] The system encapsulates all control parameters into a list of key-value pairs and sends them to the Lipro cloud via the control interface / app / oauth / api / v2 / user / control / device / group / command.do.

[0066] Step 4: Command Execution and Feedback After receiving the instruction, the cloud forwards the command to the actual device for execution. Once the device has completed the execution, the cloud returns the result.

[0067] Step 5: Status Refresh After the command is successfully sent, the system immediately calls the coordinator's refresh method to actively obtain the latest status of the device and ensure that the interface display is consistent with the actual status.

[0068] data: The recovery time and configuration error rate of the traditional solution and the solution of this invention were tested under three network environments: ideal local area network, 4G / 5G mobile network, and weak network / high latency; as shown in Tables 1-3. The "traditional solution" refers to the common processing method in existing technologies, which is to delete the device entity after the token expires, and the user needs to re-add the integration, then the system rediscovers the device, and then reconfigure the automation rules. The solution of this invention retains the device entity when the token expires, only disables the control function, and automatically restores the control after the user re-authenticates, retaining all configuration information and avoiding repeated configuration by the user. Table 1 Key network parameters for three network environments

[0069] Table 2 Simulation data of recovery time

[0070] Explanation of recovery time composition: Traditional solution: User operations (deleting integrations, re-adding, configuring automation, etc.) take approximately 11-17 seconds + API calls and platform processing take approximately 2-3 seconds. The solution of this invention: User operation (re-clicking for authentication) takes approximately 3-5 seconds + token refresh API takes approximately 1-3 seconds + platform processing takes approximately 0.2 seconds. Configuration error occurrence rate simulation data Error type definition: Token refresh failed: The refresh request returned an error (such as network timeout or server error). Device discovery failed: Device list query failed or parsing error. Entity creation failed: An error was detected when registering the entity to the platform. Automated configuration creation failure: Error rate comparison of user reconfiguration errors or rule saving failures: Table 3 Simulated data on configuration error occurrence rate

[0071] The simulation data above shows that the present invention can significantly shorten recovery time and reduce configuration error rate under different network conditions, especially in weak network environments, which verifies the effectiveness of the degradation processing mechanism of the present invention.

[0072] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.

Claims

1. A third-party smart home device integration system based on Home Assistant, characterized in that, include: The authentication and authorization module is used to guide users to complete the authorization of the third-party cloud platform based on the OAuth 2.0 protocol, obtain and securely store access tokens and refresh tokens, and automatically use the refresh token to refresh when the access token expires, and enter the degradation mode when the refresh fails. The degradation mode includes: maintaining the interface visibility of the created device entity, while disabling the control function of the device entity. The device discovery and registration module is used to call the device list query interface of the third-party cloud platform after obtaining a valid access token, parse the returned device information, and create the corresponding device entity in the Home Assistant platform based on the parsing results. The status synchronization module is used to obtain the latest status data of all devices by periodically calling the status query interface of the third-party cloud platform, and maintain a coordinator instance for each device entity. The coordinator instance is used to cache the status data of the corresponding device and trigger the corresponding device entity to refresh the interface display when the status data is updated. The command conversion and control module is used to receive standard control commands issued by the Home Assistant platform, parse the control parameters in the commands, convert the standard control commands and parameters into private protocol commands that can be recognized by the third-party cloud platform, send them to the cloud by calling the control interface of the third-party cloud platform, and trigger the status synchronization module to refresh the device status after the command is sent.

2. The system according to claim 1, characterized in that, The authentication and authorization module includes: The authorization guidance unit is used to generate the URL of the OAuth 2.0 authorization page of the third-party cloud platform, guiding users to access and authorize it; The credential management unit is used to obtain the authorization code via the callback URL and exchange the authorization code for an access token and a refresh token. The token storage unit is used to securely store access tokens, refresh tokens, and their expiration dates. Token refresh unit: Used to automatically request a new access token from a third-party cloud platform and update the token storage unit when the access token is about to expire or has already expired; Degradation processing unit: used to mark the authentication status as requiring re-authentication and enter the degradation mode when the token refresh unit fails to refresh.

3. The system according to claim 1, characterized in that, The device discovery and registration module includes: The device list acquisition unit is used to call the device list query interface of a third-party cloud platform using a valid access token to obtain device list data under the user account. The device information parsing unit is used to parse the device list data and extract the device unique identifier, device name, device model, online status and device capability set information from each device; The entity creation unit is used to create a device entity that conforms to the platform entity specification for each device in the Home Assistant platform based on the information extracted by the device information parsing unit.

4. The system according to claim 1, characterized in that, The state synchronization module includes: The status polling unit is used to periodically call the status query interface of the third-party cloud platform according to a preset polling frequency to obtain real-time status data of all devices; The coordinator unit maintains an independent coordinator instance for each device entity. The coordinator instance is used to store the latest status data of the corresponding device and, when the status polling unit obtains updated status data, notifies the corresponding device entity to refresh the interface display.

5. The system according to claim 1, characterized in that, The instruction conversion and control module includes: The instruction receiving unit is used to listen for and receive service call instructions for device entities issued by the Home Assistant platform; The parameter parsing unit is used to parse the control parameters contained in the service call command; The protocol conversion unit is used to convert service call instructions and control parameters into control commands in the private protocol format of a third-party cloud platform. The conversion includes mapping the standard parameter range of the Home Assistant platform to the parameter range required by the third-party cloud platform. The command sending unit is used to send the converted control commands to the cloud through the control interface of a third-party cloud platform. The status feedback unit is used to trigger the status synchronization module to refresh the status of the corresponding device after the instruction sending unit sends the control command, so as to display the control execution result on the interface.

6. The system according to claim 5, characterized in that, The protocol conversion unit also supports encapsulating multiple control parameters into a list of key-value pairs, which can be sent to the cloud through a single control interface call to achieve batch parameter control.

7. The system according to claim 1, characterized in that, Also includes: The platform adaptation and compatibility module inherits the standard device abstract class of the Home Assistant platform, implements the attribute interfaces and method interfaces required by the platform, and provides format conversion, field mapping and unit conversion functions between third-party cloud platform data and Home Assistant platform standard data.

8. A visual smart home integration method based on Home Assistant, applied to the system described in any one of claims 1-7, characterized in that, Includes the following steps: The authentication and authorization process guides users through the authorization process of the third-party cloud platform based on the OAuth 2.0 protocol, and obtains and securely stores access tokens and refresh tokens. When the access token expires, the refresh token is automatically used to refresh, and if the refresh fails, a fallback mode is entered. The fallback mode includes: maintaining the interface visibility of the created device entity while disabling the control functions of the device entity. The device discovery and registration process involves obtaining a valid access token, calling the device list query interface of the third-party cloud platform, parsing the returned device information, and creating the corresponding device entity in the Home Assistant platform based on the parsing results. The status synchronization step involves periodically calling the status query interface of a third-party cloud platform to obtain the latest status data of all devices, and maintaining a coordinator instance for each device entity. The coordinator instance is used to cache the status data of the corresponding device and trigger the corresponding device entity to refresh the interface display when the status data is updated. The command conversion and control steps involve receiving standard control commands from the Home Assistant platform, parsing the control parameters in the commands, converting the standard control commands and parameters into private protocol commands that can be recognized by the third-party cloud platform, sending them to the cloud by calling the control interface of the third-party cloud platform, and triggering a status synchronization step to refresh the device status after the commands are sent.

9. The method according to claim 8, characterized in that, The authentication and authorization steps specifically include: Generate the URL of the OAuth 2.0 authorization page for the third-party cloud platform, and guide the user to visit and authorize it; Obtain the authorization code via the callback URL, and then exchange the authorization code for an access token and a refresh token; Securely store the access token, refresh token, and their expiration dates; When the access token is about to expire or has expired, the refresh token is automatically used to request a new access token from the third-party cloud platform. When the refresh fails, the authentication status is marked as requiring re-authentication, and the system enters downgrade mode.

10. The method according to claim 8, characterized in that, In the instruction conversion and control steps, converting standard control instructions and parameters into private protocol instructions that can be recognized by the third-party cloud platform includes: mapping the standard parameter range of the Home Assistant platform to the parameter range required by the third-party cloud platform, and encapsulating multiple control parameters into a list of key-value pairs and sending them to the cloud through a single control interface call.