-
Notifications
You must be signed in to change notification settings - Fork 5
/
sensor.py
227 lines (169 loc) · 6.87 KB
/
sensor.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""Track packages from dhl via api"""
from urllib.parse import urlparse
import json
import logging
from datetime import timedelta
import requests
import voluptuous as vol
#from homeassistant.helpers.entity import Entity
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_SCAN_INTERVAL,
STATE_UNKNOWN,
)
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.util.json import load_json
from homeassistant.helpers.json import save_json
from homeassistant.util import Throttle
from homeassistant.helpers.entity_component import EntityComponent
_LOGGER = logging.getLogger(__name__)
DOMAIN = "dhl"
REGISTRATIONS_FILE = "dhl.conf"
SERVICE_REGISTER = "register"
SERVICE_UNREGISTER = "unregister"
# Get at https://developer.dhl.com/
ATTR_API_KEY = "api_key"
ICON = "mdi:package-variant-closed"
SCAN_INTERVAL = timedelta(seconds=1800)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(ATTR_API_KEY): cv.string,
}
)
ATTR_PACKAGE_ID = "package_id"
SUBSCRIPTION_SCHEMA = vol.All(
{
vol.Required(ATTR_PACKAGE_ID): cv.string,
}
)
ENTITY_ID_FORMAT = DOMAIN + ".{}"
DHL_API_track_shipments_URL = "https://api-eu.dhl.com/track/shipments?language=en&trackingNumber={}"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Setup the dhl sensor"""
component = hass.data.get(DOMAIN)
update_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
# Use the EntityComponent to track all packages, and create a group of them
if component is None:
component = hass.data[DOMAIN] = EntityComponent(_LOGGER, DOMAIN, hass,
update_interval)
json_path = hass.config.path(REGISTRATIONS_FILE)
registrations = _load_config(json_path)
api_key = config.get(ATTR_API_KEY)
async def async_service_register(service):
"""Handle package registration."""
package_id = service.data.get(ATTR_PACKAGE_ID).upper()
if package_id in registrations:
raise ValueError("Package allready tracked")
registrations.append(package_id)
await hass.async_add_job(save_json, json_path, registrations)
return await component.async_add_entities([
DHLSensor(hass, package_id, api_key)])
hass.services.async_register(
DOMAIN,
SERVICE_REGISTER,
async_service_register,
schema=SUBSCRIPTION_SCHEMA,
)
async def async_service_unregister(service):
"""Handle package registration."""
package_id = service.data.get(ATTR_PACKAGE_ID)
registrations.remove(package_id)
await hass.async_add_job(save_json, json_path, registrations)
entity_id = ENTITY_ID_FORMAT.format(package_id.lower())
return await component.async_remove_entity(entity_id)
hass.services.async_register(
DOMAIN,
SERVICE_UNREGISTER,
async_service_unregister,
schema=SUBSCRIPTION_SCHEMA,
)
if registrations is None:
return None
return await component.async_add_entities([DHLSensor(hass, package_id, api_key) for package_id in registrations], False)
def _load_config(filename):
"""Load configuration."""
try:
return load_json(filename, [])
except HomeAssistantError:
pass
return []
class DHLSensor(RestoreEntity):
"""DHL Sensor."""
def __init__(self, hass, package_id, api_key):
"""Initialize the sensor."""
self.hass = hass
self._package_id = package_id
self._api_key = api_key
self._attributes = None
self._state = None
self._data = None
@property
def entity_id(self):
"""Return the entity_id of the sensor"""
return ENTITY_ID_FORMAT.format(self._package_id.lower())
@property
def name(self):
"""Return the name of the sensor."""
return "Package {}".format(self._package_id)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._attributes
@property
def icon(self):
"""Icon to use in the frontend."""
return ICON
def update(self):
"""Update sensor state."""
response = requests.get(
DHL_API_track_shipments_URL.format(self._package_id),
headers = {
'Accept': 'application/json',
'DHL-API-Key': self._api_key,
},
timeout=10)
if response.status_code != 200:
_LOGGER.error("API returned {}".format(response.status_code))
return
response = response.json()
if "shipments" not in response:
_LOGGER.error("API returned unknown json structure")
return
for shipment in response["shipments"]:
if shipment["id"] == self._package_id:
# Debug log whole structure for future work
_LOGGER.debug(shipment)
# Found the right shipment
self._state = shipment.get("status", {}).get("statusCode", STATE_UNKNOWN)
self._attributes = {}
# Just put something there
try:
self._attributes["status"] = shipment.get("status", {}).get("status", STATE_UNKNOWN)
oa = shipment.get("origin", {}).get("address", {})
self._attributes["from countryCode"] = oa.get("countryCode", "UNKNOWN")
self._attributes["from addressLocality"] = oa.get("addressLocality", "UNKNOWN")
da = shipment.get("destination", {}).get("address", {})
self._attributes["destination countryCode"] = da.get("countryCode", "UNKNOWN")
self._attributes["destination addressLocality"] = da.get("addressLocality", "UNKNOWN")
sla = shipment.get("status", {}).get("location", {}).get("address", {})
self._attributes["status countryCode"] = sla.get("countryCode", "UNKNOWN")
self._attributes["status addressLocality"] = sla.get("addressLocality", "UNKNOWN")
self._attributes["status timestamp"] = sla.get("timestamp", "UNKNOWN")
except:
pass
else:
_LOGGER.info("Found other id {}".format(shipment["id"]))
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
await super().async_added_to_hass()
if self._state is not None:
return
state = await self.async_get_last_state()
self._state = state and state.state
self._attributes = state and state.attributes