Metadata-Version: 2.4
Name: lockerbot
Version: 1.0.0
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests<3,>=2.32
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: requests-mock>=1.12; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6.1; extra == "dev"
Dynamic: license-file

# lockerbot

Python SDK for the Lockerbot platform API. Synchronous HTTP client with retries,
URL-safe endpoint formatting, typed exceptions per server error code, and
paginated list endpoints.

## Requirements

- Python 3.10+
- `requests >= 2.32, < 3`

## Installation

```bash
pip install lockerbot
```

## Quick start

```python
import logging
from lockerbot import ClientConfig, LockerbotClient

config = ClientConfig(
    host="api.lockerbot.example",
    port=443,
    secret_key="your-org-secret",
    dev_mode=False,
)

with LockerbotClient(config, logger=logging.getLogger("lockerbot")) as client:
    page = client.list_devices(limit=50)
    for device in page.items:
        print(device["sn"], device["status"])

    drop = client.create_drop_token("DEV0001", 5, duration=3600)
    print(drop["secure_code"])
```

The client is a context manager — it closes the underlying `requests.Session`
on exit (or call `client.close()`). Reusing one client across many calls is fine and preferred.

## Configuration

`ClientConfig` is an immutable dataclass. All fields:

| field                  | default              | meaning                                    |
|------------------------|----------------------|--------------------------------------------|
| `host`                 | *required*           | API host                                   |
| `port`                 | `443`                | API port                                   |
| `api_version`          | `"1"`                | inserted as `platform/v{api_version}/...`  |
| `secret_key`           | *required*           | sent as `AUTHORIZATION-ORG-KEY` header     |
| `timeout`              | `30`                 | per-request timeout, seconds               |
| `max_retries`          | `3`                  | retry attempts on retriable failures       |
| `retry_backoff_factor` | `1.0`                | urllib3 backoff factor                     |
| `status_forcelist`     | `(429, 500..504)`    | HTTP statuses that trigger a retry         |
| `dev_mode`             | `False`              | sets `X-Dev: 1` header                     |

## Available methods

### Devices and cells

```text
list_devices(skip=0, limit=50, status=None)       -> PagedResult
get_device(device_id)                             -> Dict
list_device_cells(device_id)                      -> List[Dict]
list_device_available_cells(device_id)            -> List[Dict]
get_device_cell(device_id, cell_id)               -> Dict
```

### Tokens (issuance and revocation)

```text
create_drop_token(device_id, cell_id, duration=None, reserved=None)
create_pickup_token(device_id, cell_id, duration=None, reserved=None)
cancel_drop_token(device_id, cell_id)
cancel_pickup_token(device_id, cell_id)
```

`reserved=True` on either token keeps the cell held for your organization:
a reserved pickup token returns the cell to RESERVED after physical pickup
(a follow-up order is created, signalled by the `next_order_created` webhook);
a reserved drop token returns the cell to RESERVED if the token expires or is
revoked before use, keeping the same rental order active (the plain
`drop_off_token_expired` / `drop_off_token_revoked` webhook events arrive as
usual, but without a follow-up `order_expired` — you know the token was
reserved because you set the flag yourself).

### Reservations

```text
create_reservation(device_id, cell_id)
cancel_reservation(device_id, cell_id)
```

### Rentals

```text
list_rentals(status=None, device_id=None, since=None, until=None,
             cursor=None, limit=50)               -> PagedResult
get_rental(rental_id)                             -> Dict
```

### Webhooks

```text
subscribe_webhook(callback_url, is_active=True)  -> Dict
get_webhook(webhook_id)                          -> Dict
```

One webhook per organization carries both order and device events. Every
event is `POST {callback_url}` with the same envelope:

```json
{"id": "<uuid>", "type": "order_locked", "datetime": "2026-06-29T12:34:56.789Z",
 "object": "order", "object_id": "<order uuid>", "data": {}}
```

`object` is `order` (`object_id` = rental order UUID) or `device`
(`object_id` = device SN); event-specific fields are in `data`, e.g.
`device_status_changed` carries `old_status` / `new_status`. `id` is unique
per event — use it to drop duplicates. The full contract is in the server
Swagger (`POST /platform/v1/webhook/`).

## Pagination

`list_devices` and `list_rentals` return a `PagedResult`:

```python
@dataclass(slots=True, frozen=True)
class PagedResult:
    items: List[Dict[str, Any]]
    next_cursor: Optional[str] = None   # set by list_rentals (keyset)
    next_skip:   Optional[int] = None   # set by list_devices (offset)
```

Iterate all pages:

```python
# Devices (offset)
skip = 0
while True:
    page = client.list_devices(skip=skip, limit=100)
    process(page.items)
    if not page.has_more:
        break
    skip = page.next_skip

# Rentals (cursor over created_at)
cursor = None
while True:
    page = client.list_rentals(status="all", limit=100, cursor=cursor)
    process(page.items)
    if not page.has_more:
        break
    cursor = page.next_cursor
```

`PagedResult` also supports `len(page)` and `for x in page` for ergonomics.

## Error handling

All errors inherit from `LockerbotError`. For HTTP errors with a server
`error_code`, the SDK raises the matching typed subclass so callers can branch
without parsing `response_data`:

```
LockerbotError
├── APIConnectionError       — network failure
├── APITimeoutError          — request timed out
├── APIStatusError           — non-2xx response (.status_code, .code, .field, .response_data)
│   ├── CellWrongStateError      — cell not in expected status
│   ├── CellBrokenError          — cell in maintenance
│   ├── CellForbiddenError       — shared-device cell held by another org
│   ├── DeviceOfflineError       — device disconnected
│   ├── DeviceForbiddenError     — device not in your org
│   ├── RentalOrderConflictError — active order already on cell
│   ├── RentalOrderNotFoundError — no active order on cell when one was expected
│   ├── NotFoundError            — resource doesn't exist or not yours
│   └── ValidationError          — bad input (.field tells you which)
└── ResponseFormatError      — 2xx response did not match the expected format
    ├── InvalidJSONError         — body was not parseable JSON, or wrong type
    └── MissingResultError       — JSON ok, but no top-level "result" key
```

Example:

```python
from lockerbot import CellWrongStateError, DeviceOfflineError, APIStatusError

try:
    client.create_pickup_token("DEV0001", 5, reserved=True)
except CellWrongStateError as e:
    # Cell isn't OCCUPIED — drop likely hasn't happened yet
    log.info("Pickup not possible: %s", e.code)
except DeviceOfflineError:
    schedule_retry()
except APIStatusError as e:
    # any other server-side error
    log.error("Lockerbot %s: %s", e.code, e)
```

Or, if you don't want typed branching, catch `APIStatusError` and inspect `.code`:

```python
try:
    ...
except APIStatusError as e:
    if e.code == "cell_wrong_state":
        ...
```

## Development

```bash
pip install -e ".[dev]"                                     # install with dev extras
pytest -q                                                   # run tests
rm -rf dist && python -m build                              # build sdist + wheel into dist/
twine upload dist/*                                         # publish to PyPI
```

## License

MIT
