From anonymous, 1 Month ago, written in Python.
Embed
  1. #!/home/florian/proj/ikea-tradfri/.venv/bin/python3
  2.  
  3. import asyncio
  4. import os.path
  5. import pathlib
  6. import sys
  7.  
  8. import pytradfri
  9. from pytradfri import util, error
  10. #from pytradfri.api.libcoap_api import APIFactory
  11. from pytradfri.api.aiocoap_api import APIFactory
  12.  
  13. CONFIG_FILE = os.path.expanduser("~/.config/tradfri_standalone_psk.conf")
  14. HOST = "192.168.0.85"
  15.  
  16. conf = util.load_json(CONFIG_FILE)
  17. identity = conf[HOST]['identity']
  18. psk = conf[HOST]['key']
  19.  
  20. sys.excepthook = sys.__excepthook__
  21.  
  22. async def run():
  23.     #api_factory = APIFactory(host=HOST, psk_id=identity, psk=psk, timeout=2)
  24.     api_factory = await APIFactory.init(host=HOST, psk_id=identity, psk=psk)
  25.  
  26.     async def api(arg):
  27.         for _ in range(10):
  28.             try:
  29.                 return await api_factory.request(arg)
  30.             except error.RequestTimeout:
  31.                 print("Retrying after timeout...", file=sys.stderr)
  32.  
  33.     gateway = pytradfri.Gateway()
  34.  
  35.     devices_commands = await api(gateway.get_devices())
  36.     devices = await api(devices_commands)
  37.  
  38.     groups_commands = await api(gateway.get_groups())
  39.     groups = await api(groups_commands)
  40.  
  41.     # assert len(groups) == 1, groups
  42.     tradfri_groups = [g for g in groups if g.name == 'TRADFRI group']
  43.     assert len(tradfri_groups) == 1
  44.     group = tradfri_groups[0]
  45.  
  46.     moods_commands = await api(group.moods())
  47.     moods = await api(moods_commands)
  48.     curmood = await api(group.mood())
  49.  
  50.     mood_dict = {m.name.lower(): m for m in moods}
  51.     if len(sys.argv) == 1:
  52.         for name, mood in mood_dict.items():
  53.             if mood.id == curmood.id:
  54.                 print(f"* {name}")
  55.             else:
  56.                 print(f"  {name}")
  57.         sys.exit(0)
  58.  
  59.     if len(sys.argv) != 2 or sys.argv[1] not in mood_dict:
  60.         for k in mood_dict:
  61.             print(k)
  62.         sys.exit(1)
  63.            
  64.  
  65.     new_mood = mood_dict[sys.argv[1]]
  66.     await api(group.activate_mood(new_mood.id))
  67.  
  68. asyncio.get_event_loop().run_until_complete(run())
  69.