### Initialize Python environment Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Start the Python 3 interpreter and import the library. ```python python3 ``` ```python import broadlink ``` -------------------------------- ### Device Setup Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Configures a Broadlink device to connect to a local WiFi network. ```APIDOC ## broadlink.setup ### Description Connects a Broadlink device to a local network using the provided SSID and password. ### Parameters - **ssid** (string) - Required - The WiFi network name. - **password** (string) - Required - The WiFi network password. - **security_mode** (int) - Required - Security mode (0=none, 1=WEP, 2=WPA1, 3=WPA2, 4=WPA1/2). - **ip_address** (string) - Optional - Broadcast address if default setup fails. ``` -------------------------------- ### New Device Setup Source: https://github.com/mjg59/python-broadlink/blob/master/protocol.md Configure a new Broadlink device while in AP mode. ```APIDOC ## UDP Broadcast / Setup ### Description Sends a 136-byte packet to configure SSID and password for a device in AP mode. ### Method UDP Broadcast ### Endpoint 255.255.255.255:80 ### Request Body - **0x20-0x21** (int16) - Checksum (little-endian) - **0x44-0x63** (string) - SSID Name - **0x64-0x83** (string) - Password - **0x84** (byte) - SSID length - **0x85** (byte) - Password length - **0x86** (byte) - Wireless security mode (00=none, 01=WEP, 02=WPA1, 03=WPA2, 04=WPA1/2) ``` -------------------------------- ### Initiate RF Code Learning Process Source: https://context7.com/mjg59/python-broadlink/llms.txt Starts the RF learning process for compatible RM Pro devices. This is the initial step before frequency sweeping and code capture. ```python import broadlink import time ``` -------------------------------- ### Install python-broadlink Module Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Install the python-broadlink module using pip. ```bash pip3 install broadlink ``` -------------------------------- ### Turn On LC-1 Switches Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Control LC-1 type sub-devices by setting their power state to on. This example demonstrates turning on the main power and individual power outputs (pwr1, pwr2). ```python device.set_state(did="00000000000000000000a043b0d0783a", pwr=1) device.set_state(did="00000000000000000000a043b0d0783a", pwr1=1) device.set_state(did="00000000000000000000a043b0d0783a", pwr2=1) ``` -------------------------------- ### Configure Device WiFi via AP Mode Source: https://context7.com/mjg59/python-broadlink/llms.txt Sets up a new Broadlink device to connect to your WiFi network. Ensure the device is in AP mode by long-pressing the reset button before running this setup. ```python import broadlink # Setup device WiFi (connect to BroadlinkProv SSID first) # Security modes: 0=none, 1=WEP, 2=WPA1, 3=WPA2, 4=WPA1/2 broadlink.setup( ssid='MyWiFiNetwork', password='MyWiFiPassword', security_mode=3 # WPA2 ) # With custom broadcast address broadlink.setup( ssid='MyWiFiNetwork', password='MyWiFiPassword', security_mode=3, ip_address='192.168.0.255' ) ``` -------------------------------- ### Turn Off LC-1 Switches Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Control LC-1 type sub-devices by setting their power state to off. This example demonstrates turning off the main power and individual power outputs (pwr1, pwr2). ```python device.set_state(did="00000000000000000000a043b0d0783a", pwr=0) device.set_state(did="00000000000000000000a043b0d0783a", pwr1=0) device.set_state(did="00000000000000000000a043b0d0783a", pwr2=0) ``` -------------------------------- ### Turn On Smart Plug Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Control a smart plug to turn it on. ```bash broadlink_cli --device @BEDROOM.device --turnon ``` -------------------------------- ### Specify Device Using a File Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Reference device configuration from a file using the '@' prefix. This is the preferred method for managing device settings. ```bash broadlink_cli --device @BEDROOM.device --temp ``` -------------------------------- ### Learn IR Code and Display Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Initiate IR code learning from a device and display the learned code on the console. ```bash broadlink_cli --device @BEDROOM.device --learn ``` -------------------------------- ### Learn RF Code and Display Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Initiate RF code learning using a scan and display the learned code on the console. ```bash broadlink_cli --device @BEDROOM.device --rfscanlearn ``` -------------------------------- ### Learn IR Code and Save to File Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Learn an IR code and save it to a specified file. ```bash broadlink_cli --device @BEDROOM.device --learnfile LG-TV.power ``` -------------------------------- ### Specify Device with Separate Parameters Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Use separate command-line arguments for device type, host, and MAC address. ```bash broadlink_cli --type 0x2712 --host 1.1.1.1 --mac aaaaaaaaaa --temp ``` -------------------------------- ### Specify Device with Single Argument Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Provide all device information (type, host, MAC) as a single argument. ```bash broadlink_cli --device "0x2712 1.1.1.1 aaaaaaaaaa" --temp ``` -------------------------------- ### Learn RF Code and Save to File Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Learn an RF code using a scan and save it to a specified file. ```bash broadlink_cli --device @BEDROOM.device --rfscanlearn --learnfile LG-TV.power ``` -------------------------------- ### Initialize Alarm Kit Source: https://context7.com/mjg59/python-broadlink/llms.txt Placeholder for initializing S1C/S2KIT alarm kits. ```python import broadlink ``` -------------------------------- ### Enter Learning Mode Source: https://github.com/mjg59/python-broadlink/blob/master/protocol.md Sends a command to the device to enter learning mode for capturing IR or RF signals. ```APIDOC ## POST /command/0x006a/learn ### Description Sends a 16-byte payload to initiate the learning mode on the Broadlink device. ### Method POST ### Request Body - **Offset 0x00** (byte) - Required - Value: 0x03 - **Offset 0x01-0x0f** (bytes) - Required - Value: 0x00 ``` -------------------------------- ### Turn On Smart Plug Nightlight Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Activate the nightlight feature on a smart plug. ```bash broadlink_cli --device @BEDROOM.device --turnnlon ``` -------------------------------- ### Control Smart Plugs Source: https://context7.com/mjg59/python-broadlink/llms.txt Manage power state, nightlight, and energy monitoring for SP series smart plugs. ```python import broadlink # Find and authenticate smart plug devices = broadlink.discover(timeout=5) plug = [d for d in devices if 'SP' in d.model][0] plug.auth() # Basic power control plug.set_power(True) # Turn on plug.set_power(False) # Turn off # Check power state is_on = plug.check_power() print(f"Power state: {'ON' if is_on else 'OFF'}") # SP3 and later: Nightlight control if hasattr(plug, 'set_nightlight'): plug.set_nightlight(True) # Turn on nightlight plug.set_nightlight(False) # Turn off nightlight is_nightlight_on = plug.check_nightlight() print(f"Nightlight: {'ON' if is_nightlight_on else 'OFF'}") # SP2S/SP3S/SP4B: Energy monitoring if hasattr(plug, 'get_energy'): power_watts = plug.get_energy() print(f"Current power consumption: {power_watts} W") # SP4/SP4B: Full state control if hasattr(plug, 'get_state'): state = plug.get_state() print(f"Full state: {state}") # Example state: {'pwr': 1, 'ntlight': 0, 'indicator': 1, 'ntlbrightness': 50, # 'childlock': 0, 'current': 0.5, 'volt': 120.0, 'power': 60.0} # Set multiple attributes at once plug.set_state( pwr=True, ntlight=True, indicator=True, ntlbrightness=50, childlock=False ) ``` -------------------------------- ### Configure device network Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Connect a device to the local network using SSID and password. Security mode options are 0=none, 1=WEP, 2=WPA1, 3=WPA2, 4=WPA1/2. ```python broadlink.setup('myssid', 'mynetworkpass', 3) ``` ```python broadlink.setup('myssid', 'mynetworkpass', 3, ip_address='192.168.0.255') ``` -------------------------------- ### Check Smart Plug Energy Consumption Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Query the power consumption data from a smart plug. ```bash broadlink_cli --device @BEDROOM.device --energy ``` -------------------------------- ### Learn IR codes Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Steps to capture IR signals from a remote control. ```python device.enter_learning() ``` ```python packet = device.check_data() ``` -------------------------------- ### Broadlink Command Line Interface Usage Source: https://context7.com/mjg59/python-broadlink/llms.txt Perform network discovery, device configuration, and remote control operations via the CLI. ```bash # Discover devices on the network broadlink_discovery # Join device to WiFi (while connected to BroadlinkProv AP) broadlink_cli --joinwifi "MySSID" "MyPassword" # Specify device directly broadlink_cli --type 0x2712 --host 192.168.1.50 --mac AA:BB:CC:DD:EE:FF --temp # Use device file (@filename references the file) # Device file format: 0x2712 192.168.1.50 AABBCCDDEEFF echo "0x2712 192.168.1.50 AABBCCDDEEFF" > BEDROOM.device broadlink_cli --device @BEDROOM.device --temp # Universal remote: Learn IR code broadlink_cli --device @BEDROOM.device --learn broadlink_cli --device @BEDROOM.device --learnfile tv_power.ir # Universal remote: Learn RF code broadlink_cli --device @BEDROOM.device --rfscanlearn broadlink_cli --device @BEDROOM.device --rfscanlearn --learnfile garage.rf # Universal remote: Send code broadlink_cli --device @BEDROOM.device --send @tv_power.ir # Check sensors broadlink_cli --device @BEDROOM.device --temperature broadlink_cli --device @BEDROOM.device --humidity # Smart plug control broadlink_cli --device @BEDROOM.device --turnon broadlink_cli --device @BEDROOM.device --turnoff broadlink_cli --device @BEDROOM.device --turnnlon # Nightlight on broadlink_cli --device @BEDROOM.device --turnnloff # Nightlight off broadlink_cli --device @BEDROOM.device --check # Check power state broadlink_cli --device @BEDROOM.device --checknl # Check nightlight state broadlink_cli --device @BEDROOM.device --energy # Power consumption ``` -------------------------------- ### Check Device Temperature Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Query the Broadlink device for its current temperature reading. ```bash broadlink_cli --device @BEDROOM.device --temperature ``` -------------------------------- ### Join Device to Wi-Fi Network Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Connect a Broadlink device to a specified Wi-Fi network by providing the SSID and password. ```bash broadlink_cli --joinwifi SSID PASSWORD ``` -------------------------------- ### Device Discovery Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Methods for discovering Broadlink devices on the local network. ```APIDOC ## broadlink.discover ### Description Discovers devices on the local network. ### Parameters - **local_ip_address** (string) - Optional - IP address of the local machine. - **discover_ip_address** (string) - Optional - Broadcast address of the subnet. ## broadlink.hello ### Description Unicast discovery for locked devices. ### Parameters - **ip_address** (string) - Required - IP address of the device. ``` -------------------------------- ### Control BG Electrical Smart Outlets Source: https://context7.com/mjg59/python-broadlink/llms.txt Manage power states, indicator brightness, and work timers for BG1 smart outlets. ```python import broadlink # Find and authenticate BG outlet devices = broadlink.discover(timeout=5) outlet = [d for d in devices if d.devtype in [0x51E3]][0] outlet.auth() # Get current state state = outlet.get_state() print(f"State: {state}") # Example: {'pwr':1, 'pwr1':1, 'pwr2':0, 'maxworktime':60, 'idcbrightness':50} # Control power outputs outlet.set_state(pwr=True) # Master power outlet.set_state(pwr1=True) # Output 1 outlet.set_state(pwr2=False) # Output 2 # Set indicator brightness (0-100) outlet.set_state(idcbrightness=75) # Set max work time (minutes, 0=unlimited) outlet.set_state(maxworktime=120, maxworktime1=60, maxworktime2=30) # EHC31 extension lead: Additional outputs and child lock # outlet.set_state(pwr3=True, childlock=True) ``` -------------------------------- ### Check Smart Plug Power State Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Query the current power state of a smart plug. ```bash broadlink_cli --device @BEDROOM.device --check ``` -------------------------------- ### Set State Attributes for Devices Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Use this to set various state attributes for devices, such as power, brightness, and color mode. Parameters vary based on device type. ```python devices[0].set_state(pwr=0) devices[0].set_state(pwr=1) devices[0].set_state(brightness=75) devices[0].set_state(bulb_colormode=0) devices[0].set_state(blue=255) devices[0].set_state(red=0) devices[0].set_state(green=128) devices[0].set_state(bulb_colormode=1) ``` -------------------------------- ### Check Smart Plug Nightlight State Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Query the current state of the nightlight feature on a smart plug. ```bash broadlink_cli --device @BEDROOM.device --checknl ``` -------------------------------- ### Discover Broadlink Devices Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Scan the local network to discover connected Broadlink devices. ```bash broadlink_discovery ``` -------------------------------- ### Discover and Monitor Alarm Kit Source: https://context7.com/mjg59/python-broadlink/llms.txt Locate an alarm kit on the network and iterate through its connected sensors. ```python # Find and authenticate alarm kit devices = broadlink.discover(timeout=5) alarm = [d for d in devices if d.devtype == 0x2722][0] alarm.auth() # Get all sensor statuses sensors_info = alarm.get_sensors_status() print(f"Total sensors: {sensors_info['count']}") for sensor in sensors_info['sensors']: print(f"Sensor: {sensor['name']}") print(f" Type: {sensor['type']}") # Door Sensor, Motion Sensor, Key Fob print(f" Status: {sensor['status']}") # 0=normal, 1=triggered print(f" Serial: {sensor['serial']}") print(f" Order: {sensor['order']}") ``` -------------------------------- ### Control LB Series Smart Bulbs Source: https://context7.com/mjg59/python-broadlink/llms.txt Manage power, brightness, color modes, and transitions for Broadlink smart light bulbs. ```python import broadlink # Find and authenticate light bulb devices = broadlink.discover(timeout=5) bulb = [d for d in devices if 'LB' in d.model][0] bulb.auth() # Get current state state = bulb.get_state() print(f"Power: {'ON' if state['pwr'] else 'OFF'}") print(f"Brightness: {state['brightness']}%") print(f"Color mode: {state['bulb_colormode']}") # 0=RGB, 1=White, 2=Scene # Power control bulb.set_state(pwr=True) # Turn on bulb.set_state(pwr=False) # Turn off # Brightness control (1-100) bulb.set_state(brightness=75) # RGB color mode bulb.set_state(bulb_colormode=0) # Switch to RGB mode bulb.set_state(red=255, green=0, blue=0) # Red bulb.set_state(red=0, green=255, blue=0) # Green bulb.set_state(red=0, green=0, blue=255) # Blue bulb.set_state(red=255, green=128, blue=0) # Orange # White/color temperature mode (2700K-6500K typically) bulb.set_state(bulb_colormode=1) # Switch to white mode bulb.set_state(colortemp=2700) # Warm white bulb.set_state(colortemp=6500) # Cool white # HSV control bulb.set_state(hue=240, saturation=100) # Blue via HSV # Transition duration (milliseconds) bulb.set_state(brightness=100, transitionduration=2000) # 2 second fade # Set multiple attributes at once bulb.set_state( pwr=True, bulb_colormode=0, red=128, green=0, blue=255, brightness=80, transitionduration=500 ) ``` -------------------------------- ### Learn RF codes Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Steps to capture RF signals, including frequency sweeping and packet identification. ```python device.sweep_frequency() ``` ```python ok = device.check_frequency() if ok: print('Frequency found!') ``` ```python device.find_rf_packet() ``` ```python packet = device.check_data() ``` -------------------------------- ### Fetch light bulb state Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Retrieve the current state of a light bulb. ```python state = device.get_state() ``` -------------------------------- ### Discover Broadlink Devices on Network Source: https://context7.com/mjg59/python-broadlink/llms.txt Broadcasts a discovery packet to find Broadlink devices. Use `broadlink.hello()` for direct connections or locked devices. The generator version `broadlink.xdiscover()` is more memory efficient. ```python import broadlink # Discover all devices on the network (default 10 second timeout) devices = broadlink.discover(timeout=10) for device in devices: print(f"Found: {device.name} ({device.model}) at {device.host[0]}") print(f" MAC: {':'.join(format(x, '02X') for x in device.mac)}") print(f" Type: {hex(device.devtype)}") # Discover with specific network settings devices = broadlink.discover( timeout=5, local_ip_address='192.168.1.100', # Your machine's IP discover_ip_address='192.168.1.255' # Broadcast address ) # Generator version for instant device yielding (memory efficient) for device in broadlink.xdiscover(timeout=10): print(f"Found device: {device}") # Direct discovery for locked devices device = broadlink.hello('192.168.1.50') print(f"Connected to: {device}") ``` -------------------------------- ### Authenticate device Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Obtain the authentication key required for further communication. ```python device.auth() ``` -------------------------------- ### Check Device Humidity Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Query the Broadlink device for its current humidity reading. ```bash broadlink_cli --device @BEDROOM.device --humidity ``` -------------------------------- ### Discover Broadlink devices Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Methods to find devices on the network, including unicast and high-performance discovery. ```python devices = broadlink.discover() ``` ```python devices = broadlink.discover(local_ip_address='192.168.0.100') ``` ```python devices = broadlink.discover(discover_ip_address='192.168.0.255') ``` ```python device = broadlink.hello('192.168.0.16') ``` ```python for device in broadlink.xdiscover(): print(device) # Example action. Do whatever you want here. ``` -------------------------------- ### Cancel learning mode Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Exit the learning process prematurely. ```python device.cancel_sweep_frequency() ``` -------------------------------- ### Learn IR Codes with Universal Remote Source: https://context7.com/mjg59/python-broadlink/llms.txt Enters learning mode on an RM series remote to capture IR signals from existing remotes. Captured codes can be saved as base64 or to a file. Handles potential read errors if no code is captured. ```python import broadlink import time import base64 # Find and authenticate RM device devices = broadlink.discover(timeout=5) remote = [d for d in devices if d.devtype in [0x2712, 0x2737, 0x51DA]][0] remote.auth() # Enter IR learning mode remote.enter_learning() print("Point your remote at the device and press a button...") # Wait and check for data (polling approach) time.sleep(5) try: ir_packet = remote.check_data() print(f"Captured IR code ({len(ir_packet)} bytes)") # Save as base64 for storage ir_code_b64 = base64.b64encode(ir_packet).decode('utf-8') print(f"Base64: {ir_code_b64}") # Save to file with open('tv_power.ir', 'wb') as f: f.write(ir_packet) except broadlink.exceptions.ReadError: print("No IR code captured - timeout") ``` -------------------------------- ### Turn Off Smart Plug Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Control a smart plug to turn it off. ```bash broadlink_cli --device @BEDROOM.device --turnoff ``` -------------------------------- ### Fetch sensor data Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Retrieve data from environment sensors. ```python data = device.check_sensors() ``` -------------------------------- ### Handle Broadlink Exceptions Source: https://context7.com/mjg59/python-broadlink/llms.txt Implement robust error handling by catching specific Broadlink library exceptions during device operations. ```python import broadlink from broadlink import exceptions as e try: devices = broadlink.discover(timeout=5) if not devices: print("No devices found") else: device = devices[0] device.auth() # ... operations except e.NetworkTimeoutError as err: print(f"Network timeout: {err}") # Device not responding, check network/power except e.AuthenticationError as err: print(f"Authentication failed: {err}") # Invalid credentials or device locked except e.AuthorizationError as err: print(f"Authorization error: {err}") # Control key expired, re-authenticate except e.DeviceOfflineError as err: print(f"Device offline: {err}") # Device powered off or disconnected except e.CommandNotSupportedError as err: print(f"Command not supported: {err}") # Feature not available on this device model except e.DataValidationError as err: print(f"Data validation error: {err}") # Corrupted response or MAC mismatch except e.StorageError as err: print(f"Storage full: {err}") # Device storage is full except e.BroadlinkException as err: print(f"Broadlink error: {err}") # Generic Broadlink error ``` -------------------------------- ### Manage S3 Hub and Subdevices Source: https://context7.com/mjg59/python-broadlink/llms.txt Discover subdevices connected to an S3 hub and control them using their device ID (DID). ```python import broadlink # Find and authenticate hub devices = broadlink.discover(timeout=5) hub = [d for d in devices if d.devtype in [0xA59C, 0xA64D]][0] hub.auth() # Discover all connected subdevices subdevices = hub.get_subdevices() for device in subdevices: print(f"DID: {device['did']}") print(f" Name: {device.get('name', 'Unknown')}") print(f" Type: {device.get('type', 'Unknown')}") # Get state of specific subdevice did = "00000000000000000000a043b0d06963" state = hub.get_state(did=did) print(f"Subdevice state: {state}") # Control LC-1 switch (multi-gang switch) did = "00000000000000000000a043b0d0783a" # Turn on all switches hub.set_state(did=did, pwr1=True, pwr2=True, pwr3=True) # Turn off specific switch hub.set_state(did=did, pwr1=False) # Get hub state without specific DID hub_state = hub.get_state() print(f"Hub state: {hub_state}") ``` -------------------------------- ### Manage switch power Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Control and check the power state of a switch. ```python device.set_power(True) device.set_power(False) ``` ```python state = device.check_power() ``` ```python state = device.get_energy() ``` -------------------------------- ### Send IR/RF packets Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Transmit a previously learned packet. ```python device.send_data(packet) ``` -------------------------------- ### Manage power strip sockets Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Control individual sockets on a power strip. ```python device.set_power(1, True) # Example socket. It could be 2 or 3. device.set_power(1, False) ``` ```python state = device.check_power() ``` -------------------------------- ### Send Code from File Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Transmit an IR or RF code stored in a file to the Broadlink device. ```bash broadlink_cli --device @BEDROOM.device --send @LG-TV.power ``` -------------------------------- ### Check Power Strip States Source: https://context7.com/mjg59/python-broadlink/llms.txt Retrieve power status for individual sockets and energy monitoring data if supported by the device. ```python power_state = strip.check_power() print(f"Socket 1: {'ON' if power_state['s1'] else 'OFF'}") print(f"Socket 2: {'ON' if power_state['s2'] else 'OFF'}") print(f"Socket 3: {'ON' if power_state['s3'] else 'OFF'}") print(f"Socket 4: {'ON' if power_state['s4'] else 'OFF'}") # MP1S: Energy monitoring if hasattr(strip, 'get_state'): state = strip.get_state() print(f"Voltage: {state['volt']} V") print(f"Current: {state['current']} A") print(f"Power: {state['power']} W") print(f"Total consumption: {state['totalconsum']} kWh") ``` -------------------------------- ### Discover Sub-devices Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Use this function to discover and list sub-devices connected to the main Broadlink hub. The returned sub-device IDs (DIDs) are necessary for further control. ```python device.get_subdevices() ``` -------------------------------- ### Universal Remote Control Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Methods for learning and sending IR/RF codes via universal remotes. ```APIDOC ## device.enter_learning ### Description Enters IR learning mode. ## device.check_data ### Description Retrieves the learned IR or RF packet. ## device.send_data ### Description Sends an IR or RF packet. ### Parameters - **packet** (bytes) - Required - The data packet to send. ``` -------------------------------- ### Learn and Capture RF Codes Source: https://context7.com/mjg59/python-broadlink/llms.txt Perform frequency sweeping and RF packet learning on compatible RM Pro devices. ```python devices = broadlink.discover(timeout=5) remote = [d for d in devices if d.devtype in [0x2712, 0x272A, 0x520B]][0] remote.auth() # Step 1: Start frequency sweep remote.sweep_frequency() print("Long press the RF button on your remote...") # Step 2: Wait for frequency detection time.sleep(10) found, frequency = remote.check_frequency() if found: print(f"Frequency detected: {frequency} MHz") # Step 3: Enter RF learning mode remote.find_rf_packet(frequency) print("Short press the RF button again...") # Step 4: Capture the RF code time.sleep(5) try: rf_packet = remote.check_data() print(f"Captured RF code ({len(rf_packet)} bytes)") # Save for later use with open('garage_door.rf', 'wb') as f: f.write(rf_packet) except broadlink.exceptions.ReadError: print("No RF code captured") else: print("Frequency not detected - try again") remote.cancel_sweep_frequency() ``` -------------------------------- ### Device Authorization Source: https://github.com/mjg59/python-broadlink/blob/master/protocol.md Obtain an authorization key and device ID required for further communication. ```APIDOC ## POST /authorize ### Description Sends an 80-byte packet to obtain an authorization key and device ID. ### Method UDP ### Request Body - **0x04-0x12** (string) - 15-digit device identifier (e.g., IMEI) - **0x30-0x7f** (string) - NULL-terminated device name ### Response #### Success Response (200) - **0x00-0x03** (int32) - Device ID - **0x04-0x13** (bytes) - Device encryption key ``` -------------------------------- ### Interact with A1 Environment Sensor Source: https://context7.com/mjg59/python-broadlink/llms.txt Discover and authenticate an A1 sensor to retrieve human-readable or raw numeric environmental data. ```python import broadlink # Find and authenticate A1 sensor devices = broadlink.discover(timeout=5) sensor = [d for d in devices if d.devtype == 0x2714][0] sensor.auth() # Get sensor readings with human-readable levels data = sensor.check_sensors() print(f"Temperature: {data['temperature']}°C") print(f"Humidity: {data['humidity']}%") print(f"Light: {data['light']}") # dark, dim, normal, bright print(f"Air Quality: {data['air_quality']}") # excellent, good, normal, bad print(f"Noise: {data['noise']}") # quiet, normal, noisy # Get raw numeric values raw_data = sensor.check_sensors_raw() print(f"Raw readings: {raw_data}") # {'temperature': 23.5, 'humidity': 45.0, 'light': 2, 'air_quality': 1, 'noise': 0} ``` -------------------------------- ### Authenticate and Control Broadlink Device Source: https://context7.com/mjg59/python-broadlink/llms.txt Authenticates with a discovered device to obtain the encryption key for secure communication. After authentication, you can retrieve firmware versions, set device names, lock/unlock devices, and send ping commands. ```python import broadlink # Discover and authenticate devices = broadlink.discover(timeout=5) if devices: device = devices[0] # Authenticate to get encryption key device.auth() print(f"Authenticated with {device.name}") # Get firmware version fw_version = device.get_fwversion() print(f"Firmware version: {fw_version}") # Set device name device.set_name("Living Room Remote") # Lock/unlock device (prevents discovery by other apps) device.set_lock(True) # Lock device.set_lock(False) # Unlock # Send ping to keep device awake (required for firmware >= v53) device.ping() ``` -------------------------------- ### Switch and Power Strip Control Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Methods for managing power states of switches and power strips. ```APIDOC ## device.set_power ### Description Sets the power state of a switch or specific socket on a power strip. ### Parameters - **socket** (int) - Optional - Socket index for power strips. - **state** (bool) - Required - True for ON, False for OFF. ## device.check_power ### Description Returns the current power state of the device. ``` -------------------------------- ### Network Discovery Source: https://github.com/mjg59/python-broadlink/blob/master/protocol.md Discover Broadlink devices on the local network by sending a broadcast packet. ```APIDOC ## UDP Broadcast / Discovery ### Description Sends a 48-byte packet to discover Broadlink devices on the local network. ### Method UDP Broadcast ### Endpoint 255.255.255.255:80 ### Request Body - **0x08-0x0b** (int32) - Current offset from GMT (little-endian) - **0x0c-0x0d** (int16) - Current year (little-endian) - **0x0e** (byte) - Seconds past the minute - **0x0f** (byte) - Minutes past the hour - **0x10** (byte) - Hours past midnight - **0x11** (byte) - Day of the week (1=Monday) - **0x12** (byte) - Day in month - **0x13** (byte) - Month - **0x18-0x1b** (ip) - Local IP address - **0x1c-0x1d** (int16) - Source port (little-endian) - **0x20-0x21** (int16) - Checksum (little-endian) ### Response #### Success Response (200) - **0x34-0x35** (int16) - Device type - **0x3a-0x3f** (bytes) - MAC address ``` -------------------------------- ### Fetch State of a Specific Sub-device Source: https://github.com/mjg59/python-broadlink/blob/master/README.md Retrieve the current state of a specific sub-device using its unique Device ID (DID). This is useful for monitoring individual component statuses. ```python device.get_state(did="00000000000000000000a043b0d06963") ``` -------------------------------- ### Control Power Strips Source: https://context7.com/mjg59/python-broadlink/llms.txt Individually control sockets on MP series power strips. ```python import broadlink # Find and authenticate power strip devices = broadlink.discover(timeout=5) strip = [d for d in devices if 'MP1' in d.model][0] strip.auth() # Control individual sockets (1-4) strip.set_power(1, True) # Turn on socket 1 strip.set_power(2, True) # Turn on socket 2 strip.set_power(3, False) # Turn off socket 3 strip.set_power(4, False) # Turn off socket 4 ``` -------------------------------- ### Send IR/RF Code Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Transmit a learned IR or RF code to the Broadlink device. ```bash broadlink_cli --device @BEDROOM.device --send DATA ``` -------------------------------- ### Read Captured Data Source: https://github.com/mjg59/python-broadlink/blob/master/protocol.md Retrieves the captured IR or RF data from the device after learning mode has been triggered. ```APIDOC ## GET /command/0x006a/read ### Description Reads the captured data from the device. Byte 0x22 of the response contains a little-endian 16-bit error code. If 0, data is available. Bytes 0x38 and onward are encrypted and must be decrypted to access the captured payload. ### Method GET ### Request Body - **Offset 0x00** (byte) - Required - Value: 0x04 - **Offset 0x01-0x0f** (bytes) - Required - Value: 0x00 ### Response - **Byte 0x22** (uint16) - Error code (0 indicates success) - **Bytes 0x38+** (binary) - Encrypted captured data ``` -------------------------------- ### Read RM4 Sensor Data Source: https://context7.com/mjg59/python-broadlink/llms.txt Retrieve temperature and humidity readings from RM4 series devices. ```python import broadlink # Find RM4 device with sensors devices = broadlink.discover(timeout=5) remote = [d for d in devices if d.devtype in [0x51DA, 0x520B]][0] remote.auth() # Get temperature and humidity (RM4 series) sensors = remote.check_sensors() print(f"Temperature: {sensors['temperature']}°C") print(f"Humidity: {sensors['humidity']}%") # Convenience methods temp = remote.check_temperature() humidity = remote.check_humidity() print(f"Current: {temp}°C, {humidity}% RH") ``` -------------------------------- ### Turn Off Smart Plug Nightlight Source: https://github.com/mjg59/python-broadlink/blob/master/cli/README.md Deactivate the nightlight feature on a smart plug. ```bash broadlink_cli --device @BEDROOM.device --turnnloff ``` -------------------------------- ### Interact with A2 Air Quality Sensor Source: https://context7.com/mjg59/python-broadlink/llms.txt Retrieve particulate matter readings including PM1, PM2.5, and PM10 from an A2 sensor. ```python import broadlink # Find and authenticate A2 sensor devices = broadlink.discover(timeout=5) sensor = [d for d in devices if d.devtype == 0x4F60][0] sensor.auth() # Get air quality readings data = sensor.check_sensors_raw() print(f"Temperature: {data['temperature']} (raw value)") print(f"Humidity: {data['humidity']} (raw value)") print(f"PM1.0: {data['pm1']} µg/m³") print(f"PM2.5: {data['pm2_5']} µg/m³") print(f"PM10: {data['pm10']} µg/m³") ``` -------------------------------- ### Transmit IR and RF Codes Source: https://context7.com/mjg59/python-broadlink/llms.txt Send captured IR or RF packets from files, base64 strings, or manual pulse timing definitions. ```python import broadlink import base64 # Find and authenticate devices = broadlink.discover(timeout=5) remote = devices[0] remote.auth() # Send from saved file with open('tv_power.ir', 'rb') as f: ir_packet = f.read() remote.send_data(ir_packet) print("IR code sent!") # Send from base64 string ir_code_b64 = "JgBYAAABKZQSExI..." # Your saved code ir_packet = base64.b64decode(ir_code_b64) remote.send_data(ir_packet) # Convert pulse timings to packet (for manual code creation) from broadlink.remote import pulses_to_data, data_to_pulses # Create IR packet from microsecond pulse timings # [ON_duration, OFF_duration, ON_duration, OFF_duration, ...] pulses = [9000, 4500, 560, 560, 560, 1690, 560, 560] # Example NEC header ir_packet = pulses_to_data(pulses) remote.send_data(ir_packet) # Parse packet back to pulse timings recovered_pulses = data_to_pulses(ir_packet) print(f"Pulse timings: {recovered_pulses}") ``` -------------------------------- ### Transmit Data Source: https://github.com/mjg59/python-broadlink/blob/master/protocol.md Sends IR or RF data to be transmitted by the Broadlink device. ```APIDOC ## POST /command/0x006a/transmit ### Description Transmits IR or RF signals using the specified pulse lengths and frequency settings. ### Method POST ### Request Body - **Offset 0x00** (byte) - Required - Value: 0x02 - **Offset 0x01-0x03** (bytes) - Required - Value: 0x00 - **Offset 0x04** (byte) - Required - Type: 0x26 (IR), 0xb2 (RF 433Mhz), 0xd7 (RF 315Mhz) - **Offset 0x05** (byte) - Required - Repeat count - **Offset 0x06-0x07** (uint16) - Required - Length of data (little endian) - **Offset 0x08+** (bytes) - Required - Pulse lengths in 2^-15 s units ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.