Metadata-Version: 2.4
Name: Actu8HubClient
Version: 1.2.0
Summary: Python client library for the Actu8Hub IoT platform
Author: Filip Petersson
License-Expression: MIT
Project-URL: Homepage, https://actu8hub.com
Project-URL: Documentation, https://actu8hub.com
Keywords: iot,actu8hub,raspberry-pi,jetson,embedded,sensors,actuators
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Home Automation
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: System :: Hardware
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.20.0
Provides-Extra: websocket
Requires-Dist: websocket-client>=1.0.0; extra == "websocket"
Provides-Extra: all
Requires-Dist: websocket-client>=1.0.0; extra == "all"

# Actu8Hub Python Client Library

A lightweight, non-blocking Python client for connecting devices to the [Actu8Hub](https://actu8hub.com) IoT platform. Works with Raspberry Pi, NVIDIA Jetson, Linux SBCs, and any Python-capable device.

## Features

- **HTTP Polling** — battery-friendly sync at your chosen interval
- **WebSocket Real-Time** — instant actuator command push from the dashboard
- **Offline Ring Buffer** — queues up to 50 readings in RAM when Wi-Fi is down; sends them in a batch when connection is restored
- **Text/String Sensor Values** — report classification results, state labels, etc.
- **File Upload Helper** — 2-step signed URL process wrapped in a single `upload_file()` call
- **Device Logging** — debug, info, warn, error levels sent to the dashboard
- **Smart Actuator Confirmation** — avoids redundant traffic when state already matches
- **Non-Blocking** — background threading keeps your main control loop responsive
- **Context Manager** — use `with` blocks for automatic cleanup

## Installation

```bash
pip install Actu8HubClient              # HTTP mode
pip install "Actu8HubClient[websocket]" # + WebSocket real-time mode
```

Update to the latest version:

```bash
pip install --upgrade Actu8HubClient
```

> **Note:** `requests` is installed automatically. `websocket-client` is only needed if you use WebSocket real-time mode.

## Quick Start — HTTP Polling

```python
from Actu8HubClient import Actu8HubClient

# Create client with your device API key
hub = Actu8HubClient("a8h_YOUR_API_KEY")

# Queue sensor readings
hub.queue_reading("Temperature", 24.5)
hub.queue_reading("Humidity", 62.3)
hub.queue_text_reading("Status", "Normal")

# Send everything & receive actuator commands in one call
hub.sync()
```

## Quick Start — WebSocket Real-Time

```python
from Actu8HubClient import Actu8HubClient, ActuatorCommand
import time

hub = Actu8HubClient("a8h_YOUR_API_KEY")

def handle_actuator(cmd: ActuatorCommand) -> int:
    """Called when an actuator command arrives from the dashboard."""
    print(f"Command: {cmd.name} active={cmd.is_active} value={cmd.value}")
    # Execute the command on your hardware here
    # Return: 1=changed, 0=already matched, -1=error
    return 1

hub.on_actuator(handle_actuator)
hub.connect_websocket()

while True:
    hub.queue_reading("Temperature", 24.5)
    hub.transmit_readings()
    time.sleep(5)
```

## Quick Start — Background Auto-Sync

```python
from Actu8HubClient import Actu8HubClient
import time

hub = Actu8HubClient("a8h_YOUR_API_KEY")

# Start automatic sync every 10 seconds in a background thread
hub.start_background_sync(interval_s=10)

while True:
    # Your main control loop runs uninterrupted
    hub.queue_reading("Temperature", read_temp_sensor())
    time.sleep(1)
```

## API Reference

### `Actu8HubClient(api_key, base_url=None, ws_url=None, ring_buffer_size=50, max_log_queue=50)`

Create a new client instance.

| Parameter | Type | Description |
|-----------|------|-------------|
| `api_key` | `str` | Device API key from the Actu8Hub dashboard (`a8h_` or `esp32_` prefix) |
| `base_url` | `str` | Override the default server URL (default `https://api.actu8hub.com/functions/v1`) |
| `ws_url` | `str` | Override the default WebSocket URL |
| `ring_buffer_size` | `int` | Max queued readings in RAM when offline (default 50) |
| `max_log_queue` | `int` | Max buffered log entries (default 50) |

---

### Sensor Methods

#### `hub.queue_reading(name, value)`
Queue a numeric sensor reading.

```python
hub.queue_reading("Temperature", 24.5)
```

#### `hub.queue_text_reading(name, text_value, media_url=None)`
Queue a text/string sensor reading. Optionally attach a media file path.

```python
hub.queue_text_reading("Door", "Open")
hub.queue_text_reading("Camera", "Person Detected", media_url="device123/photo.jpg")
```

---

### Sync Methods (HTTP Polling)

#### `hub.sync() -> bool`
Full sync — send readings + logs, receive actuator commands. Returns `True` on success.

#### `hub.sync_sensors_only() -> bool`
Send sensor readings only.

#### `hub.sync_actuators_only() -> bool`
Receive actuator commands only.

#### `hub.sync_logs_only() -> bool`
Send device logs only.

---

### Background Sync

#### `hub.start_background_sync(interval_s=10)`
Start a daemon thread that calls `sync()` at regular intervals.

#### `hub.stop_background_sync()`
Stop the background sync thread.

---

### WebSocket Methods (Real-Time)

#### `hub.connect_websocket()`
Connect to the Actu8Hub WebSocket server. Runs in a background thread with automatic reconnection.

#### `hub.disconnect_websocket()`
Disconnect and stop the WebSocket thread.

#### `hub.transmit_readings() -> bool`
Send queued numeric readings over WebSocket.

#### `hub.transmit_text_readings() -> bool`
Send queued text readings over WebSocket (if connected) or HTTP POST (fallback). Automatically uses the best available transport.

#### `hub.transmit_logs() -> bool`
Send queued logs over WebSocket.

---

### Actuator Handling

#### `hub.on_actuator(callback)`
Register a callback for actuator commands.

```python
def handle_actuator(cmd: ActuatorCommand) -> int:
    if cmd.name == "LED":
        set_led(cmd.is_active)
        return 1   # State changed
    return -1       # Unknown actuator

hub.on_actuator(handle_actuator)
```

**Callback return values:**
- `1` — State physically changed (triggers confirmation to server)
- `0` — Already in target state (confirms only if server thinks it's pending)
- `-1` — Error (no confirmation sent)

**Trigger actuators (push buttons, e.g. emergency stop):** the callback runs on
every sync, so fire the event only when `cmd.is_pending` is `True`. It is `True`
once per press (also if the device was offline when it happened) and `False` on
later syncs and after a restart.

```python
def handle_actuator(cmd: ActuatorCommand) -> int:
    if cmd.name == "Emergency Stop":
        if cmd.is_pending:
            emergency_stop()
            return 1
        return 0
    return -1
```

#### `hub.on_connection(callback)`
Register a callback for WebSocket connection status changes.

```python
hub.on_connection(lambda connected: print(f"Connected: {connected}"))
```

---

### Device Logging

```python
hub.queue_debug_log("Sensor initialized")
hub.queue_info_log("Reading cycle complete")
hub.queue_warning_log("Battery low: 15%")
hub.queue_error_log("Sensor read timeout")
hub.queue_log(LogLevel.INFO, "Custom level log")
hub.set_max_log_queue(100)  # Adjust max queue size (capped at 100)
```

---

### Metadata Reporting

#### `hub.report_metadata(board_type=None, firmware_version=None, sdk_version=None, ip_address=None) -> bool`

Report device metadata to the dashboard.

```python
hub.report_metadata(
    board_type="Raspberry Pi 4",
    firmware_version="1.2.0",
    sdk_version="1.0.0",
    ip_address="192.168.1.42"
)
```

---

### File Upload

#### `hub.upload_file(filepath) -> str | None`

Upload a file using the 2-step signed URL process. Returns the relative `media_url` on success.

```python
media_path = hub.upload_file("/home/pi/captures/photo.jpg")
if media_path:
    hub.queue_text_reading("Camera", "Person Detected", media_url=media_path)
    hub.sync()
```

---

### Event Logging

#### `hub.log_event(sensor_name, description, seconds_ago=0) -> bool`

Log a sensor event on the server.

```python
hub.log_event("Motion", "Movement detected in Zone A")
hub.log_event("Door", "Door opened", seconds_ago=5)
```

---

### Cleanup

```python
hub.close()  # Stops all threads and closes connections
```

Or use as a context manager:

```python
with Actu8HubClient("a8h_YOUR_KEY") as hub:
    hub.queue_reading("Temp", 22.0)
    hub.sync()
# Automatically cleaned up
```

---

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `hub.is_connected` | `bool` | `True` if WebSocket is connected (or always `True` in HTTP mode) |
| `hub.pending_log_count` | `int` | Number of log entries waiting to be sent |
| `hub.has_pending` | `bool` | `True` if there are unsent actuator confirmations |

## Complete Example — Raspberry Pi GPIO

```python
import time
import RPi.GPIO as GPIO
from Actu8HubClient import Actu8HubClient, ActuatorCommand

# Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)  # LED on BCM pin 17
GPIO.setup(4, GPIO.IN)    # Button on BCM pin 4

hub = Actu8HubClient("a8h_YOUR_API_KEY")

# Report what board we are
hub.report_metadata(board_type="Raspberry Pi 4", firmware_version="1.0.0")

def handle_actuator(cmd: ActuatorCommand) -> int:
    if cmd.name == "LED":
        GPIO.output(17, GPIO.HIGH if cmd.is_active else GPIO.LOW)
        return 1
    return -1

hub.on_actuator(handle_actuator)

try:
    while True:
        button_state = GPIO.input(4)
        hub.queue_reading("Button", float(button_state))
        hub.queue_text_reading("Button State", "Pressed" if button_state else "Released")
        hub.sync()
        time.sleep(2)
except KeyboardInterrupt:
    pass
finally:
    hub.close()
    GPIO.cleanup()
```

## Offline Resilience

The client uses an internal ring buffer (default: 50 entries). If `queue_reading()` is called while the network is unavailable, readings are stored in RAM. When `sync()` or `transmit_readings()` succeeds again, all buffered readings are sent in a single batch.

If the buffer is full, the oldest reading is silently dropped to make room for new data.

## Dependencies

| Package | Required For | Install |
|---------|-------------|---------|
| `requests` | HTTP mode (polling) | `pip install requests` |
| `websocket-client` | WebSocket mode (real-time) | `pip install websocket-client` |

## License

MIT
