The official OpenShock Python SDK to integrate with an OpenShock backend easily.
- REST API — every endpoint and model, generated from the backend's OpenAPI document, sync and async
- Realtime events — SignalR user hub: hub online state, executed commands, firmware updates
- Live control — stream intensity to shockers in real time
- Typed models and enums, typed errors, automatic reconnects, Python 3.11+
pip install openshock # REST client only
pip install "openshock[realtime]" # + SignalR user hub and live controlThe base install is pure Python. The realtime extra pulls in websockets, whose wheels
include an optional C accelerator. To install without any compiled code, build it from
source with the extension switched off (no compiler needed):
BUILD_EXTENSION=no pip install --no-cache-dir --no-binary websockets "openshock[realtime]"On Windows PowerShell:
$env:BUILD_EXTENSION = "no"
pip install --no-cache-dir --no-binary websockets "openshock[realtime]"--no-cache-dir keeps pip from reusing a compiled wheel it built or downloaded earlier. If
websockets is already installed, add --force-reinstall so it is actually rebuilt.
from uuid import UUID
from openshock import OpenShockClient, unwrap
from openshock.rest.api.shockers import shocker_list_shockers, shocker_send_control
from openshock.rest.models import Control, ControlRequest, ControlType
with OpenShockClient("your-api-token", app_name="MyApp", app_version="1.0.0") as client:
# Your hubs and their shockers
for hub in unwrap(shocker_list_shockers.sync(client=client)).data:
for shocker in hub.shockers:
print(hub.name, shocker.name, shocker.id)
# Vibrate at 50% for one second
shocker_send_control.sync(
client=client,
body=ControlRequest(
shocks=[Control(id=UUID("shocker-uuid"), type_=ControlType.VIBRATE, intensity=50, duration=1000)],
custom_name="MyApp",
),
)Create API tokens at openshock.app under Settings > API Tokens.
Please set app_name / app_version: they end up in the User-Agent header and let the
OpenShock team tell integrations apart.
openshock.rest is generated from the backend's OpenAPI document with
openapi-python-client. Nothing
in it is written by hand, so it always covers the whole API.
- Operations live in
openshock.rest.api.<area>, one module per endpoint. The module name is the endpoint's operation ID in snake case. - Models and enums live in
openshock.rest.models. OpenShockClientis the generated client with OpenShock's header name, base URL, User-Agent and error handling filled in. Pass it to every operation asclient=.
Area (openshock.rest.api.…) |
Covers |
|---|---|
shockers |
Shocker CRUD, control, pause, logs, share codes |
hub_management |
Hubs: list, create, edit, pair code, gateway lookup, OTA history |
user_shocker_shares, shocker_shares |
User-to-user shares and invites |
public_shocker_shares |
Public share links |
api_tokens |
API tokens |
users, account, sessions |
Profile, account settings, login sessions |
meta |
Backend version and public stats |
hub_endpoints |
What a hub device itself calls (see below) |
integrations, admin |
Integrations and admin endpoints |
Each operation module offers the same functions:
| Function | Returns |
|---|---|
sync(...) / await asyncio(...) |
the parsed response model |
sync_detailed(...) / await asyncio_detailed(...) |
a Response with status_code, headers, content and parsed |
Endpoints without a response body only have the _detailed pair.
The same client serves both styles:
async with OpenShockClient("your-api-token") as client:
stats = unwrap(await public_get_online_devices_statistics.asyncio(client=client)).data
print(f"Devices online: {stats.devices_online}")Generated operations are typed as returning Model | OpenShockProblem | None. unwrap()
narrows that to Model for the type checker (and raises if it is handed a problem), so
unwrap(op.sync(client=client)).data type-checks without isinstance checks. Many older
endpoints wrap their payload as {"message": ..., "data": ...}, hence the .data.
Fields the API may omit are typed T | Unset (from openshock.rest.types import UNSET, Unset).
Fields the backend adds after a release are not lost: every model keeps unknown fields and
exposes them with model["fieldName"].
With OpenShockClient, every non-2xx response raises a subclass of OpenShockApiError,
which carries status_code and, when the backend sent one, the parsed problem document.
from openshock import OpenShockApiError, ShockerNoPermission, ShockerNotFoundOrNoAccess, ShockerPaused
try:
shocker_send_control.sync(client=client, body=request)
except ShockerPaused as e:
print("paused:", e.shocker_id)
except (ShockerNotFoundOrNoAccess, ShockerNoPermission) as e:
print("not allowed:", e.shocker_id)
except OpenShockApiError as e:
print(e.status_code, e.problem_type, e)| Exception | Raised when |
|---|---|
OpenShockAuthError |
401 / 403 |
TokenPermissionMissing |
the API token lacks a permission (.required_permission) |
ApiTokenPaused |
the API token is paused |
OpenShockNotFound |
404 |
HubNotFound, HubOffline |
hub lookups, e.g. the gateway lookup |
ShockerNotFoundOrNoAccess, ShockerPaused, ShockerNoPermission |
a control request was rejected (.shocker_id) |
OpenShockRateLimited |
429 (.retry_after) |
OpenShockConnectionError |
a realtime connection failed for good |
Pass raise_on_error=False to get the generator's stock behaviour instead, where documented
problems are returned as OpenShockProblem objects.
UserHubClient connects to the SignalR user hub. It needs openshock[realtime] and asyncio.
import asyncio
from openshock.realtime import UserHubClient
async def main():
async with UserHubClient("your-api-token", app_name="MyApp", app_version="1.0.0") as hub:
@hub.on_hub_status
def on_status(states):
for state in states:
print(state.device, "online" if state.online else "offline", state.firmware_version)
@hub.on_log
async def on_log(sender, logs):
for log in logs:
print(f"{sender.custom_name or sender.name}: {log.type} {log.intensity}% on {log.shocker.name}")
await hub.wait_closed()
asyncio.run(main())| Event | Arguments |
|---|---|
on_welcome |
connection_id |
on_hub_status |
list[HubOnlineState] |
on_log |
sender, list[ControlLog] |
on_hub_update |
hub_id, HubUpdateType |
on_ota_install_started |
hub_id, update_id, version |
on_ota_install_progress |
hub_id, update_id, OtaUpdateProgressTask, progress |
on_ota_install_failed |
hub_id, update_id, fatal, message |
on_ota_rollback, on_ota_install_succeeded |
hub_id, update_id |
on_connected, on_reconnected |
— |
on_reconnecting, on_closed |
error |
Handlers can be plain functions or coroutines. Subscribe with the decorator form shown
above or with hub.on_log.subscribe(handler), which returns an unsubscribe function.
hub.on("MethodName", handler) subscribes to hub methods the SDK has no typed event for.
Commands can be sent over the same connection, using the same Control model as the REST
API: await hub.control([Control(...)], custom_name="MyApp").
set_captive_portal, emergency_stop, ota_install and reboot exist too, but the
backend only honours them for user-session connections, not API tokens.
The connection reconnects on its own (immediately, then after 2s, 10s, and every 30s).
Pass retry_policy= to change that. If the token is rejected or revoked the session ends:
on_closed receives the error and wait_closed() raises it.
Naming:
UserHubClientis the realtime connection for a user.OpenShockHubClient(below) is the REST client a hub device uses. The C# SDK calls the formerOpenShockHubClient.
Live control is a stream: you keep telling the hub what a shocker should be doing right now,
and it stops shortly after you stop. LiveControlClient handles the gateway lookup, the tick
rate the gateway asks for, pings and reconnects.
import asyncio
from openshock.realtime import LiveControlClient
from openshock.rest.models import ControlType
async def main():
async with LiveControlClient("hub-uuid", api_token="your-api-token") as live:
await live.wait_connected()
# Ramp vibration from 0 to 50 over five seconds
for intensity in range(0, 51):
live.intake_frame("shocker-uuid", ControlType.VIBRATE, intensity)
await asyncio.sleep(0.1)
asyncio.run(main())intake_frame()never blocks. The latest value per shocker is sent on every tick and dropped after a short hold window (2.5 ticks, orhold_for=seconds), so call it again to keep going.release()stops sending immediately;send_frame()sends a single frame right away.live.tps,live.latency_ms,live.hub_connectedexpose the current state.- Events:
on_hub_connected,on_hub_not_connected,on_tps,on_latency,on_rejected(e.g.SHOCKER_PAUSED,SHOCKER_MISSING_LIVE_PERMISSION), plus the connection events above. - While the hub is offline the client keeps retrying in the background (0s, 5s, 10s, then every 30s).
- Pass
client=to reuse anOpenShockClient, orgateway=to skip the lookup.
The shockers need the live permission for your account.
For the endpoints a hub itself calls, use OpenShockHubClient with a device token:
from openshock import OpenShockHubClient, unwrap
from openshock.rest.api.hub_endpoints import device_get_self
with OpenShockHubClient("device-token") as hub:
me = unwrap(device_get_self.sync(client=hub)).data
print(me.name, len(me.shockers), "shockers")client = OpenShockClient("your-token", base_url="https://api.your-instance.com")
hub = UserHubClient("your-token", base_url="https://api.your-instance.com")Standalone example programs live in examples/, one folder each:
| Folder | Shows |
|---|---|
rest_quickstart |
REST, blocking: list hubs, shockers and shares |
async_control |
REST, asyncio: send a command, handle typed errors |
realtime_events |
SignalR user hub: print live events for your account |
live_control |
Live control: stream intensity to a shocker |
They read OPENSHOCK_API_TOKEN (and OPENSHOCK_API_URL for self-hosted instances) from the environment.
git clone https://github.com/OpenShock/SDK.Python.git
cd SDK.Python
pip install -e ".[dev]"
ruff format . # format
ruff check . # lint
mypy openshock/ # type check
pytest # testEverything under openshock/rest/ is generated from openapi/openapi.json, a snapshot of
the backend's OpenAPI document. Never edit it by hand.
python scripts/generate.py --update # download the latest spec, then regenerate
python scripts/generate.py # regenerate from the committed snapshot
python scripts/generate.py --check # what CI runs; fails if openshock/rest is out of dateThe generator and formatter versions are pinned in the codegen extra because they decide
the output. The script fails rather than emit a partial client if the generator skips anything.
Hand-written code is limited to what the OpenAPI document cannot describe: the preconfigured
clients (openshock/client.py), the error mapping (openshock/exceptions.py) and the
realtime clients (openshock/realtime/).
Found a security vulnerability? Please do not open a public issue. Report it privately as described in the OpenShock security policy.
You can support the OpenShock dev team here: Sponsor OpenShock