forked from renat85/home_assistant_yandex_geocode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yandex_geocode.py
293 lines (249 loc) · 10.2 KB
/
yandex_geocode.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""
Support for Yandex Geocode sensors.
"""
# -*- coding: utf-8 -*-
from datetime import datetime
from datetime import timedelta
import logging
import json
import requests
from requests import get
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_API_KEY, CONF_NAME, CONF_SCAN_INTERVAL, ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE)
import homeassistant.helpers.location as location
from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_ORIGIN = 'origin'
CONF_OPTIONS = 'options'
CONF_DISPLAY_ZONE = 'display_zone'
CONF_ATTRIBUTION = "Data provided by https://geocode-maps.yandex.ru"
CONF_GRAVATAR = 'gravatar'
ATTR_STREET = 'Улица'
ATTR_STREET_NUMBER = 'Номер дома'
ATTR_CITY = 'Город'
ATTR_COUNTY = 'Район'
ATTR_REGION = 'Область'
ATTR_COUNTRY = 'Страна'
DEFAULT_NAME = 'Yandex Geocode'
DEFAULT_OPTION = 'street, city'
DEFAULT_DISPLAY_ZONE = 'display'
DEFAULT_KEY = 'no key'
current = '0,0'
zone_check = 'a'
SCAN_INTERVAL = timedelta(seconds=15)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ORIGIN): cv.string,
vol.Optional(CONF_API_KEY, default=DEFAULT_KEY): cv.string,
vol.Optional(CONF_OPTIONS, default=DEFAULT_OPTION): cv.string,
vol.Optional(CONF_DISPLAY_ZONE, default=DEFAULT_DISPLAY_ZONE): cv.string,
vol.Optional(CONF_GRAVATAR, default=None): vol.Any(None, cv.string),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL):
cv.time_period,
})
TRACKABLE_DOMAINS = ['device_tracker', 'sensor']
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the sensor platform."""
name = config.get(CONF_NAME)
api_key = config.get(CONF_API_KEY)
origin = config.get(CONF_ORIGIN)
options = config.get(CONF_OPTIONS)
display_zone = config.get(CONF_DISPLAY_ZONE)
gravatar = config.get(CONF_GRAVATAR)
add_devices([YandexGeocode(hass, origin, name, api_key, options, display_zone, gravatar)])
class YandexGeocode(Entity):
"""Representation of a Yandex Geocode Sensor."""
def __init__(self, hass, origin, name, api_key, options, display_zone, gravatar):
"""Initialize the sensor."""
self._hass = hass
self._name = name
self._api_key = api_key
self._options = options.lower()
self._display_zone = display_zone.lower()
self._state = "Обновление данных"
self._gravatar = gravatar
self._street = None
self._street_number = None
self._city = None
self._city = None
self._county = None
self._region = None
self._country = None
self._zone_check_current = None
# Check if origin is a trackable entity
if origin.split('.', 1)[0] in TRACKABLE_DOMAINS:
self._origin_entity_id = origin
else:
self._origin = origin
if gravatar is not None:
self._picture = self._get_gravatar_for_email(gravatar)
else:
self._picture = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def entity_picture(self):
"""Return the picture of the device."""
return self._picture
@property
def device_state_attributes(self):
"""Return the state attributes."""
return{
ATTR_STREET: self._street,
ATTR_STREET_NUMBER: self._street_number,
ATTR_CITY: self._city,
ATTR_COUNTY: self._county,
ATTR_REGION: self._region,
ATTR_COUNTRY: self._country,
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
}
@Throttle(SCAN_INTERVAL)
def update(self):
"""Get the latest data and updates the states."""
if hasattr(self, '_origin_entity_id'):
self._origin = self._get_location_from_entity(
self._origin_entity_id
)
"""Update if location has changed."""
global current
global zone_check_count
global zone_check
global user_display
zone_check = self.hass.states.get(self._origin_entity_id).state
zone_check_count = 2
if zone_check == self._zone_check_current:
zone_check_count = 1
if zone_check == 'not_home':
zone_check_count = 2
if zone_check_count == 1:
pass
elif self._origin == None:
pass
elif current == self._origin:
pass
else:
_LOGGER.info("yandex request sent")
self._zone_check_current = self.hass.states.get(self._origin_entity_id).state
zone_check_count = 2
lat = self._origin
current = lat
self._reset_attributes()
if self._api_key == 'no key':
url = "https://geocode-maps.yandex.ru/"
else:
url = "https://geocode-maps.yandex.ru/1.x/?apikey=" + self._api_key + "&geocode=" + lat + "&format=json" + "&results=1" + "&kind=house"
yandex = get(url)
json_input = yandex.text
decoded = json.loads(json_input)
street_number = 'Не определено'
street = 'Не определено'
city = 'Не определено'
state = 'Не определено'
county = 'Не определено'
country = 'Не определено'
for component in decoded['response']['GeoObjectCollection']['featureMember']:
for data in component["GeoObject"]["metaDataProperty"]["GeocoderMetaData"]["Address"]["Components"]:
if 'house' in data["kind"]:
street_number = data["name"]
self._street_number = street_number
if 'street' in data["kind"]:
street = data["name"]
self._street = street
if 'locality' in data["kind"]:
city = data["name"]
self._city = city
if 'province' in data["kind"]:
state = data["name"]
self._region = state
if 'area' in data["kind"]:
county = data["name"]
self._county = county
if 'country' in data["kind"]:
country = data["name"]
self._country = country
try:
if 'formatted' in decoded:
formatted_address = decoded['formatted']
self._formatted_address = formatted_address
except IndexError:
pass
if 'error_message' in decoded:
self._state = decoded['error_message']
_LOGGER.error("You have exceeded your daily requests or entered a incorrect key please create or check the api key.")
elif self._display_zone == 'hide' or zone_check == "not_home":
if street == 'Unnamed Road':
street = alt_street
self._street = alt_street
if city == '':
city = city
if city == '':
city = county
display_options = self._options
user_display = []
if "street" in display_options:
user_display.append(street)
if "street_number" in display_options:
user_display.append(street_number)
if "city" in display_options:
self._append_to_user_display(city)
if "county" in display_options:
self._append_to_user_display(county)
if "state" in display_options:
self._append_to_user_display(state)
if "postal_code" in display_options:
self._append_to_user_display(postal_code)
if "country" in display_options:
self._append_to_user_display(country)
user_display = ', '.join( x for x in user_display )
if user_display == '':
user_display = street
self._state = user_display
else:
self._state = zone_check[0].upper() + zone_check[1:]
def _get_location_from_entity(self, entity_id):
"""Get the origin from the entity state or attributes."""
entity = self._hass.states.get(entity_id)
if entity is None:
_LOGGER.error("Unable to find entity %s", entity_id)
return None
# Check if the entity has origin attributes
if location.has_location(entity):
return self._get_location_from_attributes(entity)
# When everything fails just return nothing
return None
def _reset_attributes(self):
"""Resets attributes."""
self._street = None
self._street_number = None
self._city = None
self._county = None
self._region = None
self._country = None
def _append_to_user_display(self, append_check):
"""Appends attribute to state if false."""
if append_check == "":
pass
else:
user_display.append(append_check)
@staticmethod
def _get_location_from_attributes(entity):
"""Get the lat/long string from an entities attributes."""
attr = entity.attributes
return "%s,%s" % (attr.get(ATTR_LONGITUDE), attr.get(ATTR_LATITUDE))
def _get_gravatar_for_email(self, email: str):
"""Return an 80px Gravatar for the given email address.
Async friendly.
"""
import hashlib
url = 'https://www.gravatar.com/avatar/{}.jpg?s=80&d=wavatar'
return url.format(hashlib.md5(email.encode('utf-8').lower()).hexdigest())