Metadata-Version: 2.3
Name: ev-remote-lib
Version: 0.8.0
Summary: A robust Python library for handling Bluetooth and USB remote controls with automatic reconnection
Keywords: bluetooth,USB,remote,control,evdev,udev,input,linux
Author: foxy82
Author-email: foxy82 <foxy82.github@gmail.com>
License: MIT License
         
         Copyright (c) 2025 foxy82
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
         in the Software without restriction, including without limitation the rights
         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
         copies of the Software, and to permit persons to whom the Software is
         furnished to do so, subject to the following conditions:
         
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
Requires-Dist: evdev>=1.6.0
Requires-Dist: pyudev>=0.24.0
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/designer-living/ev-remote-lib
Project-URL: Issues, https://github.com/designer-living/ev-remote-lib/issues
Project-URL: Repository, https://github.com/designer-living/ev-remote-lib
Description-Content-Type: text/markdown

# Bluetooth Remote Control Library

[![PyPI version](https://badge.fury.io/py/bluetooth-remote-lib.svg)](https://badge.fury.io/py/bluetooth-remote-lib)
[![Python versions](https://img.shields.io/pypi/pyversions/bluetooth-remote-lib.svg)](https://pypi.org/project/bluetooth-remote-lib/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A robust Python library for handling Bluetooth remote controls that go to sleep, combining udev device monitoring with evdev event handling for seamless reconnection and event processing.

## Features

- 🔄 **Automatic Reconnection**: Handles Bluetooth remotes that go to sleep and wake up
- 📱 **Multiple Device Support**: Manage multiple remotes simultaneously with individual configurations
- ⚡ **Real-time Detection**: Uses udev for instant device discovery (no polling)
- 🎯 **Flexible Filtering**: Filter devices by name, vendor ID, product ID, or bus type
- 🔧 **Per-Device Handlers**: Different event handlers and settings for each remote type
- 🏗️ **Async/Await**: Built with modern Python async patterns
- 🧵 **Thread-Safe**: Proper threading and cleanup
- 🔍 **Device Discovery**: Built-in tools to find your remote's details

## Installation

### Using uv (recommended)

```bash
uv add bluetooth-remote-lib
```

### Using pip

```bash
pip install bluetooth-remote-lib
```

## Quick Start

```python
import asyncio
from bluetooth_remote_lib import RemoteManager, RemoteEventHandler, KeyEvent

class MyHandler(RemoteEventHandler):
    async def on_key_event(self, event: KeyEvent):
        print(f"Key pressed: {event.keycode}")

async def main():
    handler = MyHandler()
    manager = RemoteManager(
        event_handler=handler,
        device_filters={'name': 'remote'}  # Match devices with 'remote' in name
    )
    
    async with manager.managed_context():
        await asyncio.sleep(60)  # Run for 60 seconds

asyncio.run(main())
```

## Advanced Usage - Multiple Remotes

```python
import asyncio
from bluetooth_remote_lib import (
    RemoteManager, RemoteEventHandler, RemoteConfig,
    KeyEvent, KeyEventType, DeviceInfo
)

# Define handlers for specific remotes
async def handle_fire_tv(event: KeyEvent):
    if event.event_type == KeyEventType.KEY_DOWN:
        print(f"🔥 Fire TV: {event.keycode}")

async def handle_roku(event: KeyEvent):
    if event.event_type == KeyEventType.KEY_DOWN:
        print(f"📺 Roku: {event.keycode}")

class MainHandler(RemoteEventHandler):
    async def on_key_event(self, event: KeyEvent):
        print(f"Generic remote: {event.keycode}")
    
    async def on_device_connected(self, device_info: DeviceInfo):
        print(f"Connected: {device_info.name}")

# Configure multiple remotes with individual settings
remote_configs = [
    RemoteConfig(
        name="Fire TV Remote",
        filters={
            'name': 'fire tv',
            'vendor_id': 0x1949,  # Amazon
        },
        handler=handle_fire_tv,
        reconnect_delay=1.5,  # Custom timing
        scan_interval=3.0
    ),
    RemoteConfig(
        name="Roku Remote",
        filters={
            'name': 'roku',
            'vendor_id': 0x0B05,  # Roku
        },
        handler=handle_roku,
        reconnect_delay=2.0
    )
]

async def main():
    manager = RemoteManager(
        event_handler=MainHandler(),
        remote_configs=remote_configs
    )
    
    async with manager.managed_context():
        while True:
            await asyncio.sleep(1)

asyncio.run(main())
```

## Device Discovery

Find your remote's vendor/product IDs:

```bash
# Discover all input devices
bt-remote-discover

# Or use the module directly
python -m bluetooth_remote_lib discover

# Find specific devices
bt-remote find --name "fire tv"
bt-remote find --vendor-id 0x1949
```

Example output:
```
Device: Amazon Fire TV Remote
  Path: /dev/input/event5
  Vendor ID: 0x1949 (6473)
  Product ID: 0x0404 (1028)
  Key capabilities: 15 keys
    Keys: KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER...
```

## Configuration Options

### RemoteConfig Parameters

- **name**: Friendly name for the remote configuration
- **filters**: Dictionary of device matching criteria:
  - `name`: Substring to match in device name (case insensitive)
  - `vendor_id`: Vendor ID (integer)
  - `product_id`: Product ID (integer)  
  - `bus_type`: Bus type (integer)
- **handler**: Optional async function to handle events from this remote
- **reconnect_delay**: Custom delay before reconnection attempts (seconds)
- **scan_interval**: Custom interval between reconnection scans (seconds)

### Manager Parameters

- **event_handler**: Main event handler (RemoteEventHandler subclass)
- **remote_configs**: List of RemoteConfig objects
- **device_filters**: Legacy single filter dict (use remote_configs instead)
- **reconnect_delay**: Default reconnection delay (2.0 seconds)
- **scan_interval**: Default scan interval (5.0 seconds)
- **log_level**: Logging level (logging.INFO)

## Event Handling

### Key Events

```python
class MyHandler(RemoteEventHandler):
    async def on_key_event(self, event: KeyEvent):
        # event.keycode: 'KEY_UP', 'KEY_HOME', etc.
        # event.event_type: KEY_DOWN, KEY_UP, KEY_HOLD
        # event.timestamp: Event timestamp
        # event.device_name: Name of the device
        # event.raw_event: Original evdev event
        
        if event.event_type == KeyEventType.KEY_DOWN:
            if event.keycode == 'KEY_HOME':
                print("Home button pressed!")
```

### Device Events

```python
class MyHandler(RemoteEventHandler):
    async def on_device_connected(self, device_info: DeviceInfo):
        print(f"Device connected: {device_info.name}")
        print(f"Vendor: 0x{device_info.vendor_id:04x}")
    
    async def on_device_disconnected(self, device_info: DeviceInfo):
        print(f"Device disconnected: {device_info.name}")
    
    async def on_device_reconnecting(self, device_info: DeviceInfo):
        print(f"Reconnecting: {device_info.name}")
```

## Requirements

- **Linux**: This library uses Linux-specific evdev and udev systems
- **Python 3.8+**: Modern async/await support
- **Permissions**: May require user to be in `input` group or run with appropriate permissions

### System Setup

```bash
# Add user to input group (recommended)
sudo usermod -a -G input $USER
# Then log out and back in

# Or install udev rule for your specific devices
echo 'SUBSYSTEM=="input", GROUP="input", MODE="0664"' | sudo tee /etc/udev/rules.d/99-input.rules
sudo udevadm control --reload-rules
```

## Examples

The `examples/` directory contains:

- `basic_usage.py`: Simple single remote example
- `advanced_usage.py`: Multiple remotes with individual configurations

Run examples:
```bash
python examples/basic_usage.py
python examples/advanced_usage.py
```

## Contributing

Contributions welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history and changes.

## Support

- **Issues**: [GitHub Issues](https://github.com/yourusername/bluetooth-remote-lib/issues)
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/bluetooth-remote-lib/discussions)

## Related Projects

- [evdev](https://python-evdev.readthedocs.io/) - Linux input handling
- [pyudev](https://pyudev.readthedocs.io/) - Python udev bindings