### Install MerossIot from Source Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/installation.rst These commands clone the repository from GitHub, install the required dependencies, and install the library locally. This is useful for users who want to work with the latest development code. ```bash git clone https://github.com/albertogeniola/MerossIot.git cd MerossIot pip install -r requirements.txt pip install . ``` -------------------------------- ### Install Meross IoT Library Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/README.md Command to install the latest version of the Meross IoT library from the Python Package Index (PyPI). ```bash pip install meross_iot==0.4.10.4 ``` -------------------------------- ### Control Meross Smart Plugs with Python Source: https://context7.com/albertogeniola/merossiot/llms.txt Provides an example of controlling Meross smart plugs (like MSS310) using the `ToggleXMixin` interface. It demonstrates how to turn devices on, turn them off, toggle their current state, and handle multi-channel devices such as power strips. Requires Meross cloud credentials. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() # Find MSS310 smart plugs plugs = manager.find_devices(device_type="mss310") if len(plugs) < 1: print("No MSS310 plugs found...") else: dev = plugs[0] # Always call async_update() first to get current device status await dev.async_update() # Check current state is_on = dev.is_on(channel=0) print(f"Device {dev.name} is currently {'ON' if is_on else 'OFF'}") # Turn on the device (channel=0 is default for single-channel devices) print(f"Turning on {dev.name}...") await dev.async_turn_on(channel=0) # Wait a bit await asyncio.sleep(5) # Turn off the device print(f"Turning off {dev.name}...") await dev.async_turn_off(channel=0) # Toggle the current state print(f"Toggling {dev.name}...") await dev.async_toggle(channel=0) # For power strips (MSS425E), control individual outlets # await dev.async_turn_on(channel=1) # Second outlet # await dev.async_turn_on(channel=2) # Third outlet manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Handle Meross Push Notifications with Python Source: https://context7.com/albertogeniola/merossiot/llms.txt This Python snippet shows the setup for handling real-time push notifications from Meross devices. It imports necessary modules for HTTP API client and manager, and the GenericPushNotification model. This code is intended as a starting point for registering notification handlers. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager from meross_iot.model.push.generic import GenericPushNotification EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" ``` -------------------------------- ### Install MerossIot via pip Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/installation.rst This command installs the latest version of the MerossIot library from the Python Package Index. It ensures the library is upgraded to the most recent release. ```bash pip install meross-iot --upgrade ``` -------------------------------- ### Meross Device Listing Request Source: https://github.com/albertogeniola/merossiot/wiki/HTTP-APIs Example of a request to list all devices associated with the user account. This requires the access token obtained during the login process. ```http POST /v1/Device/devList HTTP/1.1 Host: iot.meross.com Authorization: Basic Content-Type: application/json vender: Meross AppVersion: 1.3.0 AppLanguage: EN User-Agent: okhttp/3.6.0 {"params": "e30=", "sign": "", "timestamp": 0, "nonce": ""} ``` -------------------------------- ### POST /config - Get Device Information Source: https://github.com/albertogeniola/merossiot/wiki/Device-pairing Retrieves comprehensive system, hardware, and firmware information from a Meross device during the local configuration phase. ```APIDOC ## POST /config ### Description Retrieves the device's system state, including hardware details, firmware version, and current control status. ### Method POST ### Endpoint http://10.10.10.1/config ### Request Body - **header** (object) - Required - Contains protocol metadata (namespace: Appliance.System.All, method: GET). - **payload** (object) - Required - Empty object for this request. ### Request Example { "header": { "from": "", "messageId": "", "method": "GET", "namespace": "Appliance.System.All", "payloadVersion": 0, "sign": "", "timestamp": 0 }, "payload": {} } ### Response #### Success Response (200) - **header** (object) - Response metadata including method GETACK. - **payload** (object) - Contains 'all' object with system, hardware, firmware, and control details. #### Response Example { "header": { "messageId": "", "namespace": "Appliance.System.All", "method": "GETACK", "payloadVersion": 1, "from": "/appliance/XXXXXXXXXXXXXXXXXXXXXXXXXXXX/publish", "timestamp": 585 }, "payload": { "all": { "system": { "hardware": { "type": "mss310", "uuid": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX" }, "firmware": { "version": "1.1.15" } } } } } ``` -------------------------------- ### Configure Meross IoT Logging Level (Python) Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/advanced-topics.rst Configures the logging verbosity for the `meross_iot` library by setting the level of the root logger. This example sets the level to WARNING, filtering out DEBUG and INFO messages. ```python import logging meross_root_logger = logging.getLogger("meross_iot") meross_root_logger.setLevel(logging.WARNING) ``` -------------------------------- ### Meross Login Request Source: https://github.com/albertogeniola/merossiot/wiki/HTTP-APIs Example of a login request to the Meross API. It demonstrates the payload structure and the required HTTP headers to exchange credentials for access tokens. ```http POST /v1/Auth/Login HTTP/1.1 Host: iot.meross.com Authorization: Basic Content-Type: application/json vender: Meross AppVersion: 1.3.0 AppLanguage: EN User-Agent: okhttp/3.6.0 {"params": "eyJlbWFpbCI6ICJtZUBnb29nbGUuY29tIiwgInBhc3N3b3JkIjogInJvb3QifQ==", "sign": "E9BE76EAA17E837B81D6BCA558028A23", "timestamp": 0, "nonce": "0123456789ABCDEF"} ``` -------------------------------- ### POST /config - Setting up wifi credentials Source: https://github.com/albertogeniola/merossiot/wiki/Device-pairing Configures the device with local Wi-Fi network credentials (SSID and password) for internet connectivity. ```APIDOC ## POST /config - Setting up wifi credentials ### Description This endpoint configures the Meross device with the credentials for the local Wi-Fi network. It requires the SSID, password, and BSSID of the network, along with other Wi-Fi parameters. ### Method POST ### Endpoint /config ### Parameters #### Request Body - **header** (object) - Required - Header information for the request. - **from** (string) - Required - Sender identifier. - **messageId** (string) - Required - Unique message identifier. - **method** (string) - Required - The method being called (e.g., "SET"). - **namespace** (string) - Required - The namespace for the Wi-Fi configuration (e.g., "Appliance.Config.Wifi"). - **payloadVersion** (integer) - Required - Version of the payload. - **sign** (string) - Required - Signature for the request. - **timestamp** (integer) - Required - Timestamp of the request. - **payload** (object) - Required - Payload containing the Wi-Fi configuration details. - **wifi** (object) - Required - Wi-Fi network configuration. - **bssid** (string) - Required - The BSSID (MAC address) of the Wi-Fi access point. - **channel** (integer) - Required - The Wi-Fi channel the network is using. - **cipher** (integer) - Required - The cipher type used for encryption. - **encryption** (integer) - Required - The encryption method used (e.g., WPA2). - **password** (string) - Required - The Wi-Fi password (Base64 encoded). - **ssid** (string) - Required - The SSID (network name) of the Wi-Fi network (Base64 encoded). ### Request Example ```json { "header": { "from": "", "messageId": "", "method": "SET", "namespace": "Appliance.Config.Wifi", "payloadVersion": 0, "sign": "", "timestamp": 0 }, "payload": { "wifi": { "bssid": "XX-XX-XX-XX-XX-XX", "channel": 6, "cipher": 3, "encryption": 6, "password": "XXBASE64PASSXX", "ssid": "XXBASE64SSIDXX" } } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "header": { "messageId": "", "namespace": "Appliance.Config.Wifi", "method": "SET", "timestamp": 0, "from": "", "payloadVersion": 0 }, "payload": { "wifi": { "message": "success" } } } ``` ``` -------------------------------- ### MerossManager Initialization and Device Discovery (Python) Source: https://context7.com/albertogeniola/merossiot/llms.txt Illustrates the initialization of the MerossManager, the central class for managing Meross devices. This snippet shows how to set up the manager with an authenticated HTTP client, configure automatic reconnection and discovery, and then discover and list all connected devices. It also covers the necessary cleanup steps. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): # Setup the HTTP client API from user-password http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) # Initialize the MerossManager with optional parameters manager = MerossManager( http_client=http_api_client, auto_reconnect=True, # Automatically reconnect on connection drop auto_discovery_on_connection=True, # Discover devices after connecting # Optional: override MQTT server # mqtt_override_server=("custom-mqtt.example.com", 443) ) # Initialize the manager (required before use) await manager.async_init() # Discover all devices registered to the account discovered_devices = await manager.async_device_discovery() print(f"Discovered {len(discovered_devices)} devices") # List all discovered devices all_devices = manager.find_devices() for dev in all_devices: print(f"- {dev.name} ({dev.type}): {dev.uuid}") print(f" Online: {dev.online_status}") # Clean up: close manager and logout manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Save and Load Meross Device Registry (Python) Source: https://context7.com/albertogeniola/merossiot/llms.txt This script demonstrates how to discover Meross devices, save their registry to a file, and then load the registry in a subsequent session without re-discovery. It utilizes the meross_iot library, asyncio, and os. It requires valid Meross cloud credentials. The loaded registry might contain stale information. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" DUMP_FILE = "meross_devices.json" async def main(): # First session: discover and dump http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager(http_client=http_api_client) await manager.async_init() # Discover all devices await manager.async_device_discovery() devices = manager.find_devices() print(f"Discovered {len(devices)} devices:") for dev in devices: print(f" - {dev.name} ({dev.type}): {dev.uuid}") # Save device registry to file manager.dump_device_registry(DUMP_FILE) print(f"\nRegistry saved to {DUMP_FILE}") manager.close() await http_api_client.async_logout() # Second session: load from dump without discovery print("\n--- Starting new session ---") http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager( http_client=http_api_client, auto_discovery_on_connection=False # Disable auto-discovery ) await manager.async_init() # Load devices from dump file (no network call needed) manager.load_devices_from_dump(DUMP_FILE) print(f"Registry loaded from {DUMP_FILE}") # Verify loaded devices devices = manager.find_devices() print(f"Loaded {len(devices)} devices:") for dev in devices: print(f" - {dev.name} ({dev.type}): {dev.uuid}") # Note: Device info from dump may be stale (online status, names, etc.) # Use async_device_discovery() for fresh data when needed manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### GET /device/electricity Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/api-reference/controller/mixins/electricity.rst Retrieves the current electricity consumption metrics from a Meross device that supports the ElectricityMixin. ```APIDOC ## GET /device/electricity ### Description Fetches real-time power consumption data including current, voltage, and power usage from the device. ### Method GET ### Endpoint /device/electricity ### Parameters #### Query Parameters - **uuid** (string) - Required - The unique identifier of the Meross device. ### Request Example GET /device/electricity?uuid=1234567890abcdef ### Response #### Success Response (200) - **current** (int) - Current in milliamperes (mA) - **voltage** (int) - Voltage in millivolts (mV) - **power** (int) - Power in milliwatts (mW) #### Response Example { "current": 150, "voltage": 230000, "power": 34500 } ``` -------------------------------- ### POST /config - Setting up user/remote endpoint Source: https://github.com/albertogeniola/merossiot/wiki/Device-pairing Configures the device with MQTT broker connection details, including user ID and password for authentication. ```APIDOC ## POST /config - Setting up user/remote endpoint ### Description This endpoint configures the Meross device with the necessary credentials to connect to the remote MQTT broker. It specifies the MQTT host, port, user ID, and a unique key for authentication. ### Method POST ### Endpoint /config ### Parameters #### Request Body - **header** (object) - Required - Header information for the request. - **from** (string) - Required - Sender identifier. - **messageId** (string) - Required - Unique message identifier. - **method** (string) - Required - The method being called (e.g., "SET"). - **namespace** (string) - Required - The namespace for the configuration key (e.g., "Appliance.Config.Key"). - **payloadVersion** (integer) - Required - Version of the payload. - **sign** (string) - Required - Signature for the request. - **timestamp** (integer) - Required - Timestamp of the request. - **payload** (object) - Required - Payload containing the configuration details. - **key** (object) - Required - Key configuration for the device. - **gateway** (object) - Required - MQTT gateway details. - **host** (string) - Required - Primary MQTT broker host. - **port** (integer) - Required - Primary MQTT broker port. - **secondHost** (string) - Optional - Secondary MQTT broker host. - **secondPort** (integer) - Optional - Secondary MQTT broker port. - **key** (string) - Required - Authentication key for the MQTT broker. - **userId** (string) - Required - User ID for MQTT broker authentication. ### Request Example ```json { "header": { "from": "", "messageId": "", "method": "SET", "namespace": "Appliance.Config.Key", "payloadVersion": 1, "sign": "", "timestamp": 0 }, "payload": { "key": { "gateway": { "host": "iot.meross.com", "port": 2001, "secondHost": "smart.meross.com", "secondPort": 2001 }, "key": "XXXX", "userId": "XXX" } } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "header": { "messageId": "", "namespace": "Appliance.Config.Key", "method": "SET", "timestamp": 0, "from": "", "payloadVersion": 1 }, "payload": { "key": { "message": "success" } } } ``` ``` -------------------------------- ### Monitor Power Consumption with Python Source: https://context7.com/albertogeniola/merossiot/llms.txt Demonstrates how to discover devices supporting the ElectricityMixin, retrieve real-time power metrics like voltage and current, and monitor consumption over time. It requires valid Meross cloud credentials and an electricity-capable device. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager from meross_iot.controller.mixins.electricity import ElectricityMixin EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() power_devices = manager.find_devices(device_class=ElectricityMixin) if len(power_devices) < 1: print("No electricity-capable devices found...") else: dev = power_devices[0] await dev.async_update() metrics = await dev.async_get_instant_metrics(channel=0) print(f"Device: {dev.name}") print(f"Power: {metrics.power_watts} W") print(f"Voltage: {metrics.voltage_volts} V") print(f"Current: {metrics.current_ampere} A") manager.close() await http_api_client.async_logout() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` -------------------------------- ### Discover and Filter Meross Devices with Python Source: https://context7.com/albertogeniola/merossiot/llms.txt Demonstrates how to use the `find_devices()` method to discover Meross devices. It covers filtering by device type, online status, device class (mixins like ElectricityMixin, ToggleXMixin, LightMixin), device name, UUID, and combining multiple filters for precise device selection. Requires Meross cloud credentials. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager from meross_iot.model.enums import OnlineStatus from meross_iot.controller.mixins.electricity import ElectricityMixin from meross_iot.controller.mixins.toggle import ToggleXMixin from meross_iot.controller.mixins.light import LightMixin EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() # Filter by device type (case sensitive) mss310_plugs = manager.find_devices(device_type="mss310") print(f"Found {len(mss310_plugs)} MSS310 smart plugs") # Filter by online status online_devices = manager.find_devices(online_status=OnlineStatus.ONLINE) print(f"Found {len(online_devices)} online devices") # Filter by device class/mixin (devices with electricity monitoring) electricity_devices = manager.find_devices(device_class=ElectricityMixin) print(f"Found {len(electricity_devices)} devices with power monitoring") # Filter by multiple device classes (devices with toggle OR light capability) toggle_or_light = manager.find_devices(device_class=[ToggleXMixin, LightMixin]) print(f"Found {len(toggle_or_light)} devices with toggle or light control") # Filter by device name living_room = manager.find_devices(device_name="Living Room Plug") # Filter by UUID specific_device = manager.find_devices(device_uuids=["device-uuid-here"]) # Combine multiple filters (logical AND) online_plugs = manager.find_devices( device_type="mss310", online_status=OnlineStatus.ONLINE ) print(f"Found {len(online_plugs)} online MSS310 plugs") manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Read Meross MS100 Temperature and Humidity Sensor Data Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/quick-start.rst This Python snippet demonstrates how to read current temperature and humidity data from a Meross MS100 sensor. It utilizes the specific methods provided by the Ms100Sensor class for data retrieval. Ensure the 'meross_iot' library is installed. ```python from meross_iot.controller.subdevice import Ms100Sensor async def read_sensor_data(sensor: Ms100Sensor): """Reads and prints temperature and humidity from the sensor.""" await sensor.async_update() print(f"Temperature: {sensor.native_temperature} °C") print(f"Humidity: {sensor.native_humidity} %") ``` -------------------------------- ### MerossManager Initialization Source: https://context7.com/albertogeniola/merossiot/llms.txt This section explains how to initialize and use the `MerossManager` class, which is the central component for managing Meross devices. It covers setting up the HTTP client, initializing the manager with auto-reconnect and discovery options, discovering devices, and cleaning up resources. ```APIDOC ## MerossManager Initialization ### Description This section explains how to initialize and use the `MerossManager` class, which is the central component for managing Meross devices. It covers setting up the HTTP client, initializing the manager with auto-reconnect and discovery options, discovering devices, and cleaning up resources. ### Method POST (Implicit via `async_from_user_password` for HTTP client) ### Endpoint `https://iotx-eu.meross.com` (or other regional URLs for HTTP client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Credentials are passed as arguments to `MerossHttpClient`) ### Request Example ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): # Setup the HTTP client API from user-password http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) # Initialize the MerossManager with optional parameters manager = MerossManager( http_client=http_api_client, auto_reconnect=True, # Automatically reconnect on connection drop auto_discovery_on_connection=True, # Discover devices after connecting # Optional: override MQTT server # mqtt_override_server=("custom-mqtt.example.com", 443) ) # Initialize the manager (required before use) await manager.async_init() # Discover all devices registered to the account discovered_devices = await manager.async_device_discovery() print(f"Discovered {len(discovered_devices)} devices") # List all discovered devices all_devices = manager.find_devices() for dev in all_devices: print(f"- {dev.name} ({dev.type}): {dev.uuid}") print(f" Online: {dev.online_status}") # Clean up: close manager and logout manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` ### Response #### Success Response (200) - **manager** (object) - An initialized `MerossManager` instance. - **discovered_devices** (list) - A list of discovered device objects. #### Response Example ```json { "message": "Manager initialized and devices discovered successfully.", "discovered_devices_count": 5, "devices": [ { "name": "Living Room Plug", "type": "mss210", "uuid": "abcdef1234567890", "online_status": true } ] } ``` ``` -------------------------------- ### Control RGB Smart Bulbs with Meross IoT Source: https://context7.com/albertogeniola/merossiot/llms.txt This script initializes a Meross manager, discovers online MSL120 bulbs, and demonstrates how to programmatically adjust their color, brightness, and temperature settings. It requires valid Meross cloud credentials and handles asynchronous device communication. ```python import asyncio import os from random import randint from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager from meross_iot.model.enums import OnlineStatus EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() bulbs = manager.find_devices(device_type="msl120", online_status=OnlineStatus.ONLINE) if len(bulbs) < 1: print("No online MSL120 smart bulbs found...") else: dev = bulbs[0] await dev.async_update() supports_rgb = dev.get_supports_rgb() supports_luminance = dev.get_supports_luminance() supports_temperature = dev.get_supports_temperature() if supports_rgb: new_rgb = (randint(0, 255), randint(0, 255), randint(0, 255)) await dev.async_set_light_color(rgb=new_rgb) if supports_luminance: await dev.async_set_light_color(luminance=50) if supports_temperature: await dev.async_set_light_color(temperature=50) await dev.async_turn_on() await asyncio.sleep(2) await dev.async_turn_off() manager.close() await http_api_client.async_logout() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` -------------------------------- ### SystemAllMixin Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/api-reference/controller/mixins/system.rst Provides comprehensive system-level functionalities for Meross devices. ```APIDOC ## SystemAllMixin ### Description This mixin class aggregates all system-related functionalities for Meross devices, offering a complete set of controls and information retrieval methods. ### Members This class exposes various methods and properties related to system management. Refer to the source code for a detailed list of members. ``` -------------------------------- ### Meross HTTP Client Authentication (Python) Source: https://context7.com/albertogeniola/merossiot/llms.txt Demonstrates how to authenticate with Meross cloud servers using the MerossHttpClient class. It shows how to log in with user credentials, retrieve cloud credentials (user ID, token, key), list registered devices, and log out to invalidate the session. This is a foundational step for interacting with Meross devices programmatically. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): # Create HTTP client with user credentials # API base URLs by region: # - Europe: "https://iotx-eu.meross.com" # - US: "https://iotx-us.meross.com" # - Asia-Pacific: "https://iotx-ap.meross.com" http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) # Access cloud credentials (useful for Home Assistant integrations) creds = http_api_client.cloud_credentials print(f"User ID: {creds.user_id}") print(f"Token: {creds.token}") print(f"Key: {creds.key}") print(f"Full credentials JSON: {creds.to_json()}") # List all devices registered to the account devices = await http_api_client.async_list_devices() for device in devices: print(f"Device: {device.dev_name} ({device.device_type}) - UUID: {device.uuid}") # Always logout when done to invalidate the token await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Register and Listen for Meross Push Notifications (Python) Source: https://context7.com/albertogeniola/merossiot/llms.txt This main function demonstrates how to initialize the Meross manager, register a push notification handler, listen for events for a specified duration, and then unregister the handler. It requires the meross_iot library, asyncio, and os modules. It uses environment variables or hardcoded credentials for authentication. ```python async def main(): http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() # Register the push notification handler manager.register_push_notification_handler_coroutine(push_notification_handler) print("Push notification handler registered. Listening for device events...") # Keep the connection alive to receive notifications # In a real application, this would be part of your main event loop try: # Listen for 60 seconds await asyncio.sleep(60) except KeyboardInterrupt: print("Stopping...") # Unregister the handler when done manager.unregister_push_notification_handler_coroutine(push_notification_handler) manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Control MSS310 Smart Plug Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/README.md Demonstrates how to authenticate with the Meross cloud, discover devices, and toggle a MSS310 smart plug on and off using the MerossManager. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" async def main(): http_api_client = await MerossHttpClient.async_from_user_password(api_base_url='https://iotx-eu.meross.com', email=EMAIL, password=PASSWORD) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() plugs = manager.find_devices(device_type="mss310") if len(plugs) < 1: print("No MSS310 plugs found...") else: dev = plugs[0] await dev.async_update() print(f"Turning on {dev.name}...") await dev.async_turn_on(channel=0) await asyncio.sleep(5) print(f"Turing off {dev.name}") await dev.async_turn_off(channel=0) manager.close() await http_api_client.async_logout() if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Control Garage Door Openers with Python Source: https://context7.com/albertogeniola/merossiot/llms.txt Shows how to interface with garage door openers using the GarageOpenerMixin. It includes checking the current door state, triggering open/close commands, and handling multi-channel devices like the MSG200. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager from meross_iot.controller.mixins.garage import GarageOpenerMixin async def main(): http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=os.environ.get('MEROSS_EMAIL'), password=os.environ.get('MEROSS_PASSWORD') ) manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() openers = manager.find_devices(device_class=GarageOpenerMixin, device_type="msg100") if openers: dev = openers[0] await dev.async_update() is_open = dev.get_is_open(channel=0) if not is_open: await dev.async_open(channel=0) else: await dev.async_close(channel=0) manager.close() await http_api_client.async_logout() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### ConsumptionXMixin Class Overview Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/api-reference/controller/mixins/consumption.rst Provides an overview of the ConsumptionXMixin class and its members. ```APIDOC ## ConsumptionXMixin This mixin class provides functionality for handling energy consumption data for Meross devices. ### Class Definition ```python meross_iot.controller.mixins.consumption.ConsumptionXMixin ``` ### Methods The following methods are available within this mixin: - **async_update()**: Asynchronously updates the consumption data. - **async_get_instantaneous_consumption()**: Asynchronously retrieves the instantaneous power consumption. - **async_get_daily_consumption()**: Asynchronously retrieves the daily energy consumption. - **async_get_monthly_consumption()**: Asynchronously retrieves the monthly energy consumption. - **async_get_yearly_consumption()**: Asynchronously retrieves the yearly energy consumption. ### Usage This mixin is intended to be inherited by device controller classes that support energy monitoring. ```python # Example of how a device controller might use this mixin class MySmartPlugWithConsumption(Device, ConsumptionXMixin): # ... device specific implementation ... pass ``` ``` -------------------------------- ### Load Device Registry from Dump (Python) Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/advanced-topics.rst Reloads device registry information from a previously dumped file into the `MerossManager` instance. This bypasses the need for an initial device discovery, speeding up initialization. ```python from meross_iot.manager import MerossManager # Assuming http_api_client is initialized manager = MerossManager(http_client=http_api_client) await manager.async_init() manager.load_devices_from_dump("test.dump") print("Registry dump loaded.") ``` -------------------------------- ### Manage Meross Cloud Credentials (Python) Source: https://context7.com/albertogeniola/merossiot/llms.txt This Python script demonstrates how to extract and reuse Meross cloud credentials. It checks for existing credentials in a file, loads them if available, and uses them to authenticate with the Meross cloud. If credentials are not found or are invalid, it performs a fresh login using email and password. The script saves the obtained credentials to a JSON file for future use and displays key credential details. It also verifies the credentials by listing connected devices. ```python import asyncio import os from meross_iot.http_api import MerossHttpClient from meross_iot.model.credentials import MerossCloudCreds EMAIL = os.environ.get('MEROSS_EMAIL') or "YOUR_MEROSS_CLOUD_EMAIL" PASSWORD = os.environ.get('MEROSS_PASSWORD') or "YOUR_MEROSS_CLOUD_PASSWORD" CREDS_FILE = "meross_credentials.json" async def main(): # Check if we have saved credentials if os.path.exists(CREDS_FILE): print("Loading saved credentials...") with open(CREDS_FILE, 'r') as f: creds_json = f.read() # Restore credentials from JSON creds = MerossCloudCreds.from_json(creds_json) print(f"Loaded credentials for: {creds.user_email}") print(f"Issued on: {creds.issued_on}") # Create client from existing credentials (no new token generated) try: http_api_client = await MerossHttpClient.async_from_cloud_creds(creds) print("Successfully authenticated with saved credentials!") except Exception as e: print(f"Saved credentials expired or invalid: {e}") print("Performing fresh login...") http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) else: # Fresh login print("Performing login...") http_api_client = await MerossHttpClient.async_from_user_password( api_base_url="https://iotx-eu.meross.com", email=EMAIL, password=PASSWORD ) # Get and save credentials for later use creds = http_api_client.cloud_credentials creds_json = creds.to_json() # Save to file for future sessions with open(CREDS_FILE, 'w') as f: f.write(creds_json) print(f"Credentials saved to {CREDS_FILE}") # Display credential details (useful for Home Assistant integrations) print(f"\nCredential Details:") print(f" User ID: {creds.user_id}") print(f" Email: {creds.user_email}") print(f" Token: {creds.token[:20]}...") print(f" Key: {creds.key}") print(f" API Domain: {creds.domain}") print(f" MQTT Domain: {creds.mqtt_domain}") print(f" Issued On: {creds.issued_on}") # List devices to verify credentials work devices = await http_api_client.async_list_devices() print(f"\nFound {len(devices)} devices") # Don't logout if you want to reuse the token later # await http_api_client.async_logout() print("\nNote: Token preserved for reuse (no logout)") if __name__ == '__main__': if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop() ``` -------------------------------- ### Configure Wi-Fi Credentials via HTTP POST Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/meross-protocol.rst This request provides the device with the target Wi-Fi SSID and password in base64 format. Upon receiving this, the device reboots and attempts to join the specified network. ```http POST /config HTTP/1.1 Host: Content-Type: application/json { "header": { "from": "http://10.10.10.1/config", "messageId": "{{MESSAGE_ID}}", "timestamp": {{TIMESTAMP}}, "sign": "{{SIGNATURE}}", "method": "SET", "namespace": "Appliance.Config.Wifi" }, "payload": { "wifi": { "ssid": "{{BASE64_ENCODED_SSID}}", "password": "{{BASE64_ENCODED_PASSWORD}}" } } } ``` -------------------------------- ### GarageOpenerMixin Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/api-reference/controller/mixins/cover.rst The GarageOpenerMixin class provides methods to interact with garage door openers supported by the meross_iot library. It includes functionalities for opening, closing, and checking the status of the garage door. ```APIDOC ## GarageOpenerMixin ### Description Provides methods to control and query the state of a garage door opener. ### Class `meross_iot.controller.mixins.garage.GarageOpenerMixin` ### Methods - **open_garage()** Opens the garage door. - **close_garage()** Closes the garage door. - **is_garage_open()** Returns `True` if the garage door is open, `False` otherwise. - **is_garage_closed()** Returns `True` if the garage door is closed, `False` otherwise. ### Example Usage ```python from meross_iot.manager import MerossManager from meross_iot.model.enums import OnlineStatus async def main(): manager = MerossManager.from_email_and_password("email", "password") await manager.async_login() await manager.async_device_discovery() garage_devices = manager.find_devices(device_type='garageopener') if garage_devices: garage = garage_devices[0] # Assuming only one garage device await garage.async_update() if garage.online_status == OnlineStatus.ONLINE: print(f"Garage door status: {'Open' if await garage.is_garage_open() else 'Closed'}") # To open the garage: # await garage.open_garage() # To close the garage: # await garage.close_garage() else: print("Garage device is offline.") else: print("No garage devices found.") await manager.async_logout() # Run the main function # import asyncio # asyncio.run(main()) ``` ``` -------------------------------- ### Dump Device Registry Information (Python) Source: https://github.com/albertogeniola/merossiot/blob/0.4.X.X/docs/advanced-topics.rst Exports the current device registry information held by the `MerossManager` to a file. This can be used to avoid repeated device discovery calls by reloading the registry later. ```python from meross_iot.manager import MerossManager # Assuming http_api_client is initialized manager = MerossManager(http_client=http_api_client) await manager.async_init() await manager.async_device_discovery() manager.dump_device_registry("test.dump") ```