### Install from source Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/installation.md Execute this command after downloading the source to complete the installation. ```console $ python setup.py install ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/README.rst Examples of discovering devices, checking state, and toggling power via the CLI. ```bash $ pysonofflanr3 discover 2019-01-31 00:45:32,074 - info: Attempting to discover Sonoff LAN Mode devices on the local network, please wait... 2019-01-31 00:46:24,007 - info: Found Sonoff LAN Mode device at IP 192.168.0.77 $ pysonofflanr3 --host 192.168.0.77 state 2019-01-31 00:41:34,931 - info: Initialising SonoffSwitch with host 192.168.0.77 2019-01-31 00:41:35,016 - info: == Device: 10006866e9 (192.168.0.77) == 2019-01-31 00:41:35,016 - info: State: OFF $ pysonofflanr3 --host 192.168.0.77 on 2019-01-31 00:49:40,334 - info: Initialising SonoffSwitch with host 192.168.0.77 2019-01-31 00:49:40,508 - info: 2019-01-31 00:49:40,508 - info: Initial state: 2019-01-31 00:49:40,508 - info: == Device: 10006866e9 (192.168.0.77) == 2019-01-31 00:49:40,508 - info: State: OFF 2019-01-31 00:49:40,508 - info: 2019-01-31 00:49:40,508 - info: New state: 2019-01-31 00:49:40,508 - info: == Device: 10006866e9 (192.168.0.77) == 2019-01-31 00:49:40,508 - info: State: ON ``` -------------------------------- ### Set up local development environment Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/CONTRIBUTING.rst Commands to create a virtual environment and install the package in development mode. ```shell $ mkvirtualenv pysonofflan $ cd pysonofflan/ $ python setup.py develop ``` -------------------------------- ### Install via pip Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/installation.md Use this command to install the most recent stable release of the library. ```console $ pip install pysonofflanr3 ``` -------------------------------- ### Low-Level Protocol Client Example Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Illustrates the basic setup for the SonoffLANModeClient, which handles the underlying communication protocols including mDNS, HTTP, and encrypted messages. A message handler function is provided to process incoming data. ```python import asyncio import logging from pysonofflanr3 import SonoffLANModeClient logger = logging.getLogger(__name__) loop = asyncio.get_event_loop() async def message_handler(message): """Handle incoming messages from the device""" if message: print(f"Received message: {message}") ``` -------------------------------- ### CLI Usage Examples Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Execute common tasks like discovery, state retrieval, and device control directly from the terminal. ```bash # Discover all Sonoff devices on the network pysonofflanr3 discover # Get device state by IP address pysonofflanr3 --host 192.168.1.50 state # Get device state by device ID (with API key for encrypted devices) pysonofflanr3 --device_id 10006866e9 --api_key "your-api-key" state # Turn device ON pysonofflanr3 --host 192.168.1.50 --api_key "your-api-key" on # Turn device OFF pysonofflanr3 --host 192.168.1.50 --api_key "your-api-key" off # Use inching mode (turn ON for 5 seconds then OFF) pysonofflanr3 --host 192.168.1.50 --api_key "your-api-key" --inching 5 on # Listen for state changes (continuous monitoring) pysonofflanr3 --host 192.168.1.50 --api_key "your-api-key" listen # Listen with automatic exit after N updates pysonofflanr3 --host 192.168.1.50 --api_key "your-api-key" --wait 5 listen # Set log level for debugging pysonofflanr3 --host 192.168.1.50 -l DEBUG state # Environment variables can be used instead of CLI options export PYSONOFFLAN_HOST=192.168.1.50 export PYSONOFFLAN_api_key=your-api-key pysonofflanr3 state ``` -------------------------------- ### Example API Key Response Format Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/encryption.md The JSON structure returned by the device containing the API key during the pairing process. ```json {"type":1,"deviceid":"xxxxxxxxxx","apikey":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","rptInfo":{"code":3100,"arg":"{\"rstReason\":0}"},"sequence":"0845895318697"} ``` -------------------------------- ### Get Sonoff Device State with pysonofflan Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Query the current state (ON/OFF) of a specific Sonoff device using its IP address. Ensure the device is reachable on the network. ```bash $ pysonofflanr3 --host 192.168.0.77 state 2019-01-31 00:41:34,931 - info: Initialising SonoffSwitch with host 192.168.0.77 2019-01-31 00:41:35,016 - info: == Device: 10006866e9 (192.168.0.77) == 2019-01-31 00:41:35,016 - info: State: OFF ``` -------------------------------- ### CLI Usage Help Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/README.rst View the command-line interface options and commands. ```text Usage: pysonofflanr3 [OPTIONS] COMMAND [ARGS]... A cli tool for controlling Sonoff Smart Switches/Plugs in LAN Mode. Options: --host TEXT IP address or hostname of the device to connect to. --device_id TEXT Device ID of the device to connect to. --inching TEXT Number of seconds of "on" time if this is an Inching/Momentary switch. -l, --level LVL Either CRITICAL, ERROR, WARNING, INFO or DEBUG --help Show this message and exit. --api_key KEY Needed for devices not in DIY mode. See https://pysonofflanr3.readthedocs.io/encryption.html Commands: discover Discover devices in the network listen Connect to device, print state and repeat off Turn the device off. on Turn the device on. state Connect to device and print current state. ``` -------------------------------- ### CLI Command: listen Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Connects to the device, prints its state, and continues to listen for updates. ```APIDOC ## listen ### Description Connect to device, print state and repeat. ### Parameters #### Options - **--host** (TEXT) - Optional - IP address or hostname of the device. - **--device_id** (TEXT) - Optional - Device ID of the device. - **--api_key** (KEY) - Optional - Needed for devices not in DIY mode. ``` -------------------------------- ### Initialize Low-Level Client Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Instantiate the SonoffLANModeClient to manage device connections and send commands. ```python # Create low-level client client = SonoffLANModeClient( host="192.168.1.50", event_handler=message_handler, ping_interval=5, # Default: 5 seconds timeout=5, # Default: 5 seconds logger=logger, loop=loop, device_id="10006866e9", api_key="your-api-key-here", outlet=0 # For power strips, specify outlet number (0-indexed) ) # Start listening for mDNS service announcements client.listen() # Send switch command payload = client.get_update_payload( device_id="10006866e9", params={"switch": "on"} ) client.send_switch(payload) ``` -------------------------------- ### Initialize SonoffSwitch with Callback Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Demonstrates initializing the SonoffSwitch class with a callback for device updates. Supports direct IP connection or device ID, and includes handling for encrypted devices using an API key. ```python import asyncio from pysonofflanr3 import SonoffSwitch # Basic usage: Connect and get device state async def get_state_callback(device): if device.basic_info is not None: print(f"Device ID: {device.device_id}") print(f"State: {'ON' if device.is_on else 'OFF'}") print(f"Available: {device.available}") device.shutdown_event_loop() # Initialize switch with callback switch = SonoffSwitch( host="192.168.1.50", callback_after_update=get_state_callback ) # For encrypted devices (non-DIY mode), provide api_key switch_encrypted = SonoffSwitch( host="192.168.1.50", callback_after_update=get_state_callback, api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ) # Connect by device_id instead of IP address switch_by_id = SonoffSwitch( device_id="10006866e9", callback_after_update=get_state_callback ) ``` -------------------------------- ### Instantiate SonoffSwitch with Host Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Initialize the SonoffSwitch class by providing the IP address of the Sonoff device. This establishes a connection and fetches the device's current state. ```python x = SonoffSwitch("192.168.1.50") ``` -------------------------------- ### CLI Command: state Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Connects to the device and prints its current state. ```APIDOC ## state ### Description Connect to device and print current state. ### Parameters #### Options - **--host** (TEXT) - Optional - IP address or hostname of the device. - **--device_id** (TEXT) - Optional - Device ID of the device. - **--api_key** (KEY) - Optional - Needed for devices not in DIY mode. ``` -------------------------------- ### Command-Line Usage Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md View the CLI help and available commands for controlling Sonoff devices. ```default Usage: pysonofflanr3 [OPTIONS] COMMAND [ARGS]... A cli tool for controlling Sonoff Smart Switches/Plugs in LAN Mode. Options: --host TEXT IP address or hostname of the device to connect to. --device_id TEXT Device ID of the device to connect to. --inching TEXT Number of seconds of "on" time if this is an Inching/Momentary switch. -l, --level LVL Either CRITICAL, ERROR, WARNING, INFO or DEBUG --help Show this message and exit. --api_key KEY Needed for devices not in DIY mode. See https://pysonofflanr3.readthedocs.io/encryption.html Commands: discover Discover devices in the network listen Connect to device, print state and repeat off Turn the device off. on Turn the device on. state Connect to device and print current state. ``` -------------------------------- ### Clone from source Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/installation.md Download the source code by cloning the public repository. ```console $ git clone git://github.com/mattsaxon/pysonofflan ``` -------------------------------- ### CLI Command: discover Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Discovers Sonoff devices available on the local network. ```APIDOC ## discover ### Description Discover devices in the network. ### Command `pysonofflanr3 discover` ``` -------------------------------- ### CLI Command: on Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Turns the specified Sonoff device on. ```APIDOC ## on ### Description Turn the device on. ### Parameters #### Options - **--host** (TEXT) - Optional - IP address or hostname of the device. - **--device_id** (TEXT) - Optional - Device ID of the device. - **--api_key** (KEY) - Optional - Needed for devices not in DIY mode. ``` -------------------------------- ### Clone the repository Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/CONTRIBUTING.rst Initial step to create a local copy of the project fork. ```shell $ git clone git@github.com:your_name_here/pysonofflan.git ``` -------------------------------- ### Library Usage Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/README.rst Instantiate the SonoffSwitch class to interact with a device. ```python x = SonoffSwitch("192.168.1.50") ``` ```python async def print_state_callback(device): if device.basic_info is not None: print("ON" if device.is_on else "OFF") device.shutdown_event_loop() SonoffSwitch( host="192.168.1.50", callback_after_update=print_state_callback ) ``` -------------------------------- ### Create a development branch Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/CONTRIBUTING.rst Command to switch to a new branch for implementing changes. ```shell $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Deploy project updates Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/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 ``` -------------------------------- ### Run quality checks and tests Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/CONTRIBUTING.rst Commands to verify code style and run test suites. ```shell $ flake8 pysonofflanr3 tests $ python setup.py test or py.test $ tox ``` -------------------------------- ### Monitor Device State Changes Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Use an async callback function to react to real-time state updates from a Sonoff device. ```python from pysonofflanr3 import SonoffSwitch async def state_monitor_callback(device): """Called whenever device state changes""" device.shared_state["callback_counter"] += 1 if device.basic_info is not None: print(f"== Device: {device.device_id} ({device.host}) ==") print(f"State: {'ON' if device.is_on else 'OFF'}") print(f"Available: {device.available}") print(f"Update count: {device.shared_state['callback_counter']}") # Stop after 10 updates if device.shared_state["callback_counter"] >= 10: device.shutdown_event_loop() # Shared state for tracking across callbacks shared_state = {"callback_counter": 0} SonoffSwitch( host="192.168.1.50", callback_after_update=state_monitor_callback, shared_state=shared_state, api_key="your-api-key-here" ) ``` -------------------------------- ### Discover Sonoff Devices on Network Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Uses the Discover class to scan the local network for Sonoff devices via mDNS (Zeroconf). It returns a dictionary mapping device IDs to their IP addresses and ports. The discovery process can be configured with a specific waiting time. ```python import asyncio import logging from pysonofflanr3 import Discover # Setup logger logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def find_devices(): # Discover devices (waits 5 seconds by default) devices = await Discover.discover(logger, seconds_to_wait=10) # Returns dict: {"device_id": "ip:port", ...} for device_id, socket_address in devices.items(): print(f"Found device: {device_id} at {socket_address}") return devices # Run discovery loop = asyncio.get_event_loop() found_devices = loop.run_until_complete(find_devices()) # Output example: # Found device: 10006866e9 at 192.168.1.50:8081 # Found device: 1000686712 at 192.168.1.51:8081 ``` -------------------------------- ### SonoffSwitch with Callback for State Update Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Use the 'callback_after_update' parameter to execute an asynchronous function after the device connection is initialized and state is updated. The callback receives the device object and should handle its own loop management if necessary. ```python async def print_state_callback(device): if device.basic_info is not None: print("ON" if device.is_on else "OFF") device.shutdown_event_loop() SonoffSwitch( host="192.168.1.50", callback_after_update=print_state_callback ) ``` -------------------------------- ### Download tarball Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/installation.md Download the source code as a tarball using curl. ```console $ curl -OL https://github.com/mattsaxon/pysonofflan/tarball/master ``` -------------------------------- ### Run specific tests Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/CONTRIBUTING.rst Command to execute a subset of tests using the unittest module. ```shell $ python -m unittest tests.test_pysonofflan ``` -------------------------------- ### Turn Sonoff Device ON with pysonofflan Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Control a Sonoff device by sending an 'on' command via its IP address. This will switch the device to the ON state. ```bash $ pysonofflanr3 --host 192.168.0.77 on 2019-01-31 00:49:40,334 - info: Initialising SonoffSwitch with host 192.168.0.77 2019-01-31 00:49:40,508 - info: 2019-01-31 00:49:40,508 - info: Initial state: 2019-01-31 00:49:40,508 - info: == Device: 10006866e9 (192.168.0.77) == 2019-01-31 00:49:40,508 - info: State: OFF 2019-01-31 00:49:40,508 - info: 2019-01-31 00:49:40,508 - info: New state: 2019-01-31 00:49:40,508 - info: == Device: 10006866e9 (192.168.0.77) == 2019-01-31 00:49:40,508 - info: State: ON ``` -------------------------------- ### Discover Sonoff Devices with pysonofflan Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Use the 'discover' command to find Sonoff LAN Mode devices on your local network. This command initiates a network scan and reports the IP addresses of found devices. ```bash $ pysonofflanr3 discover 2019-01-31 00:45:32,074 - info: Attempting to discover Sonoff LAN Mode devices on the local network, please wait... 2019-01-31 00:46:24,007 - info: Found Sonoff LAN Mode device at IP 192.168.0.77 ``` -------------------------------- ### Capture API Key via TCPDump Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/encryption.md Command to monitor network traffic on an OpenWRT router to intercept the API key during device pairing. ```bash tcpdump -s 0 -vvv -i wlan1 -w | grep apikey ``` -------------------------------- ### Commit and push changes Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/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 ``` -------------------------------- ### Control Sonoff Device Power State Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Shows how to control a Sonoff device's power state by turning it on or off using async methods or by setting the state property. Requires an API key for encrypted devices. ```python from pysonofflanr3 import SonoffSwitch async def control_device_callback(device): if device.basic_info is not None and device.available: # Check current state print(f"Current state: {device.state}") # "ON", "OFF", or "UNKNOWN" # Turn the device on if device.is_off: await device.turn_on() print("Device turned ON") # Turn the device off if device.is_on: await device.turn_off() print("Device turned OFF") device.shutdown_event_loop() SonoffSwitch( host="192.168.1.50", callback_after_update=control_device_callback, api_key="your-api-key-here" # Required for encrypted devices ) ``` -------------------------------- ### Control Power Strip Outlets Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Specify the outlet index when initializing SonoffSwitch to control individual sockets on a power strip. ```python from pysonofflanr3 import SonoffSwitch async def strip_callback(device): if device.basic_info is not None and device.available: print(f"Outlet state: {'ON' if device.is_on else 'OFF'}") await device.turn_on() device.shutdown_event_loop() # Control outlet 0 on a power strip SonoffSwitch( host="192.168.1.50", callback_after_update=strip_callback, api_key="your-api-key-here", outlet=0 # First outlet ) # Control outlet 2 on the same strip SonoffSwitch( host="192.168.1.50", callback_after_update=strip_callback, api_key="your-api-key-here", outlet=2 # Third outlet ) ``` -------------------------------- ### CLI Command: off Source: https://github.com/mattsaxon/pysonofflan/blob/V3-Firmware/docs/readme.md Turns the specified Sonoff device off. ```APIDOC ## off ### Description Turn the device off. ### Parameters #### Options - **--host** (TEXT) - Optional - IP address or hostname of the device. - **--device_id** (TEXT) - Optional - Device ID of the device. - **--api_key** (KEY) - Optional - Needed for devices not in DIY mode. ``` -------------------------------- ### Configure Inching/Momentary Mode Source: https://context7.com/mattsaxon/pysonofflan/llms.txt Configures a Sonoff switch to automatically turn off after a specified duration, useful for devices like garage doors or doorbells. Requires an API key for encrypted devices. ```python from pysonofflanr3 import SonoffSwitch async def inching_callback(device): if device.basic_info is not None: print(f"Inching switch activated") print(f"Device will turn OFF automatically after inching period") # Device will turn ON, then automatically turn OFF after 3 seconds SonoffSwitch( host="192.168.1.50", callback_after_update=inching_callback, inching_seconds=3, api_key="your-api-key-here" ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.