Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
54 lines (41 loc) · 1.97 KB
/
Copy pathmain.py
File metadata and controls
54 lines (41 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Print realtime events for your account until interrupted (Ctrl+C)."""
import asyncio
import contextlib
import logging
import os
import sys
from uuid import UUID
from openshock.realtime import ControlLog, HubControlLogSender, HubOnlineState, HubUpdateType, UserHubClient
APP_NAME = "OpenShock.SDK.Python.Examples"
APP_VERSION = "1.0.0"
BASE_URL = os.environ.get("OPENSHOCK_API_URL", "https://api.openshock.app")
API_TOKEN = os.environ.get("OPENSHOCK_API_TOKEN") or sys.exit(
"Set OPENSHOCK_API_TOKEN to an API token from https://openshock.app (Settings > API Tokens)."
)
async def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s: %(message)s")
hub = UserHubClient(API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION)
@hub.on_welcome
def on_welcome(connection_id: str) -> None:
print(f"Connected, connection id {connection_id}")
@hub.on_hub_status
def on_hub_status(states: list[HubOnlineState]) -> None:
for state in states:
status = f"online (firmware {state.firmware_version})" if state.online else "offline"
print(f"Hub {state.device} is {status}")
@hub.on_hub_update
def on_hub_update(hub_id: UUID, update: HubUpdateType) -> None:
print(f"Hub {hub_id}: {update}")
@hub.on_log
async def on_log(sender: HubControlLogSender, logs: list[ControlLog]) -> None:
who = sender.custom_name or sender.name
mine = " (this connection)" if sender.connection_id == hub.connection_id else ""
for log in logs:
live = " [live]" if log.live_control else ""
print(f"{who}{mine}: {log.type} {log.intensity}% for {log.duration} ms on {log.shocker.name}{live}")
hub.on_reconnecting(lambda error: print(f"Connection lost ({error}), reconnecting..."))
hub.on_reconnected(lambda: print("Reconnected"))
async with hub:
await hub.wait_closed()
with contextlib.suppress(KeyboardInterrupt):
asyncio.run(main())