2015-05-11 16:05:46 +00:00
|
|
|
"""
|
2016-03-07 20:18:53 +00:00
|
|
|
Support for OpenWRT (luci) routers.
|
2015-05-11 16:05:46 +00:00
|
|
|
|
2015-10-13 18:50:53 +00:00
|
|
|
For more details about this platform, please refer to the documentation at
|
2015-11-09 12:12:18 +00:00
|
|
|
https://home-assistant.io/components/device_tracker.luci/
|
2015-05-11 16:05:46 +00:00
|
|
|
"""
|
2014-11-12 05:39:17 +00:00
|
|
|
import json
|
2016-02-19 05:27:50 +00:00
|
|
|
import logging
|
2014-11-12 05:39:17 +00:00
|
|
|
import re
|
|
|
|
import threading
|
2016-02-19 05:27:50 +00:00
|
|
|
from datetime import timedelta
|
|
|
|
|
2014-11-12 05:39:17 +00:00
|
|
|
import requests
|
2016-09-05 17:37:36 +00:00
|
|
|
import voluptuous as vol
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2016-09-05 17:37:36 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2017-01-02 19:50:42 +00:00
|
|
|
from homeassistant.components.device_tracker import (
|
|
|
|
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
|
2016-02-19 05:27:50 +00:00
|
|
|
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
|
2014-12-07 07:57:02 +00:00
|
|
|
from homeassistant.util import Throttle
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2016-03-07 17:12:06 +00:00
|
|
|
# Return cached results if last scan was less then this time ago.
|
2014-11-12 05:39:17 +00:00
|
|
|
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2016-09-05 17:37:36 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
|
|
|
vol.Required(CONF_HOST): cv.string,
|
|
|
|
vol.Required(CONF_USERNAME): cv.string,
|
|
|
|
vol.Required(CONF_PASSWORD): cv.string
|
|
|
|
})
|
|
|
|
|
2014-11-12 05:39:17 +00:00
|
|
|
|
|
|
|
def get_scanner(hass, config):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Validate the configuration and return a Luci scanner."""
|
2014-11-12 05:39:17 +00:00
|
|
|
scanner = LuciDeviceScanner(config[DOMAIN])
|
|
|
|
|
|
|
|
return scanner if scanner.success_init else None
|
|
|
|
|
|
|
|
|
2017-01-02 19:50:42 +00:00
|
|
|
class LuciDeviceScanner(DeviceScanner):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""This class queries a wireless router running OpenWrt firmware.
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2016-03-07 20:18:53 +00:00
|
|
|
Adapted from Tomato scanner.
|
2014-11-12 05:39:17 +00:00
|
|
|
"""
|
2016-03-07 20:18:53 +00:00
|
|
|
|
2014-11-12 05:39:17 +00:00
|
|
|
def __init__(self, config):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Initialize the scanner."""
|
2014-12-07 07:57:02 +00:00
|
|
|
host = config[CONF_HOST]
|
|
|
|
username, password = config[CONF_USERNAME], config[CONF_PASSWORD]
|
2014-11-12 05:39:17 +00:00
|
|
|
|
|
|
|
self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);")
|
|
|
|
|
|
|
|
self.lock = threading.Lock()
|
|
|
|
|
|
|
|
self.last_results = {}
|
|
|
|
|
|
|
|
self.token = _get_token(host, username, password)
|
|
|
|
self.host = host
|
|
|
|
|
|
|
|
self.mac2name = None
|
|
|
|
self.success_init = self.token is not None
|
|
|
|
|
|
|
|
def scan_devices(self):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Scan for new devices and return a list with found device IDs."""
|
2014-11-12 05:39:17 +00:00
|
|
|
self._update_info()
|
|
|
|
return self.last_results
|
|
|
|
|
|
|
|
def get_device_name(self, device):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Return the name of the given device or None if we don't know."""
|
2014-11-12 05:39:17 +00:00
|
|
|
with self.lock:
|
|
|
|
if self.mac2name is None:
|
|
|
|
url = 'http://{}/cgi-bin/luci/rpc/uci'.format(self.host)
|
|
|
|
result = _req_json_rpc(url, 'get_all', 'dhcp',
|
|
|
|
params={'auth': self.token})
|
|
|
|
if result:
|
|
|
|
hosts = [x for x in result.values()
|
|
|
|
if x['.type'] == 'host' and
|
|
|
|
'mac' in x and 'name' in x]
|
2015-05-30 13:30:34 +00:00
|
|
|
mac2name_list = [
|
|
|
|
(x['mac'].upper(), x['name']) for x in hosts]
|
2014-11-12 05:39:17 +00:00
|
|
|
self.mac2name = dict(mac2name_list)
|
|
|
|
else:
|
|
|
|
# Error, handled in the _req_json_rpc
|
|
|
|
return
|
2015-05-30 13:30:34 +00:00
|
|
|
return self.mac2name.get(device.upper(), None)
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2014-12-07 07:57:02 +00:00
|
|
|
@Throttle(MIN_TIME_BETWEEN_SCANS)
|
2014-11-12 05:39:17 +00:00
|
|
|
def _update_info(self):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Ensure the information from the Luci router is up to date.
|
|
|
|
|
2015-09-07 17:19:11 +00:00
|
|
|
Returns boolean if scanning successful.
|
|
|
|
"""
|
2014-11-12 05:39:17 +00:00
|
|
|
if not self.success_init:
|
|
|
|
return False
|
2014-12-04 09:14:27 +00:00
|
|
|
|
2014-11-12 05:39:17 +00:00
|
|
|
with self.lock:
|
2016-09-05 17:37:36 +00:00
|
|
|
_LOGGER.info('Checking ARP')
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2014-12-04 09:14:27 +00:00
|
|
|
url = 'http://{}/cgi-bin/luci/rpc/sys'.format(self.host)
|
|
|
|
result = _req_json_rpc(url, 'net.arptable',
|
|
|
|
params={'auth': self.token})
|
|
|
|
if result:
|
2015-01-07 02:36:39 +00:00
|
|
|
self.last_results = []
|
2015-01-07 02:57:06 +00:00
|
|
|
for device_entry in result:
|
|
|
|
# Check if the Flags for each device contain
|
|
|
|
# NUD_REACHABLE and if so, add it to last_results
|
|
|
|
if int(device_entry['Flags'], 16) & 0x2:
|
|
|
|
self.last_results.append(device_entry['HW address'])
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2014-12-04 09:14:27 +00:00
|
|
|
return True
|
2014-11-12 05:39:17 +00:00
|
|
|
|
2014-12-04 09:14:27 +00:00
|
|
|
return False
|
2014-11-12 05:39:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _req_json_rpc(url, method, *args, **kwargs):
|
2016-03-07 17:12:06 +00:00
|
|
|
"""Perform one JSON RPC operation."""
|
2014-11-12 05:39:17 +00:00
|
|
|
data = json.dumps({'method': method, 'params': args})
|
|
|
|
try:
|
|
|
|
res = requests.post(url, data=data, timeout=5, **kwargs)
|
|
|
|
except requests.exceptions.Timeout:
|
2016-09-05 17:37:36 +00:00
|
|
|
_LOGGER.exception('Connection to the router timed out')
|
2014-11-12 05:39:17 +00:00
|
|
|
return
|
|
|
|
if res.status_code == 200:
|
|
|
|
try:
|
|
|
|
result = res.json()
|
|
|
|
except ValueError:
|
|
|
|
# If json decoder could not parse the response
|
2016-09-05 17:37:36 +00:00
|
|
|
_LOGGER.exception('Failed to parse response from luci')
|
2014-11-12 05:39:17 +00:00
|
|
|
return
|
|
|
|
try:
|
|
|
|
return result['result']
|
|
|
|
except KeyError:
|
2016-09-05 17:37:36 +00:00
|
|
|
_LOGGER.exception('No result in response from luci')
|
2014-11-12 05:39:17 +00:00
|
|
|
return
|
|
|
|
elif res.status_code == 401:
|
|
|
|
# Authentication error
|
|
|
|
_LOGGER.exception(
|
|
|
|
"Failed to authenticate, "
|
|
|
|
"please check your username and password")
|
|
|
|
return
|
|
|
|
else:
|
2016-09-05 17:37:36 +00:00
|
|
|
_LOGGER.error('Invalid response from luci: %s', res)
|
2014-11-12 05:39:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _get_token(host, username, password):
|
2016-03-07 17:12:06 +00:00
|
|
|
"""Get authentication token for the given host+username+password."""
|
2014-11-12 05:39:17 +00:00
|
|
|
url = 'http://{}/cgi-bin/luci/rpc/auth'.format(host)
|
|
|
|
return _req_json_rpc(url, 'login', username, password)
|