2015-10-23 15:01:42 +00:00
|
|
|
"""
|
2016-03-07 17:12:06 +00:00
|
|
|
Support for OpenWRT (ubus) routers.
|
2015-10-23 15:01:42 +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.ubus/
|
2015-10-23 15:01:42 +00:00
|
|
|
"""
|
|
|
|
import json
|
2016-02-19 05:27:50 +00:00
|
|
|
import logging
|
2015-10-23 15:01:42 +00:00
|
|
|
import re
|
|
|
|
import threading
|
2016-02-19 05:27:50 +00:00
|
|
|
from datetime import timedelta
|
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
import requests
|
2016-09-04 08:06:16 +00:00
|
|
|
import voluptuous as vol
|
2015-10-23 15:01:42 +00:00
|
|
|
|
2016-09-04 08:06:16 +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
|
2015-10-23 15:01:42 +00:00
|
|
|
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.
|
2015-10-23 15:01:42 +00:00
|
|
|
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
|
|
|
|
})
|
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
|
|
|
|
def get_scanner(hass, config):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Validate the configuration and return an ubus scanner."""
|
2015-10-23 15:01:42 +00:00
|
|
|
scanner = UbusDeviceScanner(config[DOMAIN])
|
|
|
|
|
|
|
|
return scanner if scanner.success_init else None
|
|
|
|
|
|
|
|
|
2017-01-02 19:50:42 +00:00
|
|
|
class UbusDeviceScanner(DeviceScanner):
|
2015-10-23 15:01:42 +00:00
|
|
|
"""
|
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.
|
2015-10-23 15:01:42 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, config):
|
2016-03-07 20:18:53 +00:00
|
|
|
"""Initialize the scanner."""
|
2015-10-23 15:01:42 +00:00
|
|
|
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)
|
2015-10-23 15:01:42 +00:00
|
|
|
self.hostapd = []
|
2015-10-24 09:20:57 +00:00
|
|
|
self.leasefile = None
|
2015-10-23 15:01:42 +00:00
|
|
|
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."""
|
2015-10-23 15:01:42 +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."""
|
2015-10-23 15:01:42 +00:00
|
|
|
with self.lock:
|
|
|
|
if self.leasefile is None:
|
2017-04-30 05:04:49 +00:00
|
|
|
result = _req_json_rpc(
|
|
|
|
self.url, self.session_id, 'call', 'uci', 'get',
|
|
|
|
config="dhcp", type="dnsmasq")
|
2015-10-23 15:01:42 +00:00
|
|
|
if result:
|
2015-10-26 10:50:09 +00:00
|
|
|
values = result["values"].values()
|
|
|
|
self.leasefile = next(iter(values))["leasefile"]
|
2015-10-23 15:01:42 +00:00
|
|
|
else:
|
2015-10-24 09:20:57 +00:00
|
|
|
return
|
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
if self.mac2name is None:
|
2017-04-30 05:04:49 +00:00
|
|
|
result = _req_json_rpc(
|
|
|
|
self.url, self.session_id, 'call', 'file', 'read',
|
|
|
|
path=self.leasefile)
|
2015-10-23 15:01:42 +00:00
|
|
|
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]
|
2015-10-23 15:01:42 +00:00
|
|
|
else:
|
|
|
|
# Error, handled in the _req_json_rpc
|
|
|
|
return
|
2015-10-24 09:20:57 +00:00
|
|
|
|
2015-10-23 15:01:42 +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.
|
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
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
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
if not self.hostapd:
|
2017-04-30 05:04:49 +00:00
|
|
|
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
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
self.last_results = []
|
2015-10-24 09:20:57 +00:00
|
|
|
results = 0
|
2015-10-23 15:01:42 +00:00
|
|
|
for hostapd in self.hostapd:
|
2017-04-30 05:04:49 +00:00
|
|
|
result = _req_json_rpc(
|
|
|
|
self.url, self.session_id, 'call', hostapd, 'get_clients')
|
2015-10-24 09:20:57 +00:00
|
|
|
|
2015-10-23 15:01:42 +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-23 15:01:42 +00:00
|
|
|
|
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
|
|
|
|
2015-10-23 15:01:42 +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]})
|
2015-10-23 15:01:42 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
res = requests.post(url, data=data, timeout=5)
|
2015-10-24 09:20:57 +00:00
|
|
|
|
2015-10-23 15:01:42 +00:00
|
|
|
except requests.exceptions.Timeout:
|
|
|
|
return
|
2015-10-24 09:20:57 +00:00
|
|
|
|
2015-10-23 15:01:42 +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":
|
2015-10-23 15:01:42 +00:00
|
|
|
return response["result"][1]
|
|
|
|
else:
|
|
|
|
return response["result"]
|
|
|
|
|
2015-10-24 09:20:57 +00:00
|
|
|
|
2015-10-23 15:01:42 +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)
|
2015-10-23 15:01:42 +00:00
|
|
|
return res["ubus_rpc_session"]
|