Metadata-Version: 2.4
Name: pysaunum
Version: 0.8.0
Summary: Python library for controlling Saunum sauna controllers via Modbus
Author-email: Mario Mett <mario@mett.ee>
License-Expression: MIT
Project-URL: Homepage, https://github.com/mettolen/pysaunum
Project-URL: Repository, https://github.com/mettolen/pysaunum
Project-URL: Issues, https://github.com/mettolen/pysaunum/issues
Keywords: saunum,sauna,modbus,home-automation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Classifier: Topic :: Home Automation
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pymodbus>=3.11.2
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-timeout>=2.1.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Dynamic: license-file

# pysaunum

[![CI](https://github.com/mettolen/pysaunum/actions/workflows/ci.yml/badge.svg)](https://github.com/mettolen/pysaunum/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/mettolen/pysaunum/branch/main/graph/badge.svg)](https://codecov.io/gh/mettolen/pysaunum)
[![PyPI version](https://badge.fury.io/py/pysaunum.svg)](https://badge.fury.io/py/pysaunum)
[![PyPI Downloads](https://img.shields.io/pypi/dm/pysaunum.svg)](https://pypi.org/project/pysaunum/)
[![Python versions](https://img.shields.io/pypi/pyversions/pysaunum.svg)](https://pypi.org/project/pysaunum/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Python library for controlling [Saunum](https://saunum.com/) sauna controllers via Modbus TCP.

---

This library is used by the [Saunum](https://www.home-assistant.io/integrations/saunum) Home Assistant integration.

<a href="https://www.home-assistant.io/integrations/saunum/" target="_blank"><img alt="Dynamic Regex Badge" src="https://img.shields.io/badge/dynamic/regex?url=https%3A%2F%2Fwww.home-assistant.io%2Fintegrations%2Fsaunum%2F&search=(%5B%5Cd%2C%5D%2B)%5Cs*%3C%2Fa%3E%5Cs*active%20installations&replace=%241&style=for-the-badge&logo=homeassistant&label=Active%20installations&labelColor=%23f2f4f9&color=%2346bdf4"></a> <a href="https://www.home-assistant.io/docs/quality_scale/" target="_blank"><img alt="Dynamic Regex Badge" src="https://img.shields.io/badge/dynamic/regex?url=https%3A%2F%2Fwww.home-assistant.io%2Fintegrations%2Fsaunum%2F&search=%3Ca%20href%3D'%5B%5E'%5D*quality_scale%5B%5E'%5D*'%3E(%5B%5E%3C%5D%2B%3F)%20quality%3C%2Fa%3E&replace=%241&style=for-the-badge&logo=homeassistant&label=Quality%20scale&labelColor=%23f2f4f9&color=%2346bdf4"></a> <a href="https://my.home-assistant.io/redirect/config_flow_start?domain=saunum" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/Saunum-i?style=for-the-badge&logo=homeassistant&label=Add%20integration&labelColor=%23f2f4f9&color=%2346bdf4"></a>

## Features

- 🔌 **Async/await support** using asyncio with comprehensive error handling
- 🏠 **Sauna preset** configuration using device-dependent, 0-indexed values
- 🌡️ **Temperature control** with zero-value support (40-100°C range, 0 = type defined)
- ⏱️ **Session management** with configurable duration (60-1080 minutes, default 120, 0 = type defined)
- ⏲️ **Fan duration** control (0-20 minutes, 0 = type defined)
- 💨 **Fan control** with discrete speeds (0=Default/Off, 1=Low, 2=Medium, 3=High)
- 🧊 **Controller state monitoring** (standby, scheduled, heating, ready, cooldown, waiting for door)
- 💡 **Light control** for sauna lighting
- 🛠️ **Controller actions** for software restart, closing cooldown, and dismissing notifications
- 💧 **AutoLeil control** for humidity/interval modes, water throws, ventilation, and button settings
- 🔆 **Infrared control** with intensity levels 1-10 and IR mode monitoring
- 🔥 **Heater monitoring** with element count (0-3 active elements)
- 🚨 **Alarm status** monitoring (door, temperature, sensor, and power-unit alarms)
- 🛡️ **Type hints** for better IDE support and development experience
- 📊 **Comprehensive data model** with typed fields, enums, and bit-flag masks

## Installation

```bash
pip install pysaunum
```

## Quick Start

### Using Factory Method (Recommended)

The factory method automatically establishes a connection before returning the client:

```python
import asyncio
from pysaunum import SaunumClient, SaunumConnectionError

async def main():
    try:
        # Create and connect - client is ready to use immediately
        client = await SaunumClient.create("192.168.1.100")

        # Read current state
        data = await client.async_get_data()
        print(f"Current temperature: {data.current_temperature}°C")
        print(f"Target temperature: {data.target_temperature}°C")
        print(f"Session active: {data.session_active}")
        print(f"Controller state: {data.controller_state.name}")
        print(f"Heater elements active: {data.heater_elements_active}")

        # Start a sauna session with configuration
        await client.async_set_target_temperature(80)  # Set to 80°C
        await client.async_set_sauna_duration(120)     # 2 hours
        await client.async_set_fan_speed(2)            # Medium fan
        await client.async_start_session()

        # Stop the session when done
        await client.async_stop_session()

    except SaunumConnectionError as err:
        print(f"Connection error: {err}")
    finally:
        # Close connection
        await client.async_close()

asyncio.run(main())
```

### Traditional Method

You can also create and connect manually:

```python
import asyncio
from pysaunum import SaunumClient, SaunumConnectionError

async def main():
    # Create client - replace with your sauna controller's IP
    client = SaunumClient(host="192.168.1.100", port=502, device_id=1)

    try:
        # Must explicitly connect before using
        await client.connect()

        # Read current state
        data = await client.async_get_data()
        print(f"Current temperature: {data.current_temperature}°C")

    except SaunumConnectionError as err:
        print(f"Connection error: {err}")
    finally:
        # Close connection
        await client.async_close()

asyncio.run(main())
```

## Connection and Polling Guidance

Saunum controllers use Modbus TCP port **502** by default. When scheduling reads and writes:

- Allow at least **500 ms** between Modbus requests; **1000 ms** is recommended.
- Low-traffic applications may poll every **2-5 seconds**.
- Use a request timeout of at least **2 seconds**. The client default is 10 seconds.
- Read at least once every **5-10 seconds** to keep the connection alive.
- The control panel closes an idle connection after **20 seconds**.

## Context Manager Usage (Recommended)

```python
import asyncio
from pysaunum import SaunumClient
from pysaunum.const import FanSpeed, SaunaType

async def main():
    try:
        # Using async context manager automatically handles connection cleanup
        async with SaunumClient(host="192.168.1.100") as client:
            # Configure sauna
            await client.async_set_sauna_type(SaunaType.TYPE_2)  # Type 2 sauna
            await client.async_set_target_temperature(85)
            await client.async_set_fan_speed(FanSpeed.HIGH)

            # Start session
            await client.async_start_session()

            # Read updated state
            data = await client.async_get_data()
            print(f"Session started: {data.session_active}")
            print(f"Heater elements: {data.heater_elements_active}/3")

    except Exception as err:
        print(f"Error: {err}")

asyncio.run(main())
```

## Available Constants

```python
from pysaunum.const import (
    # AutoLeil mode enum (IntEnum)
    AutoLeilMode,       # HUMIDITY=0, INTERVAL=1

    # Fan speed enum (IntEnum)
    FanSpeed,           # FanSpeed.OFF=0, LOW=1, MEDIUM=2, HIGH=3

    # Convenience labels for the first three preset indices
    SaunaType,          # SaunaType.TYPE_1=0, TYPE_2=1, TYPE_3=2

    # Device-reported controller state (IntEnum)
    ControllerState,    # STANDBY through WAITING_FOR_DOOR

    # Status bit masks (IntFlag)
    Notification,
    StartBlockReason,

    # Connection defaults
    DEFAULT_PORT,       # 502
    DEFAULT_DEVICE_ID,  # 1
    DEFAULT_TIMEOUT,    # 10.0 seconds

    # Limits
    MIN_TEMPERATURE,    # 40°C
    MAX_TEMPERATURE,    # 100°C
    MIN_DURATION,       # 60 minutes (minimum non-default duration)
    MAX_DURATION,       # 1080 minutes (18 hours)
    DEFAULT_DURATION,   # 120 minutes (2 hours)
    MIN_FAN_DURATION,   # 0 minutes
    MAX_FAN_DURATION,   # 20 minutes
    MIN_IR_INTENSITY,   # 1
    MAX_IR_INTENSITY,   # 10

    # AutoLeil limits
    AUTOLEIL_HUMIDITY_TEMPERATURE_SUM,  # 130 (max humidity = 130 - target temp)
    MAX_AUTOLEIL_TARGET_HUMIDITY,       # 100%
    MIN_AUTOLEIL_INTERVAL,              # 1 minute
    MAX_AUTOLEIL_INTERVAL,              # 25 minutes
    MIN_AUTOLEIL_WATER_AMOUNT,          # 3 (0.3 seconds)
    MAX_AUTOLEIL_WATER_AMOUNT,          # 40 (4.0 seconds)
    MIN_AUTOLEIL_DURATION,              # 60 minutes
    MAX_AUTOLEIL_DURATION,              # 1080 minutes
    AUTOLEIL_DURATION_STEP,             # 30 minutes
    AUTOLEIL_BUTTON_TIMEOUTS,           # (5, 15, 30, 60, 120, 180, 240, 300) seconds
)

# Fan speed values are IntEnum members
assert FanSpeed.OFF == 0
assert FanSpeed.HIGH == 3
assert 2 in FanSpeed  # Membership testing

# The available preset count is device-dependent; these are convenience labels
assert SaunaType.TYPE_1 == 0
assert SaunaType.TYPE_3 == 2
```

## API Reference

### Main Client Methods

| Method                                         | Description                 | Parameters                                         |
| ---------------------------------------------- | --------------------------- | -------------------------------------------------- |
| `async_get_data()`                             | Read all current sauna data | None                                               |
| `async_start_session()`                        | Start sauna session         | None                                               |
| `async_stop_session()`                         | Stop sauna session          | None                                               |
| `async_set_target_temperature(temp)`           | Set target temperature      | `temp: int` (0, 40-100°C)                          |
| `async_set_sauna_duration(minutes)`            | Set session duration        | `minutes: int` (0, 60-1080)                        |
| `async_set_fan_speed(speed)`                   | Set fan speed               | `speed: int` (0-3)                                 |
| `async_set_fan_duration(minutes)`              | Set fan duration            | `minutes: int` (0-20)                              |
| `async_set_sauna_type(type)`                   | Set sauna preset            | `type: int` (0 to device-dependent N-1)            |
| `async_set_light_control(enabled)`             | Control sauna light         | `enabled: bool`                                    |
| `async_set_ir_intensity(level)`                | Set infrared intensity      | `level: int` (1-10, IR mode only)                  |
| `async_restart_software()`                     | Restart controller software | None                                               |
| `async_close_cooldown()`                       | Close active cooldown       | None                                               |
| `async_dismiss_notifications()`                | Dismiss notifications       | None                                               |
| `async_set_autoleil_mode(mode)`                | Set humidity/interval mode  | `mode: int` (0-1)                                  |
| `async_set_autoleil_target_humidity(humidity)` | Set target humidity         | `humidity: int` (0 to min(100, 130-target temp))   |
| `async_set_autoleil_interval(minutes)`         | Set water throw interval    | `minutes: int` (1-25)                              |
| `async_set_autoleil_water_amount(amount)`      | Set valve-open duration     | `amount: int` (3-40, in 0.1 seconds)               |
| `async_set_autoleil_duration(minutes)`         | Set AutoLeil duration       | `minutes: int` (60-1080, step 30)                  |
| `async_set_autoleil_ready_mode(enabled)`       | Set ready mode              | `enabled: bool`                                    |
| `async_set_autoleil_auto_ventilation(enabled)` | Set auto ventilation        | `enabled: bool`                                    |
| `async_set_autoleil_button_use(enabled)`       | Enable physical button      | `enabled: bool`                                    |
| `async_set_autoleil_button_timeout(seconds)`   | Set button timeout          | `seconds: int` (5, 15, 30, 60, 120, 180, 240, 300) |

Before a session starts, fan speed `0` selects the sauna preset default and
speeds `1-3` configure the next Modbus-started session. During an active session or cooldown, `0` turns the fan off and `1-3` changes its speed.

The restart action is intended for remote recovery and temporarily interrupts the connection. Closing cooldown has no effect when cooldown is inactive. Dismissing notifications only closes dismissible on-screen messages; it does not clear active alarms or their causes.

### AutoLeil Control

AutoLeil controls require control panel firmware **1.2.5** or newer and AutoLeil firmware **1.8.2** or newer. Only use these methods when AutoLeil is connected.

```python
from pysaunum import AutoLeilMode

await client.async_set_autoleil_mode(AutoLeilMode.HUMIDITY)
await client.async_set_autoleil_target_humidity(40)
await client.async_set_autoleil_interval(10)
await client.async_set_autoleil_water_amount(10)  # 1.0 second
await client.async_set_autoleil_duration(120)
await client.async_set_autoleil_ready_mode(True)
await client.async_set_autoleil_auto_ventilation(True)
await client.async_set_autoleil_button_use(True)
await client.async_set_autoleil_button_timeout(60)
```

`async_get_data()` reads the current AutoLeil configuration from registers 10-18
into the `autoleil_*` fields. Before a session starts, these values apply to the
next Modbus-started session; during a session they reflect the active settings.
Selecting a sauna type loads that type's AutoLeil settings, so write AutoLeil
values after `async_set_sauna_type()`. Check `autoleil_connected` before relying on them.

Target humidity is validated against the current target temperature using `130 - target_temperature`, capped at 100%. When the target temperature is `0` (preset default), only the 100% cap is applied. AutoLeil duration must use 30-minute steps and cannot exceed an explicitly configured session duration. If session duration is `0` (preset default), the controller enforces the preset-specific limit.

### Infrared Control

`async_get_data()` reads infrared intensity from register **300** and IR mode
status from register **400** using separate single-register requests. These reads
are included in every data fetch; devices must support both registers.

Only set intensity when `ir_mode_active` is true. The setter validates the **1-10**
range but does not switch modes or check mode status before writing.

```python
data = await client.async_get_data()
print(f"IR mode active: {data.ir_mode_active}")
print(f"IR intensity: {data.ir_intensity}")

if data.ir_mode_active:
    await client.async_set_ir_intensity(5)
```

### Data Model (SaunumData)

```python
@dataclass(frozen=True)
class SaunumData:
    # Session control
    session_active: bool                   # Raw controller session status
    sauna_type: SaunaType | int            # Device-dependent preset index
    sauna_duration: int                    # 0 or 60-1080 minutes
    fan_duration: int                      # 0-20 minutes
    target_temperature: int                # Target temp (0=type default/cooldown)
    fan_speed: FanSpeed | None             # Fan speed enum
    light_on: bool                         # Light status

    # AutoLeil configuration (registers 10-18, meaningful when AutoLeil is connected)
    autoleil_mode: AutoLeilMode | None     # Humidity/interval mode
    autoleil_target_humidity: int          # Target humidity percentage
    autoleil_interval: int                 # Water throw interval in minutes
    autoleil_water_amount: int             # Valve-open time in 0.1 seconds
    autoleil_duration: int                 # AutoLeil duration in minutes
    autoleil_ready_mode: bool              # Start AutoLeil when sauna is ready
    autoleil_auto_ventilation: bool        # Ventilate after water dosing
    autoleil_button_use: bool              # Physical button enabled
    autoleil_button_timeout: int           # Button timeout in seconds

    # Status sensors
    current_temperature: int               # Current temp in °C
    on_time: int                           # Accumulated sauna on time in seconds
    heater_elements_active: int            # Active heater elements
    door_open: bool                        # Door status
    humidity: int                          # Relative humidity percentage
    active_session_duration: int           # Active duration in minutes
    session_time_remaining: int            # Session time remaining in seconds
    fan_time_remaining: int                # Fan time remaining in seconds
    controller_state: ControllerState      # Device-reported operating state
    autoleil_connected: bool               # AutoLeil connection status
    autoleil_active: bool                  # AutoLeil activity status
    autoleil_button_presses: int           # Physical button press count
    autoleil_manual_throws: int            # Manual water throw count
    autoleil_auto_throws: int              # Automatic water throw count
    active_notifications: Notification     # Active notification bit mask
    start_block_reasons: StartBlockReason  # Session start-block bit mask
    can_start_session: bool                # No start-block reasons (property)

    # Alarm status
    alarm_door_open: bool                  # Door open during start or heating
    alarm_door_sensor: bool                # Door open too long
    alarm_thermal_cutoff: bool             # Thermal protection
    alarm_internal_temp: bool              # Overheating alarm
    alarm_temp_sensor_short: bool          # Sensor short circuit
    alarm_temp_sensor_open: bool           # Sensor disconnected
    alarm_psu_update_required: bool        # Power unit needs firmware update (206)
    alarm_psu_comm: bool                   # Power unit communication error (207)
    alarm_psu_firmware_outdated: bool      # Power unit firmware incompatible (208)

    # Infrared
    ir_intensity: int                      # Intensity level (1-10), IR mode only
    ir_mode_active: bool                   # IR mode status
```

### Exception Handling

```python
from pysaunum import (
    SaunumConnectionError,      # Connection issues
    SaunumCommunicationError,   # Modbus communication errors
    SaunumTimeoutError,         # Timeout errors
    SaunumInvalidDataError,     # Invalid data received
)

try:
    async with SaunumClient("192.168.1.100") as client:
        data = await client.async_get_data()
except SaunumConnectionError:
    print("Failed to connect to sauna controller")
except SaunumCommunicationError:
    print("Communication error with sauna controller")
except SaunumTimeoutError:
    print("Operation timed out")
except SaunumInvalidDataError:
    print("Controller returned unexpected data")
```

`SaunumTimeoutError` is not a subclass of `SaunumConnectionError`, so catch it
separately. All library exceptions inherit from `SaunumException`.

## Development

### Setup

```bash
# Clone the repository
git clone https://github.com/mettolen/pysaunum.git
cd pysaunum

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode with dev dependencies
pip install -e ".[dev]"
```

### Testing & Quality

```bash
# Run all tests with coverage
pytest --cov=pysaunum --cov-report=term-missing

# Run type checking
mypy src/pysaunum

# Run linting and formatting
ruff check src/pysaunum
ruff format src/pysaunum

# Run pre-commit hooks (if installed)
pre-commit run --all-files
```

### Current Test Coverage

The library maintains **100% test coverage** with comprehensive tests including:

- ✅ Connection handling and error scenarios
- ✅ All API methods with valid and invalid inputs
- ✅ Modbus communication error handling
- ✅ Data parsing and validation
- ✅ Context manager functionality
- ✅ Exception hierarchy and error messages

## Requirements

- Python 3.12+
- Dependencies:
  - `pymodbus` >= 3.11.2 (Modbus TCP communication)
  - `asyncio` (built-in, async/await support)

## Compatibility

This library is tested and compatible with:

- Saunum sauna controllers with Modbus TCP interface
  - Tested with control panel v1.2.5 and power unit v1.2.3
  - AutoLeil controls require control panel v1.2.5 and AutoLeil v1.8.2
  - Modbus Interface Spec v1.2 targets control panel v1.2.5, power unit v1.2.3,
    and AutoLeil v1.8.2.
  - `async_get_data()` reads registers added in spec v1.2 (0-18, 100-118,
    200-208, 300, and 400), so it requires control panel v1.2.5 or newer.
- Home Assistant integration
- Python 3.12, 3.13, 3.14

## Advanced Usage

### Monitoring Session State

```python
from pysaunum import ControllerState

data = await client.async_get_data()

if data.controller_state is ControllerState.COOLDOWN:
    print("The heaters are off and the cooldown fan is active")
```

The state comes directly from controller register 109 and distinguishes standby,
scheduled, heating, ready, cooldown, and waiting for the door to close.

### Monitoring Status and Start Conditions

```python
from pysaunum import Notification, StartBlockReason

data = await client.async_get_data()

print(f"Humidity: {data.humidity}%")
print(f"Session remaining: {data.session_time_remaining} seconds")
print(f"Fan remaining: {data.fan_time_remaining} seconds")
print(f"AutoLeil connected: {data.autoleil_connected}")

if Notification.DOOR_OPEN in data.active_notifications:
    print("Door-open notification is active")

if not data.can_start_session:
    print(f"Cannot start: {data.start_block_reasons}")

if StartBlockReason.OTHER_CONTROLLER_ERROR in data.start_block_reasons:
    print("The controller reports another blocking error")
```

Notification and start-block values are 32-bit `IntFlag` masks, so multiple
conditions can be active simultaneously.

### Monitoring Heater Elements

```python
data = await client.async_get_data()
print(f"Active heater elements: {data.heater_elements_active}/3")

# Heater elements show how many of the 3 elements are currently active
# 0 = No heating, 1-3 = Number of elements heating
```

### Alarm Monitoring

```python
data = await client.async_get_data()

# Check for any active alarms
alarms = [
    ("Door open during start or heating", data.alarm_door_open),
    ("Door sensor alarm", data.alarm_door_sensor),
    ("Thermal cutoff", data.alarm_thermal_cutoff),
    ("Internal overheating", data.alarm_internal_temp),
    ("Temperature sensor short", data.alarm_temp_sensor_short),
    ("Temperature sensor open", data.alarm_temp_sensor_open),
    ("Power unit firmware update required", data.alarm_psu_update_required),
    ("Power unit communication error", data.alarm_psu_comm),
    ("Power unit firmware outdated", data.alarm_psu_firmware_outdated),
]

active_alarms = [name for name, active in alarms if active]
if active_alarms:
    print(f"Active alarms: {', '.join(active_alarms)}")
```

## Troubleshooting

### Connection Issues

1. **Check IP address**: Ensure the sauna controller IP is correct
2. **Network connectivity**: Verify network connection to the controller
3. **Modbus port**: Default port is 502, ensure it's not blocked by firewall
4. **Device ID**: Default device ID is 1, check controller configuration

### Common Error Patterns

```python
# Handle specific error types
try:
    await client.connect()
except SaunumTimeoutError:
    print("Connection timeout - controller may be offline")
except SaunumConnectionError as err:
    if "refused" in str(err).lower():
        print("Connection refused - check IP and port")
    else:
        print(f"Connection error: {err}")
```

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:

- Setting up your development environment
- Code style and testing requirements
- Submitting pull requests
- Reporting bugs and requesting features

For major changes, please open an issue first to discuss what you would like to change.
