core/homeassistant/components/device_tracker/ubus.py

158 lines
5.0 KiB
Python
Raw Normal View History

"""
2016-03-07 17:12:06 +00:00
Support for OpenWRT (ubus) routers.
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.ubus/
"""
import json
2016-02-19 05:27:50 +00:00
import logging
import re
import threading
2016-02-19 05:27:50 +00:00
from datetime import timedelta
import requests
2016-09-04 08:06:16 +00:00
import voluptuous as vol
2016-09-04 08:06:16 +00:00
import homeassistant.helpers.config_validation as cv
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
from homeassistant.util import Throttle
2016-03-07 17:12:06 +00:00
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
2016-09-04 08:06:16 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string
})
def get_scanner(hass, config):
2016-03-07 20:18:53 +00:00
"""Validate the configuration and return an ubus scanner."""
scanner = UbusDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None
class UbusDeviceScanner(DeviceScanner):
"""
2016-03-07 20:18:53 +00:00
This class queries a wireless router running OpenWrt firmware.
2015-10-24 09:20:57 +00:00
2016-03-07 20:18:53 +00:00
Adapted from Tomato scanner.
"""
def __init__(self, config):
2016-03-07 20:18:53 +00:00
"""Initialize the scanner."""
host = config[CONF_HOST]
username, password = config[CONF_USERNAME], config[CONF_PASSWORD]
self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);")
self.lock = threading.Lock()
self.last_results = {}
self.url = 'http://{}/ubus'.format(host)
2015-10-24 09:20:57 +00:00
self.session_id = _get_session_id(self.url, username, password)
self.hostapd = []
2015-10-24 09:20:57 +00:00
self.leasefile = None
self.mac2name = None
self.success_init = self.session_id 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."""
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."""
with self.lock:
if self.leasefile is None:
result = _req_json_rpc(
self.url, self.session_id, 'call', 'uci', 'get',
config="dhcp", type="dnsmasq")
if result:
2015-10-26 10:50:09 +00:00
values = result["values"].values()
self.leasefile = next(iter(values))["leasefile"]
else:
2015-10-24 09:20:57 +00:00
return
if self.mac2name is None:
result = _req_json_rpc(
self.url, self.session_id, 'call', 'file', 'read',
path=self.leasefile)
if result:
self.mac2name = dict()
for line in result["data"].splitlines():
2015-10-26 10:50:09 +00:00
hosts = line.split(" ")
self.mac2name[hosts[1].upper()] = hosts[3]
else:
# Error, handled in the _req_json_rpc
return
2015-10-24 09:20:57 +00:00
return self.mac2name.get(device.upper(), None)
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
2016-03-07 20:18:53 +00:00
"""Ensure the information from the Luci router is up to date.
Returns boolean if scanning successful.
"""
if not self.success_init:
return False
with self.lock:
_LOGGER.info("Checking ARP")
2015-10-24 09:20:57 +00:00
if not self.hostapd:
hostapd = _req_json_rpc(
self.url, self.session_id, 'list', 'hostapd.*', '')
2015-10-26 10:32:00 +00:00
self.hostapd.extend(hostapd.keys())
2015-10-24 09:20:57 +00:00
self.last_results = []
2015-10-24 09:20:57 +00:00
results = 0
for hostapd in self.hostapd:
result = _req_json_rpc(
self.url, self.session_id, 'call', hostapd, 'get_clients')
2015-10-24 09:20:57 +00:00
if result:
2015-10-24 09:20:57 +00:00
results = results + 1
2015-10-26 10:32:00 +00:00
self.last_results.extend(result['clients'].keys())
2015-10-26 10:32:00 +00:00
return bool(results)
2015-10-24 09:20:57 +00:00
2015-10-26 10:50:09 +00:00
def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params):
2016-03-07 17:12:06 +00:00
"""Perform one JSON RPC operation."""
2015-10-24 09:20:57 +00:00
data = json.dumps({"jsonrpc": "2.0",
"id": 1,
"method": rpcmethod,
"params": [session_id,
subsystem,
method,
2015-10-26 10:50:09 +00:00
params]})
try:
res = requests.post(url, data=data, timeout=5)
2015-10-24 09:20:57 +00:00
except requests.exceptions.Timeout:
return
2015-10-24 09:20:57 +00:00
if res.status_code == 200:
response = res.json()
2015-10-24 09:20:57 +00:00
2015-10-26 10:50:09 +00:00
if rpcmethod == "call":
return response["result"][1]
else:
return response["result"]
2015-10-24 09:20:57 +00:00
def _get_session_id(url, username, password):
2016-03-07 17:12:06 +00:00
"""Get the authentication token for the given host+username+password."""
2015-10-24 09:20:57 +00:00
res = _req_json_rpc(url, "00000000000000000000000000000000", 'call',
'session', 'login', username=username,
password=password)
return res["ubus_rpc_session"]