### Download and install from source Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/installation.md Downloads the source tarball and installs the package using setup.py. ```console $ curl -OJL https://github.com/gadgetmobile/blebox_uniapi/tarball/master ``` ```console $ python setup.py install ``` -------------------------------- ### Install via pip Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/installation.md Installs the most recent stable release of the library. ```console $ pip install blebox_uniapi ``` -------------------------------- ### Set up local development environment Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Commands to set up a virtual environment and install the project locally for development. Assumes virtualenvwrapper is installed. ```shell mkvirtualenv blebox_uniapi cd blebox_uniapi/ python setup.py develop ``` -------------------------------- ### Create API Session with ApiHost Source: https://context7.com/blebox/blebox_uniapi/llms.txt Establishes an asynchronous HTTP session with a BleBox device using ApiHost. Includes examples for GET and POST requests. Requires `aiohttp` and `blebox_uniapi.session`. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost async def create_session(): # Create an aiohttp session with custom timeout timeout = aioiohttp.ClientTimeout(total=None, sock_connect=5, sock_read=5) session = aiohttp.ClientSession(timeout=timeout) # Create ApiHost for a device at 192.168.1.100 api_host = ApiHost( host="192.168.1.100", port=80, timeout=timeout, session=session, loop=None, # Optional event loop username="admin", # Optional basic auth password="secret" # Optional basic auth ) # Make direct API calls device_state = await api_host.async_api_get("/api/device/state") print(f"Device info: {device_state}") # POST request example response = await api_host.async_api_post( "/api/rgbw/set", '{"rgbw":{"desiredColor": "ff000000"}}' ) return api_host # Run the async function asyncio.run(create_session()) ``` -------------------------------- ### Set up local development environment Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Commands to create a virtual environment and install the package in development mode. ```shell $ mkvirtualenv blebox_uniapi $ cd blebox_uniapi/ $ python setup.py develop ``` -------------------------------- ### GET /api/device/state Source: https://context7.com/blebox/blebox_uniapi/llms.txt Retrieves the current state information of the BleBox device. ```APIDOC ## GET /api/device/state ### Description Retrieves the current state and configuration of the connected BleBox device. ### Method GET ### Endpoint /api/device/state ### Response #### Success Response (200) - **device_state** (object) - The JSON object containing the device's current state and metadata. ``` -------------------------------- ### Update box_types for MultiSensor Configuration Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/howtoaddsensor.md Modify the box_types module in the blebox_uniapi library to include configuration for the MultiSensor, specifying API paths and sensor mappings for illuminance and other readings. This example uses an API level of 20220114. ```python "multiSensor": { 20220114: { "api_path": "/state", "extended_state_path": "/state/extended", "sensors": [ [ "multiSensor", { "illuminance": lambda x:f"multiSensor/sensors/[id={x}]/value", "temperature": lambda x: f"multiSensor/sensors/[id={x}]/value", "wind": lambda x: f"multiSensor/sensors/[id={x}]/value", "humidity": lambda x: f"multiSensor/sensors/[id={x}]/value", }, ] ], "binary_sensors": [ [ "multiSensor", { "rain": lambda x: f"multiSensor/sensors/[id={x}]/value", "flood": lambda x: f"multiSensor/sensors/[id={x}]/value", }, ] ], }, ``` -------------------------------- ### Control Lights with blebox_uniapi Source: https://context7.com/blebox/blebox_uniapi/llms.txt Demonstrates how to connect to a light-capable device, inspect its capabilities, and send commands for color and brightness. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box async def control_light(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) lights = box.features.get("lights", []) for light in lights: await light.async_update() print(f"Light: {light.full_name}") print(f" Is On: {light.is_on}") print(f" Color Mode: {light.color_mode}") print(f" Supports Color: {light.supports_color}") print(f" Supports White: {light.supports_white}") print(f" Brightness: {light.brightness}") print(f" RGB Hex: {light.rgb_hex}") # Turn on with RGBW value (red with white) # Format: RRGGBBWW (hex values 00-FF for each channel) await light.async_on("ff000080") # Red + 50% white # For dimmerBox (brightness only 0-255) # await light.async_on(128) # 50% brightness # Turn on with RGB list [R, G, B, W] await light.async_on([255, 128, 0, 64]) # Orange with white # Turn off await light.async_off() # Access effect list if supported if light.effect_list: print(f" Available effects: {light.effect_list}") print(f" Current effect: {light.effect}") asyncio.run(control_light()) ``` -------------------------------- ### Clone the repository Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Initial step to create a local copy of the project fork. ```shell $ git clone git@github.com:your_name_here/blebox_uniapi.git ``` -------------------------------- ### Deploy new version Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Commands for maintainers to bump the version and push tags for deployment. ```shell $ bump2version patch # possible: major / minor / patch $ git push $ git push --tags ``` -------------------------------- ### Control Climate Features Source: https://context7.com/blebox/blebox_uniapi/llms.txt Demonstrates how to control thermostat features like turning on/off, setting target temperatures, and monitoring heating/cooling states. Requires the 'climates' feature to be available on the box. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box async def control_climate(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) climates = box.features.get("climates", []) for climate in climates: await climate.async_update() print(f"Climate: {climate.full_name}") print(f" Is On: {climate.is_on}") print(f" Current Temp: {climate.current}C") print(f" Target Temp: {climate.desired}C") print(f" Min Temp: {climate.min_temp}C") print(f" Max Temp: {climate.max_temp}C") print(f" Is Heating: {climate.is_heating}") print(f" Is Cooling: {climate.is_cooling}") print(f" Mode: {climate.mode}") print(f" HVAC Action: {climate.hvac_action}") # Turn on the thermostat await climate.async_on() # Set target temperature (in Celsius) await climate.async_set_temperature(22.5) # Turn off await climate.async_off() asyncio.run(control_climate()) ``` -------------------------------- ### Create a development branch Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Command to switch to a new branch for local changes. ```shell $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Clone the blebox_uniapi repository Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Use this command to clone your forked repository locally. Replace 'your_name_here' with your GitHub username. ```shell git clone git@github.com:your_name_here/blebox_uniapi.git ``` -------------------------------- ### Run quality checks and tests Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Commands to verify code quality and run test suites. ```shell $ flake8 blebox_uniapi tests $ python setup.py test or pytest $ tox ``` -------------------------------- ### Control Switches with Switch Feature Source: https://context7.com/blebox/blebox_uniapi/llms.txt Demonstrates how to control relay switches using the `Switch` feature class. Allows turning switches on and off, and checking their current state. Requires `aiohttp`, `blebox_uniapi.session.ApiHost`, and `blebox_uniapi.box.Box`. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box async def control_switch(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) # Get switch features switches = box.features.get("switches", []) for switch in switches: # Update state from device await switch.async_update() print(f"Switch: {switch.full_name}") print(f" Current state: {'ON' if switch.is_on else 'OFF'}") print(f" Device class: {switch.device_class}") # Turn on the switch await switch.async_turn_on() print(" Turned ON") # Wait and turn off await asyncio.sleep(2) await switch.async_turn_off() print(" Turned OFF") asyncio.run(control_switch()) ``` -------------------------------- ### Read Sensor Data Source: https://context7.com/blebox/blebox_uniapi/llms.txt Shows how to read data from various sensor types including temperature, humidity, and air quality. Also demonstrates reading binary sensors for events like rain or flood detection. Ensure the box has the 'sensors' or 'binary_sensors' features. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box async def read_sensors(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) sensors = box.features.get("sensors", []) for sensor in sensors: await sensor.async_update() print(f"Sensor: {sensor.full_name}") print(f" Device Class: {sensor.device_class}") print(f" Value: {sensor.native_value} {sensor.unit}") print(f" Sensor ID: {sensor.sensor_id}") # Temperature sensor specific if sensor.device_class == "temperature": print(f" Current: {sensor.current}C") # Power consumption sensor specific if sensor.device_class == "powerConsumption": print(f" Last Reset: {sensor.last_reset}") # Binary sensors (rain, flood detection) binary_sensors = box.features.get("binary_sensors", []) for binary_sensor in binary_sensors: await binary_sensor.async_update() print(f"Binary Sensor: {binary_sensor.full_name}") print(f" State: {'Detected' if binary_sensor.state else 'Clear'}") print(f" Device Class: {binary_sensor.device_class}") asyncio.run(read_sensors()) ``` -------------------------------- ### Control Covers with blebox_uniapi Source: https://context7.com/blebox/blebox_uniapi/llms.txt Shows how to manage motorized covers, including position control, tilt adjustments, and state monitoring. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box from blebox_uniapi.cover import BleboxCoverState, UnifiedCoverType async def control_cover(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) covers = box.features.get("covers", []) for cover in covers: await cover.async_update() print(f"Cover: {cover.full_name}") print(f" Type: {cover.cover_type}") print(f" Position: {cover.current}%") print(f" State: {cover.state}") print(f" Is Slider: {cover.is_slider}") print(f" Has Tilt: {cover.has_tilt}") print(f" Has Stop: {cover.has_stop}") # Interpret state if cover.state == BleboxCoverState.MOVING_DOWN: print(" Status: Closing...") elif cover.state == BleboxCoverState.MOVING_UP: print(" Status: Opening...") elif cover.state == BleboxCoverState.LOWER_LIMIT_REACHED: print(" Status: Fully closed") elif cover.state == BleboxCoverState.UPPER_LIMIT_REACHED: print(" Status: Fully open") # Open the cover await cover.async_open() # Set specific position (0=closed, 100=open) if cover.is_slider: await cover.async_set_position(50) # 50% open # Stop movement if cover.has_stop: await cover.async_stop() # Close the cover await cover.async_close() # Control tilt (for shutters with tilt support) if cover.has_tilt: print(f" Tilt Position: {cover.tilt_current}%") await cover.async_set_tilt_position(45) # 45% tilt await cover.async_open_tilt() # Tilt to 0% await cover.async_close_tilt() # Tilt to 100% asyncio.run(control_cover()) ``` -------------------------------- ### Clone repository Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/installation.md Downloads the source code from the public GitHub repository. ```console $ git clone git://github.com/gadgetmobile/blebox_uniapi ``` -------------------------------- ### Handle BleBox API Errors Source: https://context7.com/blebox/blebox_uniapi/llms.txt Demonstrates how to catch specific exceptions during device initialization and control operations. Use this to manage connection timeouts, authentication failures, and device-specific response errors. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box from blebox_uniapi.error import ( Error, ConnectionError, TimeoutError, HttpError, UnauthorizedRequest, UnsupportedBoxResponse, UnsupportedBoxVersion, BadFieldMissing, DeviceStateNotAvailable, ) async def safe_device_control(): try: async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) try: box = await Box.async_from_host(api_host) except UnsupportedBoxVersion as e: print(f"Device firmware too old: {e}") return except UnsupportedBoxResponse as e: print(f"Unknown device type or malformed response: {e}") return switches = box.features.get("switches", []) for switch in switches: try: await switch.async_update() await switch.async_turn_on() except DeviceStateNotAvailable: print("Device state not yet fetched") except BadFieldMissing as e: print(f"Missing data in response: {e}") except TimeoutError as e: print(f"Connection timed out: {e}") except ConnectionError as e: print(f"Failed to connect: {e}") except UnauthorizedRequest as e: print(f"Authentication failed: {e}") except HttpError as e: print(f"HTTP error: {e}") except Error as e: print(f"BleBox API error: {e}") asyncio.run(safe_device_control()) ``` -------------------------------- ### Run tests and checks Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Commands to verify your changes by running linters (flake8) and tests. Includes running tests with tox for multiple Python versions. ```shell flake8 blebox_uniapi tests python setup.py test or pytest tox ``` -------------------------------- ### Create Illuminance Sensor Class Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/howtoaddsensor.md Define a new sensor class, Illuminance, inheriting from BaseSensor in the blebox_uniapi.sensor module. This class handles reading and formatting illuminance values, setting the unit to 'lx' and device class to 'illuminance'. ```python class Illuminance(BaseSensor): def __init__(self, product: "Box", alias: str, methods: dict): super().__init__(product, alias, methods) self._unit = "lx" self._device_class = "illuminance" def _read_illuminance(self): product = self._product if product.last_data is not None: raw = self.raw_value("illuminance") if raw is not None: alias = self._alias return round(product.expect_int(alias, raw, 100000, 0)/100.0, 1) return None ``` -------------------------------- ### Discover and Create Box Device Source: https://context7.com/blebox/blebox_uniapi/llms.txt Automatically detects a BleBox device type and creates a `Box` instance with all supported features. Requires `aiohttp`, `blebox_uniapi.session.ApiHost`, and `blebox_uniapi.box.Box`. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box async def discover_device(): async with aiohttp.ClientSession() as session: # Create API host api_host = ApiHost( host="192.168.1.100", port=80, timeout=aiohttp.ClientTimeout(sock_connect=5, sock_read=5), session=session, loop=None ) # Auto-discover and create Box instance box = await Box.async_from_host(api_host) # Access device information print(f"Device Name: {box.name}") print(f"Device Type: {box.type}") print(f"Unique ID: {box.unique_id}") print(f"Firmware: {box.firmware_version}") print(f"Hardware: {box.hardware_version}") print(f"API Version: {box.api_version}") print(f"Model: {box.model}") print(f"Brand: {box.brand}") # List all features for feature_type, features in box.features.items(): print(f"\n{feature_type}:") for feature in features: print(f" - {feature.full_name} (ID: {feature.unique_id})") return box asyncio.run(discover_device()) ``` -------------------------------- ### POST /api/rgbw/set Source: https://context7.com/blebox/blebox_uniapi/llms.txt Updates the color settings for an RGBW light device. ```APIDOC ## POST /api/rgbw/set ### Description Sets the desired color for an RGBW light device. ### Method POST ### Endpoint /api/rgbw/set ### Request Body - **rgbw** (object) - Required - Contains the desired color settings. - **desiredColor** (string) - Required - The hex color code to set. ``` -------------------------------- ### Commit and push changes Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Stage all changes, commit them with a descriptive message, and push the branch to your GitHub fork. ```shell git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Create a new branch for development Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Create a new branch for your bug fix or feature development. Replace 'name-of-your-bugfix-or-feature' with a descriptive branch name. ```shell git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Commit and push changes Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Standard git workflow to stage, commit, and push local changes to the remote repository. ```shell $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Deploy new version Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Commands for maintainers to deploy a new version of the package. This involves updating the version number, committing, and pushing to GitHub. ```shell bump2version patch # possible: major / minor / patch git push git push --tags ``` -------------------------------- ### Update SensorFactory Type Class Mapper Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/howtoaddsensor.md In the blebox_uniapi.sensor.SensorFactory class, update the type_class_mapper dictionary to include the new Illuminance sensor class. This ensures that the factory can correctly instantiate the Illuminance sensor when a device reports light-related measurements. ```python class SensorFactory: @classmethod def many_from_config( cls, product, box_type_config, extended_state ) -> list["BaseSensor"]: type_class_mapper = { "airSensor": AirQuality, "temperature": Temperature, "humidity": Humidity, "wind": Wind, "illuminance" : Illuminance } ``` -------------------------------- ### Update SENSOR_TYPES for Illuminance Sensor Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/howtoaddsensor.md Add a new SensorEntityDescription to the SENSOR_TYPES tuple in the Home Assistant Blebox sensor module to enable entities for light readings. Requires importing necessary classes from homeassistant.components.blebox.sensor and homeassistant.const. ```python from homeassistant.components.blebox.sensor import SensorEntityDescription, SensorDeviceClass from homeassistant.const import LIGHT_LUX SENSOR_TYPES = ( # ... (existing entries) SensorEntityDescription( key="illuminance", device_class=SensorDeviceClass.ILLUMINANCE, native_unit_of_measurement=LIGHT_LUX, ), ) ``` -------------------------------- ### Query Device Configuration Source: https://context7.com/blebox/blebox_uniapi/llms.txt Accesses the box_types module to inspect supported device features and API versions. Useful for determining capabilities before interacting with a specific device model. ```python from blebox_uniapi.box_types import ( get_conf_set, get_conf, get_latest_conf, get_latest_api_level, BOX_TYPE_CONF, ) # List all supported device types print("Supported device types:") for device_type in BOX_TYPE_CONF.keys(): print(f" - {device_type}") # Get configuration for a specific device type device_type = "switchBox" conf_set = get_conf_set(device_type) print(f"\n{device_type} API levels: {list(conf_set.keys())}") # Get latest configuration latest_conf = get_latest_conf(device_type) print(f"Latest API path: {latest_conf.get('api_path')}") print(f"Features: {[k for k in latest_conf.keys() if k not in ['api_path', 'api', 'extended_state_path', 'model']]}") # Get configuration for specific API level api_level = 20200831 conf = get_conf(api_level, conf_set) print(f"\nConfig for API level {api_level}:") print(f" API path: {conf.get('api_path')}") # Get latest supported API level latest_level = get_latest_api_level(device_type) print(f"Latest API level for {device_type}: {latest_level}") ``` -------------------------------- ### Run specific tests Source: https://github.com/blebox/blebox_uniapi/blob/master/CONTRIBUTING.rst Command to execute a subset of the test suite using pytest. ```shell $ pytest tests.test_blebox_uniapi ``` -------------------------------- ### Run a subset of tests with pytest Source: https://github.com/blebox/blebox_uniapi/blob/master/docs/contributing.md Execute a specific test module using pytest to quickly check targeted functionality. ```shell pytest tests.test_blebox_uniapi ``` -------------------------------- ### Control TV Lift Buttons Source: https://context7.com/blebox/blebox_uniapi/llms.txt Provides control for TV lift devices using the Button feature. It checks the control type (UP, DOWN, OPEN, CLOSE, FAVORITE) and executes the corresponding action. Ensure the box has the 'buttons' feature. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box from blebox_uniapi.button import ControlType async def control_tv_lift(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) buttons = box.features.get("buttons", []) for button in buttons: print(f"Button: {button.full_name}") print(f" Control Type: {button.control_type}") print(f" Query String: {button.query_string}") # Check control type and execute if button.control_type == ControlType.UP: print(" Action: Move Up") elif button.control_type == ControlType.DOWN: print(" Action: Move Down") elif button.control_type == ControlType.OPEN: print(" Action: Open") elif button.control_type == ControlType.CLOSE: print(" Action: Close") elif button.control_type == ControlType.FAVORITE: print(" Action: Go to Favorite Position") # Execute button press await button.set() asyncio.run(control_tv_lift()) ``` -------------------------------- ### Poll Device State Source: https://context7.com/blebox/blebox_uniapi/llms.txt Implements a polling loop to keep device features updated. The Box class automatically handles caching to minimize redundant API requests. ```python import aiohttp import asyncio from blebox_uniapi.session import ApiHost from blebox_uniapi.box import Box async def poll_device_state(): async with aiohttp.ClientSession() as session: api_host = ApiHost("192.168.1.100", 80, None, session, None) box = await Box.async_from_host(api_host) # Get all feature types all_features = [] for feature_type, features in box.features.items(): all_features.extend(features) # Poll loop while True: # Update box data (fetches from device API) await box.async_update_data() # All features automatically get updated state for feature in all_features: # Feature state is now current print(f"{feature.full_name}: Updated") # Access raw device data print(f"Raw data: {box.last_data}") await asyncio.sleep(10) # Poll every 10 seconds # asyncio.run(poll_device_state()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.