Skip to content

Instantly share code, notes, and snippets.

@balloob
Last active November 13, 2016 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balloob/b3d5f008f9db38e8de9da0ddd52e7e2e to your computer and use it in GitHub Desktop.
Save balloob/b3d5f008f9db38e8de9da0ddd52e7e2e to your computer and use it in GitHub Desktop.
Track spectacle bots in Home Assistant https://home-assistant.io
"""
Component to track where spectacles are being sold.
To install:
- Install Home Assistant (duh): https://home-assistant.io
- Add this file as <config dir>/custom_components/sensor/spectacles.py
- Add to configuration.yaml:
sensor:
platform: spectacles
"""
import asyncio
import logging
import async_timeout
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_PICTURE, ATTR_LATITUDE, ATTR_LONGITUDE,
ATTR_FRIENDLY_NAME)
from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.helpers.event import async_track_utc_time_change
import homeassistant.helpers.config_validation as cv
from homeassistant.util import slugify
DEPENDENCIES = ['zone']
OBJECT_ID_FORMAT = 'spectacles_{}_{}'
URL = "https://www.spectacles.com/locations"
PIC = "https://www.spectacles.com/favicon.ico"
RESPONSE_SCHEMA = vol.Schema({
'coordinates': [vol.Schema({
'lat': cv.latitude,
'lng': cv.longitude,
}, extra=vol.ALLOW_EXTRA)]
}, extra=vol.ALLOW_EXTRA)
_LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup spectacles tracking."""
entities = set()
@asyncio.coroutine
def check_update(time):
"""Check for updated spectacle bots."""
nonlocal entities
with async_timeout.timeout(10, loop=hass.loop):
res = yield from hass.websession.get(URL)
data = yield from res.json()
try:
data = RESPONSE_SCHEMA(data)
except vol.Invalid as ex:
_LOGGER.warning('Got invalid JSON: %s. %s', ex, data)
return
coords = data.get('coordinates')
new_entities = set()
for info in coords:
entity_id = ENTITY_ID_FORMAT.format(
slugify(OBJECT_ID_FORMAT.format(info['lat'], info['lng'])))
name = '{} {}'.format(
int(hass.config.distance(info['lat'], info['lng'])),
hass.config.units.length_unit,
)
hass.states.async_set(
entity_id,
'selling',
{
ATTR_ENTITY_PICTURE: PIC,
ATTR_LATITUDE: info['lat'],
ATTR_LONGITUDE: info['lng'],
ATTR_FRIENDLY_NAME: name
}
)
new_entities.add(entity_id)
for old in (entities - new_entities):
hass.states.async_remove(old)
entities = new_entities
async_track_utc_time_change(hass, check_update, minute='/5')
yield from check_update(None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment