Metadata-Version: 2.4
Name: walkingpad-controller
Version: 0.1.0
Summary: Python library for controlling KingSmith WalkingPad treadmills over BLE (FTMS and legacy WiLink protocols)
Project-URL: Homepage, https://github.com/mcdax/walkingpad-controller
Project-URL: Repository, https://github.com/mcdax/walkingpad-controller
Project-URL: Issues, https://github.com/mcdax/walkingpad-controller/issues
Author: mcdax
License-Expression: MIT
License-File: LICENSE
Keywords: ble,bluetooth,ftms,kingsmith,treadmill,walkingpad
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Home Automation
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Requires-Dist: bleak>=0.20.0
Provides-Extra: all
Requires-Dist: ph4-walkingpad>=1.0.0; extra == 'all'
Provides-Extra: wilink
Requires-Dist: ph4-walkingpad>=1.0.0; extra == 'wilink'
Description-Content-Type: text/markdown

# walkingpad-controller

Python library for controlling KingSmith WalkingPad treadmills over Bluetooth Low Energy (BLE).

Supports both **FTMS** (Fitness Machine Service) and legacy **WiLink** protocols behind a unified API. Protocol is auto-detected based on the BLE device name and advertised services.

## Features

- **Unified API** — single `WalkingPadController` class for all device types
- **Auto protocol detection** — FTMS for newer KS-HD-* devices, WiLink for older models
- **Real-time status** — speed, distance, duration, calories, steps via BLE notifications
- **Cold-start handling** — retry logic for KingSmith FTMS devices that need START_OR_RESUME before accepting speed commands
- **Reconnect recovery** — pending target speed is automatically re-applied after BLE reconnection
- **KingSmith extensions** — step counter via proprietary FTMS extension (bit 13)

## Installation

```bash
pip install walkingpad-controller
```

For legacy WiLink device support (older WalkingPad models):

```bash
pip install walkingpad-controller[wilink]
```

## Quick Start

```python
import asyncio
from bleak import BleakScanner
from walkingpad_controller import WalkingPadController

async def main():
    # Find your treadmill
    device = await BleakScanner.find_device_by_name("KS-HD-Z1D")

    # Create controller (protocol auto-detected from BLE name)
    controller = WalkingPadController(ble_device=device)

    # Connect
    await controller.connect()
    print(f"Protocol: {controller.protocol.value}")
    print(f"Speed range: {controller.min_speed}-{controller.max_speed} km/h")

    # Start at 3.0 km/h
    await controller.start(target_speed=3.0)

    # Read status
    print(f"Speed: {controller.status.speed} km/h")
    print(f"Steps: {controller.status.steps}")

    # Stop and disconnect
    await controller.stop()
    await controller.disconnect()

asyncio.run(main())
```

## Status Callbacks

Register callbacks to receive real-time status updates:

```python
from walkingpad_controller import WalkingPadController, TreadmillStatus

def on_status(status: TreadmillStatus):
    print(f"Speed: {status.speed} km/h, Distance: {status.distance}m, "
          f"Duration: {status.duration}s, Calories: {status.calories}, "
          f"Steps: {status.steps}")

controller = WalkingPadController(ble_device=device)
controller.register_status_callback(on_status)
controller.register_disconnect_callback(lambda: print("Disconnected!"))
await controller.connect()
```

## API Reference

### WalkingPadController

The main entry point. Auto-detects protocol and delegates to the appropriate backend.

| Property / Method | Description |
|---|---|
| `protocol` | Detected protocol (`ProtocolType.FTMS` or `ProtocolType.WILINK`) |
| `connected` | Whether the device is currently connected |
| `status` | Current `TreadmillStatus` |
| `min_speed` / `max_speed` | Speed range in km/h (read from device for FTMS) |
| `speed_increment` | Speed step size in km/h |
| `connect()` | Connect and auto-detect protocol |
| `disconnect()` | Disconnect from the device |
| `start(target_speed=None)` | Start the belt, optionally at a target speed |
| `stop()` | Stop the belt |
| `set_speed(speed_kmh)` | Set speed (starts belt if stopped) |
| `switch_mode(mode)` | Switch operating mode (WiLink: auto/manual/standby) |
| `register_status_callback(cb)` | Register a `TreadmillStatus` callback |
| `register_disconnect_callback(cb)` | Register a disconnect callback |
| `update_ble_device(device)` | Update BLE device reference after rediscovery |

### TreadmillStatus

Dataclass with real-time treadmill data:

| Field | Type | Description |
|---|---|---|
| `belt_state` | `int` | 0=stopped, 1=active, 5=standby, 9=starting |
| `speed` | `float` | Current speed in km/h |
| `mode` | `int` | Operating mode (0=auto, 1=manual, 2=standby) |
| `distance` | `int` | Total distance in meters |
| `duration` | `int` | Elapsed time in seconds |
| `steps` | `int` | Step count (FTMS KingSmith extension) |
| `calories` | `int` | Total energy in kcal |
| `calories_per_hour` | `int` | Energy rate |
| `heart_rate` | `int` | Heart rate in bpm (if available) |
| `timestamp` | `float` | Unix timestamp of last update |

### Protocol-Specific Controllers

For advanced use, you can use the protocol controllers directly:

- **`FTMSController`** — FTMS protocol (newer KS-HD-* devices)
- **`WiLinkController`** — Legacy WiLink protocol (older WalkingPad models, requires `[wilink]` extra)

## Supported Devices

### FTMS Protocol (tested)
- KingSmith KS-Z1D (BLE name: `KS-HD-Z1D`)
- Other KingSmith devices with BLE names starting with `KS-HD-`

### WiLink Protocol (via ph4-walkingpad)
- WalkingPad A1, A1 Pro
- WalkingPad C1, C2
- Other models supported by [ph4-walkingpad](https://github.com/niclasku/ph4-walkingpad)

## Known Behavior

### FTMS Cold Start
KingSmith FTMS devices require a `START_OR_RESUME` command before the belt will accept speed commands. After a cold start, there is a delay of several seconds before `SET_TARGET_SPEED` takes effect. The library handles this automatically with retry logic.

### BLE Connection Drops
KingSmith FTMS devices may drop the BLE connection shortly after a cold start, especially at weaker signal strength. The library stores the pending target speed and can re-apply it after reconnection via the status callback mechanism.

### Connection Exclusivity
Only one BLE client can connect to the treadmill at a time. If Home Assistant holds the connection, the KS Fit app cannot connect, and vice versa.

## Requirements

- Python 3.10+
- [bleak](https://github.com/hbldh/bleak) >= 0.20.0
- [ph4-walkingpad](https://github.com/niclasku/ph4-walkingpad) >= 1.0.0 (optional, for WiLink devices)

## License

MIT
