import os
import time
import httpx
from typing import Any, Dict, List
# Common Samsung TV app name -> appId mappings. App IDs may vary by region/model.
APP_NAME_TO_ID = {
"youtube": "111299001912",
"netflix": "3201907018807",
"prime video": "3201910019365",
"prime_video": "3201910019365",
"amazon prime": "3201910019365",
"hbo": "3201601007230",
"hbo max": "3201601007230",
}
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 get_status(self) -> Dict[str, Any]:
url = f"{self.base_url}/devices/{self.device_id}/status"
with httpx.Client(timeout=10) as client:
response = client.get(url, headers=self._headers)
response.raise_for_status()
return response.json()
def is_on(self) -> bool:
status = self.get_status()
try:
value = status["components"]["main"]["switch"]["switch"]["value"]
return str(value).lower() == "on"
except Exception:
return False
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 open_app(self, app: str) -> Dict[str, Any]:
key = app.strip().lower()
app_id = APP_NAME_TO_ID.get(key, app)
return self.send_commands([
{
"component": "main",
"capability": "custom.launchapp",
"command": "launchApp",
"arguments": [app_id],
}
])
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)