Advertisement
jarekmor

HA API - automation list

Sep 10th, 2021
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # przed uruchomieniem programu nalezy w tym samym folderze utworzyć następujące pliki:
  2. # - HA_API_automations.json - pusty plik, w którym będzie zapisywana lista automatyzacji
  3. # - HA_API_KEY.txt - plik z wygenerowanym w HA "Long-Lived Access Tokens"
  4.  
  5. from requests import get
  6. import json
  7. import os
  8. import datetime
  9.  
  10. end_time = datetime.datetime.now()
  11. start_time = end_time - datetime.timedelta(days=1)
  12.  
  13. # definicja END_POINT w API HA
  14. END_POINT = "history/period/{}?end_time={}".format(start_time, end_time)
  15.  
  16. # adres serwera z HA
  17. url = "http://192.168.1.5:8123/api/{}".format(END_POINT)
  18.  
  19. # otwieramy plik i czytamy "Long-Lived Access Tokens" wygenerowany w HA
  20. # Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  21. f = open("HA_API_KEY.txt", "r")
  22. HA_API_KEY = f.readline()
  23. f.close()
  24.  
  25. headers={
  26.         "Authorization": HA_API_KEY,
  27.         "content-type": "application/json"
  28.     }
  29.  
  30. response = get(url, headers=headers)
  31.  
  32. # zapis odpowiedzi do formatu JSON
  33. response_json = response.json()
  34.  
  35. table = []
  36. dict = {}
  37. for x in range(len(response_json)):
  38.     if "automation." in response_json[x][0]["entity_id"]:
  39.  
  40.         dict = {
  41.         "entity_name": response_json[x][0]["entity_id"],
  42.         "state": response_json[x][0]["state"],
  43.         "last_triggered": response_json[x][0]["attributes"]["last_triggered"][0:19].replace("T", " ")
  44.         }
  45.         table.append(dict)
  46.  
  47. # utworzenie posortowanej po dacie liście encji "automation" z danego okresu
  48. new_table = sorted(table, key=lambda k: datetime.datetime.strptime(k["last_triggered"], "%Y-%m-%d %H:%M:%S"), reverse=True)
  49.  
  50. #zapis wygenerowanej listy do pliku
  51. json_object = json.dumps(new_table, indent = 4)
  52. with open("HA_API_automations.json", "w") as outfile:
  53.     outfile.write(json_object)
  54.  
  55.  
  56.  
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement