### Complete Gree Climate Discovery and Connection Example Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/discovery.md A full example demonstrating how to set up a custom listener, scan for devices, connect to a discovered device, and retrieve its state. This snippet requires asyncio, Discovery, Listener, DeviceInfo, and Device imports. ```python import asyncio from greeclimate.discovery import Discovery, Listener from greeclimate.deviceinfo import DeviceInfo from greeclimate.device import Device class MyListener(Listener): """Custom listener to handle discovery events.""" async def device_found(self, device_info: DeviceInfo) -> None: print(f"New device found: {device_info.name}") print(f" Address: {device_info.ip}:{device_info.port}") print(f" MAC: {device_info.mac}") print(f" Model: {device_info.model}") async def device_update(self, device_info: DeviceInfo) -> None: print(f"Device {device_info.name} moved to {device_info.ip}") async def main(): # Create discovery manager discovery = Discovery(timeout=5) # Add listener for events listener = MyListener() discovery.add_listener(listener) # Scan for 10 seconds print("Scanning for devices...") devices = await discovery.scan(wait_for=10) print(f"\nFound {len(devices)} device(s):") # Connect to first discovered device if devices: device_info = devices[0] print(f"\nConnecting to {device_info.name}...") device = Device(device_info) try: await device.bind() await device.update_state() print(f"Power: {device.power}") print(f"Temperature: {device.current_temperature}°C") except Exception as e: print(f"Failed to connect: {e}") asyncio.run(main()) ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/cmroche/greeclimate/blob/master/AGENTS.md Installs project dependencies and testing tools in an isolated virtual environment. ```bash python -m venv .venv source .venv/bin/activate pip install -r requirements.txt pip install flake8 pytest pytest-asyncio pytest-cov ``` -------------------------------- ### Basic Device Control with Gree Climate Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/README.md Discover, bind, and control a Gree device. This example shows how to get the current state and push updates for power, mode, and target temperature. ```python import asyncio from greeclimate.discovery import Discovery from greeclimate.device import Device, Mode async def main(): # Discover devices discovery = Discovery(timeout=5) devices = await discovery.scan(wait_for=5) if not devices: print("No devices found") return # Connect to first device device = Device(devices[0]) await device.bind() # Get current state await device.update_state() print(f"Power: {device.power}, Temp: {device.current_temperature}°C") # Change state device.power = True device.mode = Mode.Cool device.target_temperature = 24 await device.push_state_update() asyncio.run(main()) ``` -------------------------------- ### Complete Gree Climate Device Configuration Example Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md This example demonstrates how to discover, bind, configure, and control a Gree climate device using the greeclimate library. It covers setting temperature units, target temperature, mode, fan speed, and various features. Ensure logging is configured and asyncio is used for asynchronous operations. ```python import asyncio import logging from greeclimate.device import Device, Mode, FanSpeed, TemperatureUnits from greeclimate.deviceinfo import DeviceInfo from greeclimate.discovery import Discovery from greeclimate.cipher import CipherV1 # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) async def main(): # Discovery configuration discovery = Discovery(timeout=5, allow_loopback=False) # Scan for devices print("Scanning for devices...") devices = await discovery.scan(wait_for=5) if not devices: print("No devices found") return # Device configuration from discovered device device_info = devices[0] # Create device with custom timeouts device = Device( device_info, timeout=120, # 2 minutes for normal operations bind_timeout=10 # 10 seconds for binding ) try: # Bind device await device.bind() # Get initial state await device.update_state() # Configure device settings device.temperature_units = TemperatureUnits.C device.target_temperature = 23 device.mode = Mode.Cool device.fan_speed = FanSpeed.Auto # Configure features device.power = True device.fresh_air = True device.quiet = False device.turbo = False device.power_save = True # Configure blade positions device.horizontal_swing = 1 # Full swing device.vertical_swing = 1 # Full swing # Send all changes await device.push_state_update() # Get updated state await device.update_state() print(f"Device configured successfully") print(f"Current temperature: {device.current_temperature}°C") print(f"Target temperature: {device.target_temperature}°C") except Exception as e: print(f"Error: {e}") asyncio.run(main()) ``` -------------------------------- ### Complete Error Handling Example in Python Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/errors.md Demonstrates how to handle various exceptions like DeviceNotBoundError, DeviceTimeoutError, and ValueError when interacting with Gree devices. This example covers device discovery, binding, state updates, and command pushing. ```python import asyncio from greeclimate.device import Device, Mode, TemperatureUnits from greeclimate.deviceinfo import DeviceInfo from greeclimate.discovery import Discovery from greeclimate.exceptions import DeviceNotBoundError, DeviceTimeoutError async def main(): discovery = Discovery(timeout=5) devices = await discovery.scan(wait_for=5) if not devices: print("No devices found") return device_info = devices[0] device = Device(device_info, timeout=120, bind_timeout=10) try: # Try to bind print(f"Binding to {device_info.name}...") await device.bind() # Get initial state print("Fetching device state...") await device.update_state() print(f"Power: {device.power}") print(f"Temperature: {device.current_temperature}°C") # Try to change state device.power = True device.mode = Mode.Cool device.target_temperature = 24 print("Sending commands...") await device.push_state_update() print("Success!") except DeviceNotBoundError: print(f"Failed: Could not bind to {device_info.name}") print("Possible causes:") print(" - Device is too far from network") print(" - Device was recently powered on (try again in a few seconds)") print(" - Device not in pairing mode") except DeviceTimeoutError: print(f"Failed: {device_info.name} did not respond") print("Possible causes:") print(" - Network connectivity issue") print(" - Device is powered off") print(" - Device IP address is incorrect") print(" - Timeout is too short for slow network") except ValueError as e: print(f"Invalid configuration: {e}") print("Check temperature/humidity values are within valid ranges") except Exception as e: print(f"Unexpected error: {type(e).__name__}: {e}") asyncio.run(main()) ``` -------------------------------- ### Complete Usage Example of Taskable Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/taskable.md Example demonstrating how to use the Taskable mixin in a custom class to manage background tasks for event processing. ```python import asyncio from greeclimate.taskable import Taskable class EventBus(Taskable): """Example of a class using Taskable to manage background tasks.""" def __init__(self): Taskable.__init__(self) self.events = [] async def process_event(self, event): """Process an event asynchronously.""" await asyncio.sleep(0.1) self.events.append(event) print(f"Processed: {event}") def emit(self, event): """Emit an event to be processed in background.""" self._create_task(self.process_event(event)) async def main(): bus = EventBus() # Emit multiple events bus.emit("event1") bus.emit("event2") bus.emit("event3") print(f"Created {len(bus.tasks)} tasks") # Wait for all tasks to complete await asyncio.gather(*bus.tasks, return_exceptions=True) print(f"All tasks complete") print(f"Processed events: {bus.events}") asyncio.run(main()) ``` -------------------------------- ### Example Device Configurations Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Illustrates various ways to initialize a Device object with different timeout and event loop configurations. ```python from greeclimate.device import Device from greeclimate.deviceinfo import DeviceInfo # Standard configuration device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "Living Room AC") device = Device(device_info) ``` ```python # Fast timeouts for responsive networks device = Device(device_info, timeout=30, bind_timeout=5) ``` ```python # Slow network configuration device = Device(device_info, timeout=180, bind_timeout=15) ``` ```python # Custom event loop import asyncio loop = asyncio.new_event_loop() device = Device(device_info, loop=loop) ``` -------------------------------- ### Install Dependencies Source: https://github.com/cmroche/greeclimate/blob/master/README.md Installs the necessary Python packages required for the project, typically from a requirements file. ```bash pip install -r requirements.txt ``` -------------------------------- ### API Reference Structure Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/MANIFEST.txt This documentation is structured to guide users through the GreeClimate library's API. Start with the README for an overview, then refer to specific class files for detailed documentation, and consult types.md for enums and constants. ```APIDOC ## How to Use This Documentation 1. **README.md**: Overview and quick reference. 2. **api-reference/{class}.md**: Specific class documentation. 3. **types.md**: Enum values and constants. 4. **configuration.md**: Configuration options. 5. **errors.md**: Error handling and exceptions. Each file contains complete method/property documentation, required parameters and types, working examples, and source code location references. ``` -------------------------------- ### Complete Device Communication Example Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/network.md Demonstrates a full cycle of device communication, including binding, sending commands, and receiving responses. Requires asyncio and specific device information. ```python import asyncio from greeclimate.network import DeviceProtocol2, Commands, Response from greeclimate.deviceinfo import DeviceInfo from greeclimate.cipher import CipherV1 class MyProtocol(DeviceProtocol2): def packet_received(self, obj, addr): print(f"Received from {addr}: {obj}") async def main(): # Create protocol loop = asyncio.get_event_loop() protocol_factory = MyProtocol() # Create UDP endpoint transport, _ = await loop.create_datagram_endpoint( lambda: protocol_factory, remote_addr=("192.168.1.100", 7000) ) # Create device info device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "AC") # Create binding message bind_msg = protocol_factory.create_bind_message(device_info) # Send with cipher cipher = CipherV1() await protocol_factory.send(bind_msg, cipher=cipher) # Wait for binding await protocol_factory.ready.wait() # Now send a command cmd_msg = protocol_factory.create_command_message(device_info, Pow=1) await protocol_factory.send(cmd_msg) transport.close() asyncio.run(main()) ``` -------------------------------- ### Complete Cipher Usage Example Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/cipher.md Demonstrates encryption and decryption using CipherV1 and CipherV2. Shows encryption with and without a device key for CipherV1, and encryption with an authentication tag for CipherV2. Requires asyncio to run. ```python import asyncio from greeclimate.cipher import CipherV1, CipherV2 async def main(): # Example with CipherV1 cipher_v1 = CipherV1() # Encrypt a command data = {"t": "cmd", "opt": ["Pow"], "p": [1]} encrypted, tag = cipher_v1.encrypt(data) print(f"CipherV1 Encrypted: {encrypted}") # Set device key (from binding process) cipher_v1.key = "device_specific_key_abc123xyz" # Encrypt with device key encrypted_device, _ = cipher_v1.encrypt(data) print(f"CipherV1 with device key: {encrypted_device}") # Example with CipherV2 cipher_v2 = CipherV2() cipher_v2.key = "device_specific_key_abc123xyz" # Encrypt with authentication tag encrypted, auth_tag = cipher_v2.encrypt(data) print(f"CipherV2 Encrypted: {encrypted}") print(f"CipherV2 Auth Tag: {auth_tag}") # Decrypt decrypted = cipher_v2.decrypt(encrypted) print(f"Decrypted: {decrypted}") asyncio.run(main()) ``` -------------------------------- ### Complete Gree Climate Device Usage Example Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Demonstrates connecting to a Gree Climate device, updating its state, and sending commands to change settings like power, mode, temperature, and fan speed. ```python import asyncio from greeclimate.device import Device, Mode, FanSpeed, TemperatureUnits from greeclimate.deviceinfo import DeviceInfo from greeclimate.cipher import CipherV1 async def main(): # Create device device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "Living Room AC") device = Device(device_info) # Bind to device (auto-detect cipher) await device.bind() # Update state from device await device.update_state() # Check current state if device.power: print(f"Temperature: {device.current_temperature}°C") # Make changes device.power = True device.mode = Mode.Cool device.target_temperature = 24 device.fan_speed = FanSpeed.Auto # Send updates to device await device.push_state_update() asyncio.run(main()) ``` -------------------------------- ### Configuration Options Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/MANIFEST.txt Reference for configuration parameters and options for initializing and using the GreeClimate library, including device settings, discovery options, and cipher setup. ```APIDOC ## Configuration Options ### Description This section details the various configuration parameters available for the GreeClimate library. It covers options for initializing the `Device`, `Discovery`, and `DeviceInfo` classes, as well as settings for cipher configuration, property ranges, environment variable usage, and recommended timeout values. ### Configuration Areas #### Device Constructor Parameters - Parameters used when creating an instance of the `Device` class. #### Discovery Initialization Options - Options to configure the behavior of the `Discovery` class during network scanning. #### DeviceInfo Configuration - Settings related to how device information is handled and persisted. #### Cipher Setup and Keys - Parameters for configuring encryption, including specifying keys or key management strategies. #### Property Valid Ranges - Documentation on the valid ranges for various device properties, as referenced in `types.md`. #### Environment Variable Usage - Information on how environment variables can be used to override or set configuration values. #### Timeout Recommendations - Guidance on setting appropriate timeout values for network operations to ensure reliability. ### Examples - **Environment-based configuration** - **Timeout tuning** ``` -------------------------------- ### Device Class Integration with Taskable Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/taskable.md Example showing how the Device class uses Taskable to manage background tasks for device operations like state updates. It demonstrates waiting for all device-related tasks to complete. ```python from greeclimate.device import Device from greeclimate.deviceinfo import DeviceInfo device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "AC") device = Device(device_info) await device.bind() # The device's update_state() is triggered as a background task # You can wait for all device tasks to complete: await asyncio.gather(*device.tasks, return_exceptions=True) ``` -------------------------------- ### Get DeviceInfo String Representation Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/deviceinfo.md Returns a human-readable string representation of the device. Useful for logging or displaying device details. ```python def __str__(self) -> str: # ... implementation details ... pass # Example Usage: device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "Living Room") print(device_info) # Output: Device: Living Room @ 192.168.1.100:7000 (mac: aabbcc112233) ``` -------------------------------- ### Persist and Reconnect Greeclimate Device with Key Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/README.md Save the device key after binding and use it later to reconnect. This example shows how to retrieve the key and use it with a specific Cipher instance. ```python # After binding, save the key key = device.device_cipher.key # Later, reconnect with saved key from greeclimate.cipher import CipherV1 cipher = CipherV1() await device.bind(key=key, cipher=cipher) ``` -------------------------------- ### Create and Use DeviceInfo Instance Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/deviceinfo.md Demonstrates how to create a DeviceInfo instance with all its attributes and how to use it with the Device class. Also shows how to compare two DeviceInfo objects to detect changes. ```python from greeclimate.deviceinfo import DeviceInfo from greeclimate.device import Device # Create a DeviceInfo instance device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aa:bb:cc:11:22:33", name="Living Room AC", brand="Gree", model="GWH18QE-K6DNA1A", version="V3.31" ) # Print device information print(device_info) # Output: Device: Living Room AC @ 192.168.1.100:7000 (mac: aa:bb:cc:11:22:33) # Use with Device class device = Device(device_info) # Check if device info has changed old_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "AC1") new_info = DeviceInfo("192.168.1.101", 7000, "aabbcc112233", "AC1") if old_info == new_info: print("Same device (moved to new IP)") else: print("Different device") ``` -------------------------------- ### Initialize DeviceInfo with Full Configuration Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Instantiate a DeviceInfo object with all available parameters, including brand, model, and version, typically obtained from device discovery. ```python device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aa:bb:cc:11:22:33", name="Living Room AC", brand="Gree", model="GWH18QE-K6DNA1A", version="V3.31" ) ``` -------------------------------- ### Get List of Outstanding Tasks Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/taskable.md Get the list of outstanding tasks waiting for completion. This list is updated automatically as tasks complete and are removed. ```python task1 = handler._create_task(some_operation()) task2 = handler._create_task(another_operation()) print(f"Pending tasks: {len(handler.tasks)}") # Wait for all to complete await asyncio.gather(*handler.tasks, return_exceptions=True) ``` -------------------------------- ### Initialize DeviceInfo with Minimal Configuration Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Create a DeviceInfo object with the essential parameters: IP address, port, MAC address, and a name. ```python device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aabbcc112233", name="AC Unit" ) ``` -------------------------------- ### Initialize DeviceInfo from Environment Variables Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Configure a DeviceInfo object by retrieving connection details from environment variables, with fallback defaults. ```python import os device_info = DeviceInfo( ip=os.getenv("AC_IP", "192.168.1.100"), port=int(os.getenv("AC_PORT", 7000)), mac=os.getenv("AC_MAC", "aabbcc112233"), name=os.getenv("AC_NAME", "AC Unit") ) ``` -------------------------------- ### temperature_units Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the temperature unit mode, choosing between Celsius and Fahrenheit. ```APIDOC ## Property: temperature_units ### Description Get/set the temperature unit mode. ### Type `int | None` ### Accepted Values Accepts values from the `TemperatureUnits` enum: - `TemperatureUnits.C` (0): Celsius - `TemperatureUnits.F` (1): Fahrenheit ``` -------------------------------- ### CipherV1.key Property Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/cipher.md Allows getting and setting the encryption key. The key can be managed as a string. ```APIDOC ## CipherV1.key Property ### Description Get the encryption key as a string. ### Parameters #### Path Parameters - **value** (str) - Required - The key as a UTF-8 string ### Response #### Success Response (200) - **str** - The encryption key in UTF-8 string format ### Request Example ```python cipher = CipherV1() cipher.key = "negotiated_device_key_123abc" encrypted, _ = cipher.encrypt({"t": "cmd", "opt": ["Pow"]}) ``` ``` -------------------------------- ### Initialize DeviceInfo Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/deviceinfo.md Instantiate DeviceInfo with essential network parameters and optional device details. The MAC address can be provided with or without colons. ```python from greeclimate.deviceinfo import DeviceInfo # Basic device info from discovery device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aabbcc112233", name="Living Room AC" ) ``` ```python # Complete device info with all fields device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aa:bb:cc:11:22:33", name="Living Room AC", brand="Gree", model="GWH18QE-K6DNA1A", version="V3.31" ) ``` -------------------------------- ### clean_filter Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get the filter cleaning indicator. This read-only property is true if the filter needs cleaning. ```APIDOC ## clean_filter ### Description Get the filter cleaning indicator. ### Type bool | None ### Details Read-only. True indicates the filter needs cleaning. ### Source greeclimate/device.py:590 ``` -------------------------------- ### Initialize Discovery with Default Parameters Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Instantiate the Discovery class with default settings for timeout, loopback inclusion, and event loop. ```python discovery = Discovery() ``` -------------------------------- ### quiet Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set quiet mode, which enables low-noise operation by reducing fan speed. ```APIDOC ## Property: quiet ### Description Get/set quiet mode (low-noise operation). ### Type `int | None` *When enabled, the device operates at reduced fan speed to minimize noise.* ``` -------------------------------- ### vertical_swing Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the vertical blade position or swing. Accepts values from the `VerticalSwing` enum. ```APIDOC ## Property: vertical_swing ### Description Get/set the vertical blade position/swing. ### Type `int | None` ### Accepted Values Accepts values from the `VerticalSwing` enum: - `VerticalSwing.Default` (0) - `VerticalSwing.FullSwing` (1) - `VerticalSwing.FixedUpper` (2) - `VerticalSwing.FixedUpperMiddle` (3) - `VerticalSwing.FixedMiddle` (4) - `VerticalSwing.FixedLowerMiddle` (5) - `VerticalSwing.FixedLower` (6) - `VerticalSwing.SwingUpper` (7) - `VerticalSwing.SwingUpperMiddle` (8) - `VerticalSwing.SwingMiddle` (9) - `VerticalSwing.SwingLowerMiddle` (10) - `VerticalSwing.SwingLower` (11) ``` -------------------------------- ### horizontal_swing Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the horizontal blade position or swing. Accepts values from the `HorizontalSwing` enum. ```APIDOC ## Property: horizontal_swing ### Description Get/set the horizontal blade position/swing. ### Type `int | None` ### Accepted Values Accepts values from the `HorizontalSwing` enum: - `HorizontalSwing.Default` (0) - `HorizontalSwing.FullSwing` (1) - `HorizontalSwing.Left` (2) - `HorizontalSwing.LeftCenter` (3) - `HorizontalSwing.Center` (4) - `HorizontalSwing.RightCenter` (5) - `HorizontalSwing.Right` (6) ``` -------------------------------- ### Discover All Greeclimate Devices Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/README.md Instantiate the Discovery class and scan the network for devices. The scan returns a list of DeviceInfo objects. ```python discovery = Discovery(timeout=5) devices = await discovery.scan(wait_for=10) for device_info in devices: print(f"{device_info.name}: {device_info.ip}:{device_info.port}") ``` -------------------------------- ### light Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the front panel light. This property is available on devices that have a display light. ```APIDOC ## Property: light ### Description Get/set the front panel light. ### Type `bool | None` *Available on devices with a display light.* ``` -------------------------------- ### sleep Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set sleep mode, which enables gradual temperature adjustment for comfort during sleep. ```APIDOC ## Property: sleep ### Description Get/set sleep mode (gradual temperature adjustment). ### Type `bool | None` *When enabled, the device gradually adjusts the temperature over time for comfort during sleep.* ``` -------------------------------- ### Handle Device Events Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/INDEX.md Sets up a listener to react to device discovery events. Implement the Listener interface to define custom event handling logic. ```python class MyListener(Listener): async def device_found(self, device_info): print(f"Found: {device_info.name}") discovery.add_listener(MyListener()) ``` -------------------------------- ### DeviceInfo Constructor Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/deviceinfo.md Initializes a DeviceInfo instance with network and identification details for a Gree HVAC unit. Supports basic and complete initialization with optional brand, model, and version information. ```APIDOC ## DeviceInfo Constructor ### Description Initializes device information for a Gree HVAC unit. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ip** (str) - Required - IPv4 address of the device - **port** (int) - Required - UDP port for communication (typically 7000) - **mac** (str) - Required - MAC address in format 'aabbcc112233' or with colons - **name** (str) - Required - Friendly name of the device; if empty, defaults to sanitized MAC - **brand** (str) - Optional - Brand name (e.g., 'Gree', 'Proklima', 'Trane') - **model** (str) - Optional - Model number or identifier - **version** (str) - Optional - Firmware version string ### Request Example ```python from greeclimate.deviceinfo import DeviceInfo # Basic device info from discovery device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aabbcc112233", name="Living Room AC" ) # Complete device info with all fields device_info = DeviceInfo( ip="192.168.1.100", port=7000, mac="aa:bb:cc:11:22:33", name="Living Room AC", brand="Gree", model="GWH18QE-K6DNA1A", version="V3.31" ) ``` ### Response #### Success Response DeviceInfo instance #### Response Example None (Instance creation) ``` -------------------------------- ### current_temperature Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get the current temperature reading from the device sensor. This is a read-only property updated by `update_state()`. ```APIDOC ## Property: current_temperature ### Description Get the current temperature reading from the device sensor. ### Type `int | None` ### Read-only Updated by `update_state()`. ``` -------------------------------- ### current_humidity Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get the current relative humidity reading from the device. This is a read-only property and is updated by the `update_state()` method. ```APIDOC ## current_humidity ### Description Get the current relative humidity reading. ### Type int | None ### Details Read-only. Updated by `update_state()`. ### Source greeclimate/device.py:586 ``` -------------------------------- ### power_save Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the power save mode. When enabled, the device reduces its power consumption during operation. ```APIDOC ## power_save ### Description Get/set power save mode. ### Type bool | None ### Details When enabled, reduces power consumption during operation. ### Source greeclimate/device.py:560 ``` -------------------------------- ### Discover and Connect to Devices Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/INDEX.md Scans for available Gree devices on the network and connects to the first one found. Requires the Discovery and Device classes. ```python discovery = Discovery() devices = await discovery.scan(wait_for=5) device = Device(devices[0]) await device.bind() ``` -------------------------------- ### fan_speed Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the fan speed. Accepts values from the `FanSpeed` enum, ranging from Auto to High. ```APIDOC ## Property: fan_speed ### Description Get/set the fan speed. ### Type `int | None` ### Accepted Values Accepts values from the `FanSpeed` enum: - `FanSpeed.Auto` (0) - `FanSpeed.Low` (1) - `FanSpeed.MediumLow` (2) - `FanSpeed.Medium` (3) - `FanSpeed.MediumHigh` (4) - `FanSpeed.High` (5) ``` -------------------------------- ### Initialize CipherV2 Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/cipher.md Instantiate the CipherV2 handler. Use the default discovery key or provide a custom 16-byte key. ```python from greeclimate.cipher import CipherV2 # Create with default discovery key cipher = CipherV2() # Create with a custom key cipher = CipherV2(key=b'your16bytekey!!') ``` -------------------------------- ### DeviceProtocolBase2.device_cipher Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/network.md Manages the encryption cipher used for device communication. Allows getting and setting the cipher instance. ```APIDOC ## device_cipher ### Description Get the encryption cipher used for device communication. ### Method Signature ```python @property def device_cipher(self) -> CipherBase ``` ### Description Set the encryption cipher. ### Method Signature ```python @device_cipher.setter def device_cipher(self, value: CipherBase) -> None ``` ### Parameters #### Parameters - **value** (CipherBase) - CipherV1 or CipherV2 instance. ``` -------------------------------- ### ready Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/network.md Provides an asyncio Event that signals when the device has been successfully bound. This event can be awaited to synchronize operations until the device is ready. ```APIDOC ## ready ### Description Get the event that signals successful binding. ### Property Type `asyncio.Event` ### Usage Can be awaited to block until the device is bound: ```python await protocol.ready.wait() ``` ``` -------------------------------- ### Configure Device Timeouts Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/errors.md Shows how to set custom `timeout` and `bind_timeout` values when initializing a `Device` object. Adjusting these parameters can help manage responsiveness expectations for different device operations. ```python # Custom timeouts device = Device( device_info, timeout=120, # 2 minutes for normal operations bind_timeout=10 # 10 seconds for binding ) # Note: binding_timeout should be short to prevent delays in cipher detection ``` -------------------------------- ### dehumidifier_mode Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get the dehumidifier mode setting. Accepts values from the `DehumidifierMode` enum, such as `Default` (0) or `AnionOnly` (9). ```APIDOC ## dehumidifier_mode ### Description Get the dehumidifier mode setting. ### Type int | None ### Details Accepts values from the `DehumidifierMode` enum: - `DehumidifierMode.Default` (0) - `DehumidifierMode.AnionOnly` (9) ### Source greeclimate/device.py:582 ``` -------------------------------- ### anion Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the anion (ozone generator) feature. This property is available on devices that support this specific feature. ```APIDOC ## Property: anion ### Description Get/set the anion (ozone generator) feature. ### Type `bool | None` *Available on devices that support this feature.* ``` -------------------------------- ### Initialize Discovery with Custom Event Loop Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Provide a custom asyncio event loop for asynchronous operations when initializing the Discovery class. If not provided, the current running loop is used. ```python import asyncio loop = asyncio.new_event_loop() discovery = Discovery(timeout=5, loop=loop) ``` -------------------------------- ### target_temperature Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the target temperature for the device. The valid range depends on the temperature units (Celsius or Fahrenheit). ```APIDOC ## Property: target_temperature ### Description Get/set the target temperature for the device. ### Type `int | None` ### Valid Range Depends on temperature units: - Celsius: 8–30 °C - Fahrenheit: 46–86 °F *Note: When in `TemperatureUnits.F` mode, the internal representation converts to Celsius and back for device communication.* ### Raises `ValueError` if temperature is out of valid range ### Example ```python device.temperature_units = TemperatureUnits.C device.target_temperature = 24 ``` ``` -------------------------------- ### water_full Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get the water tank full indicator for dehumidifier units. This read-only property is true if the water tank is full. ```APIDOC ## water_full ### Description Get the water tank full indicator. ### Type bool | None ### Details Read-only. True indicates the water tank is full (for dehumidifier units). ### Source greeclimate/device.py:595 ``` -------------------------------- ### Initialize Discovery Manager Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/discovery.md Instantiate the Discovery manager with custom timeout and loopback settings. The timeout parameter controls the duration of scan requests. ```python from greeclimate.discovery import Discovery discovery = Discovery(timeout=5) ``` -------------------------------- ### fresh_air Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the fresh air valve state, if supported by the device. Can be set to open (`True`) or closed (`False`). ```APIDOC ## Property: fresh_air ### Description Get/set the fresh air valve state (if supported). ### Type `bool | None` - `True`: Fresh air valve is open - `False`: Fresh air valve is closed ``` -------------------------------- ### Initialize Discovery Including Loopback Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Enable the inclusion of the loopback interface (127.0.0.1) in network scans by setting allow_loopback to True. ```python discovery = Discovery(allow_loopback=True) ``` -------------------------------- ### Configure Greeclimate Device with Environment Variables Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/configuration.md Read device connection details like IP, port, MAC, name, and timeouts from environment variables. Provides default values if variables are not set. This is useful for flexible deployment in different environments. ```python import os from greeclimate.device import Device from greeclimate.deviceinfo import DeviceInfo # Read from environment ac_ip = os.getenv("GREE_AC_IP", "192.168.1.100") ac_port = int(os.getenv("GREE_AC_PORT", 7000)) ac_mac = os.getenv("GREE_AC_MAC", "aabbcc112233") ac_name = os.getenv("GREE_AC_NAME", "AC Unit") ac_timeout = int(os.getenv("GREE_AC_TIMEOUT", 120)) ac_bind_timeout = int(os.getenv("GREE_AC_BIND_TIMEOUT", 10)) # Create device device_info = DeviceInfo(ac_ip, ac_port, ac_mac, ac_name) device = Device(device_info, timeout=ac_timeout, bind_timeout=ac_bind_timeout) ``` -------------------------------- ### power Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the power state of the unit. This property controls whether the device is powered on or off. The state can also be unknown. ```APIDOC ## Property: power ### Description Get/set the power state of the unit. ### Type `bool | None` - `True`: Unit is powered on - `False`: Unit is powered off - `None`: State unknown ### Example ```python device.power = True await device.push_state_update() ``` ``` -------------------------------- ### Connect to a Greeclimate Device Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/README.md Create a Device instance using DeviceInfo and bind to it. The bind method automatically detects the cipher type. ```python device = Device(device_info, timeout=120, bind_timeout=10) await device.bind() # Auto-detect CipherV1 or CipherV2 ``` -------------------------------- ### buzzer Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the device buzzer/beeper control. Setting this to false disables the beeper for the next command sent. Defaults to true. ```APIDOC ## buzzer ### Description Get/set the device buzzer/beeper control. ### Type bool ### Details When False, the next command sent will disable the beeper for that operation. Defaults to True. ### Source greeclimate/device.py:600 ``` -------------------------------- ### Device Constructor Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Initializes a Device object for communication with a Gree HVAC unit. It requires device information and allows configuration of communication timeouts and the event loop. ```APIDOC ## Device Constructor ### Description Initialize a device object for communication with a Gree HVAC unit. ### Signature ```python Device(device_info: DeviceInfo, timeout: int = 120, bind_timeout: int = 10, loop: AbstractEventLoop = None) ``` ### Parameters #### Path Parameters - **device_info** (DeviceInfo) - Required - Information about the physical device including IP, port, and MAC address - **timeout** (int) - Optional - Timeout in seconds for device communication requests (Default: 120) - **bind_timeout** (int) - Optional - Timeout in seconds for binding operations; keep short to prevent delays in cipher detection (Default: 10) - **loop** (AbstractEventLoop) - Optional - The event loop to run device operations on; if None, uses the current running loop or creates a new one (Default: None) ### Returns - Device instance ### Raises - `DeviceNotBoundError`: If device operations are attempted before binding ### Example ```python from greeclimate.device import Device from greeclimate.deviceinfo import DeviceInfo device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "Living Room AC") device = Device(device_info, timeout=120) ``` ``` -------------------------------- ### Configure Discovery Parameters Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/README.md Customize discovery parameters, including the timeout for responses and whether to allow loopback interfaces. This helps optimize the device discovery process. ```python discovery = Discovery( timeout=5, # Wait 5 seconds for responses allow_loopback=False # Skip loopback interface ) ``` -------------------------------- ### raw_properties Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get the raw dictionary of all property values. Keys are property names from the Props enum, and values are their current cached values. ```APIDOC ## raw_properties ### Description Get the raw dictionary of all property values. ### Type dict ### Details Keys are property names from the Props enum, values are their current cached values. ### Source greeclimate/device.py:357 ``` -------------------------------- ### target_humidity Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the target relative humidity. This property applies to units capable of dehumidification and accepts integer values between 30 and 80%. ```APIDOC ## target_humidity ### Description Get/set the target relative humidity. ### Type int | None ### Details Valid range: 30–80% Applies to dehumidifier-capable units. ### Source greeclimate/device.py:569 ``` -------------------------------- ### Initialize Gree Device Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Instantiate a Device object for communication with a Gree HVAC unit. Ensure DeviceInfo is correctly populated with IP, port, and MAC address. Adjust timeouts as needed for your network conditions. ```python from greeclimate.device import Device from greeclimate.deviceinfo import DeviceInfo device_info = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "Living Room AC") device = Device(device_info, timeout=120) ``` -------------------------------- ### __eq__ Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/deviceinfo.md Compares two DeviceInfo objects for equality. Devices are considered equal if they share the same MAC address, name, brand, model, and version. IP address and port are ignored. ```APIDOC ## __eq__ ### Description Compare two DeviceInfo objects for equality. Two devices are equal if they have the same MAC address, name, brand, model, and version. ### Parameters #### Path Parameters - **other** (object) - Required - Another DeviceInfo instance to compare ### Returns `bool` — True if all identifying fields match, False otherwise ### Example ```python info1 = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "AC1", "Gree", "Model1") info2 = DeviceInfo("192.168.1.101", 7000, "aabbcc112233", "AC1", "Gree", "Model1") info3 = DeviceInfo("192.168.1.100", 7000, "ddeeff445566", "AC2", "Gree", "Model2") print(info1 == info2) # True (IP can differ) print(info1 == info3) # False (different MAC/name) ``` Note: IP address and port are NOT used in equality comparison, allowing for devices that move to different network addresses. ``` -------------------------------- ### steady_heat Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the steady heat mode. When enabled, it maintains a target temperature of 8 °C, primarily used for frost prevention. ```APIDOC ## steady_heat ### Description Get/set steady heat mode. ### Type bool | None ### Details When enabled, maintains a target temperature of 8 °C (used for frost prevention). ### Source greeclimate/device.py:551 ``` -------------------------------- ### Initialize Taskable Mixin Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/taskable.md Initialize the Taskable mixin. Use the current running loop or create a new one if none is provided. ```python import asyncio from greeclimate.taskable import Taskable class MyHandler(Taskable): def __init__(self): Taskable.__init__(self) ``` -------------------------------- ### turbo Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the turbo mode for rapid heating or cooling. When enabled, the device operates at maximum capacity for faster temperature changes. ```APIDOC ## turbo ### Description Get/set turbo mode (rapid heating/cooling). ### Type bool | None ### Details When enabled, the device operates at maximum capacity for faster temperature change. ### Source greeclimate/device.py:542 ``` -------------------------------- ### mode Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Get or set the operating mode of the unit. Accepts values from the `Mode` enum, including Auto, Cool, Dry, Fan, and Heat. ```APIDOC ## Property: mode ### Description Get/set the operating mode of the unit. ### Type `int | None` ### Accepted Values Accepts values from the `Mode` enum: - `Mode.Auto` (0) - `Mode.Cool` (1) - `Mode.Dry` (2) - `Mode.Fan` (3) - `Mode.Heat` (4) ``` -------------------------------- ### Get Device Property Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/device.md Retrieves a specific property value from the device's current state using an Enum member from the Props class. ```python power = device.get_property(Props.POWER) temp = device.get_property(Props.TEMP_SENSOR) ``` -------------------------------- ### DeviceProtocolBase2.device_key Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/network.md Manages the encryption key string used for device communication. Allows getting and setting the key, with checks to ensure the cipher is set. ```APIDOC ## device_key ### Description Get the encryption key string. ### Method Signature ```python @property def device_key(self) -> str ``` ### Raises - `ValueError`: If cipher not set. ### Description Set the encryption key string. ### Method Signature ```python @device_key.setter def device_key(self, value: str) -> None ``` ### Parameters #### Parameters - **value** (str) - Encryption key string. ### Raises - `ValueError`: If cipher not set. ``` -------------------------------- ### Discovery Constructor Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/discovery.md Initializes the Discovery class, which manages network scanning for Gree devices. You can configure the timeout for responses and whether to include the loopback interface in scans. ```APIDOC ## Discovery Constructor ### Description Initialize the device discovery manager. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```python Discovery(timeout: int = 2, allow_loopback: bool = False, loop: AbstractEventLoop = None) ``` ### Parameters - **timeout** (int) - Optional - Wait this many seconds for device responses to scan requests. Default: 2. - **allow_loopback** (bool) - Optional - Whether to allow scanning the loopback/localhost interface. Default: False. - **loop** (AbstractEventLoop) - Optional - The async event loop to use; if None, uses the current running loop or creates a new one. Default: None. ### Returns Discovery instance ### Example ```python from greeclimate.discovery import Discovery discovery = Discovery(timeout=5) ``` ``` -------------------------------- ### Compare DeviceInfo Objects for Equality Source: https://github.com/cmroche/greeclimate/blob/master/_autodocs/api-reference/deviceinfo.md Compares two DeviceInfo objects for equality based on MAC address, name, brand, model, and version. IP address and port are ignored in the comparison. ```python def __eq__(self, other) -> bool: # ... implementation details ... pass # Example Usage: info1 = DeviceInfo("192.168.1.100", 7000, "aabbcc112233", "AC1", "Gree", "Model1") info2 = DeviceInfo("192.168.1.101", 7000, "aabbcc112233", "AC1", "Gree", "Model1") info3 = DeviceInfo("192.168.1.100", 7000, "ddeeff445566", "AC2", "Gree", "Model2") print(info1 == info2) # True (IP can differ) print(info1 == info3) # False (different MAC/name) ```