-
Notifications
You must be signed in to change notification settings - Fork 0
/
homeassistant.py
82 lines (72 loc) · 2.61 KB
/
homeassistant.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import json
import logging
import os
import sys
from plantronics import Spokes
from requests import post
from requests.exceptions import ConnectionError
class HomeAssistant:
def __init__(self):
try:
with open(os.path.join(sys.path[0], "secrets.json")) as secrets_file:
secrets_data = json.load(secrets_file)
except IOError:
logging.error(
(
"The secrets.json file does not exist.",
"Copy secrets.example.json and rename it to secrets.json.",
"Make sure to edit the placeholder",
)
)
raise
self.host = secrets_data["homeAssistantUrl"]
self.accessToken = secrets_data["homeAssistantAccessToken"]
class Sensor(HomeAssistant):
def __init__(self):
self.spo = Spokes()
self.name = self.spo.get_device_info()["Result"]["ProductName"]
self.friendlyName = self.name + " Adapter"
self.icon = "mdi:headset"
def set_sensor(self, state):
sen = Sensor()
self.name = str(sen.name).replace(" ", "_")
self.host = HomeAssistant().host + "/api/states/" + "sensor." + self.name
self.accessToken = HomeAssistant().accessToken
self.computerName = os.environ["COMPUTERNAME"]
self.headers = {
"Authorization": ("Bearer " + self.accessToken),
"content-type": "application/json",
}
try:
self.source = self.spo.get_callmanager_state()["Result"]["Calls"][0][
"Source"
]
except Exception:
self.source = None
try:
response = post(
url=self.host,
headers=self.headers,
data=json.dumps(
{
"state": state,
"attributes": {
"friendly_name": sen.friendlyName,
"icon": sen.icon,
"source": self.source,
"computer_name": self.computerName,
},
}
),
)
except ConnectionError:
logging.warn("Request to Home Assistant failed")
pass
finally:
if response.status_code == 200 or response.status_code == 201:
self.sensorInfo = response.json
return self.sensorInfo
else:
logging.error(
f"Response should have status code 200 or 201, but was: {response.status_code}"
)