smartthings.py•1.76 kB
import os
import httpx
from typing import Any, Dict, List
class SmartThingsClient:
def __init__(self, token: str, device_id: str) -> None:
self.base_url = "https://api.smartthings.com/v1"
self.token = token
self.device_id = device_id
self._headers = {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
}
def send_commands(self, commands: List[Dict[str, Any]]) -> Dict[str, Any]:
url = f"{self.base_url}/devices/{self.device_id}/commands"
with httpx.Client(timeout=10) as client:
response = client.post(url, headers=self._headers, json={"commands": commands})
response.raise_for_status()
return response.json()
def turn_on(self) -> Dict[str, Any]:
return self.send_commands([
{"component": "main", "capability": "switch", "command": "on"}
])
def turn_off(self) -> Dict[str, Any]:
return self.send_commands([
{"component": "main", "capability": "switch", "command": "off"}
])
def set_volume(self, level: int) -> Dict[str, Any]:
level = max(0, min(100, int(level)))
return self.send_commands([
{
"component": "main",
"capability": "audioVolume",
"command": "setVolume",
"arguments": [level],
}
])
def get_client_from_env() -> SmartThingsClient:
token = os.environ.get("SMARTTHINGS_TOKEN")
device_id = os.environ.get("SMARTTHINGS_DEVICE_ID")
if not token or not device_id:
raise RuntimeError("SMARTTHINGS_TOKEN and SMARTTHINGS_DEVICE_ID must be set")
return SmartThingsClient(token, device_id)