-
Notifications
You must be signed in to change notification settings - Fork 3
/
sensor.py
231 lines (175 loc) · 7.53 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
228
229
230
231
"""Track packages from postnord 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 = "postnord"
REGISTRATIONS_FILE = "postnord.conf"
SERVICE_REGISTER = "register"
SERVICE_UNREGISTER = "unregister"
# Get at https://developer.postnord.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 + ".{}"
POSTNORD_API_findByIdentifier_URL = "https://api2.postnord.com/rest/shipment/v2/trackandtrace/findByIdentifier.json?apikey={}&id={}"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Setup the postnord 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([
PostnordSensor(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([PostnordSensor(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 PostnordSensor(RestoreEntity):
"""Postnord 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(POSTNORD_API_findByIdentifier_URL.format(self._api_key,
self._package_id), timeout=10)
if response.status_code != 200:
_LOGGER.error("API returned {}".format(response.status_code))
return
response = response.json()
if "TrackingInformationResponse" not in response or "shipments" not in response["TrackingInformationResponse"]:
_LOGGER.error("API returned unknown json structure")
return
for shipment in response["TrackingInformationResponse"]["shipments"]:
if shipment["shipmentId"] == self._package_id:
# Found the right shipment
self._state = shipment.get("status", STATE_UNKNOWN)
self._attributes = {}
self._attributes["from"] = shipment.get("consignor", {}).get("name", STATE_UNKNOWN)
self._attributes["status"] = shipment.get("statusText", {}).get("header", STATE_UNKNOWN)
self._attributes["type"] = shipment.get("service", {}).get("name", STATE_UNKNOWN)
self._attributes["estimatedTimeOfArrival"] = shipment.get("estimatedTimeOfArrival", STATE_UNKNOWN)
# Flag where it is, if known
if 'deliveryPoint' in shipment:
if 'coordinate' in shipment['deliveryPoint']:
if len(shipment['deliveryPoint']['coordinate']) > 0:
self._attributes['latitude'] = shipment['deliveryPoint']['coordinate'][0]['northing']
self._attributes['longitude'] = shipment['deliveryPoint']['coordinate'][0]['easting']
# find it under items
for item in shipment.get("items", []):
if item.get("itemId", "") != self._package_id:
continue
for attr in ["dropOffDate", "returnDate"]:
if attr in item:
self._attributes[attr] = item[attr]
try:
for event in item.get("events", []):
# find the last event and publish that status
# Ignoring INFORMED events and such
if event["status"] not in ["EN_ROUTE",
"AVAILABLE_FOR_DELIVERY"]:
continue
self._attributes["location"] = event["location"]["displayName"]
self._attributes["locationType"] = event["location"]["locationType"]
except:
pass
else:
_LOGGER.info("Found other shipmentId {}".format(shipment["shipmentId"]))
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