From 29c9c5a7eca4854940f695e76b8fe48f172d06d5 Mon Sep 17 00:00:00 2001 From: Krzysztof Koziarek Date: Fri, 23 Oct 2015 17:01:42 +0200 Subject: [PATCH 1/5] Add new OpenWRT presence detection routine based on ubus instead of luci --- .../components/device_tracker/ubus.py | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 homeassistant/components/device_tracker/ubus.py diff --git a/homeassistant/components/device_tracker/ubus.py b/homeassistant/components/device_tracker/ubus.py new file mode 100644 index 00000000000..1e650297399 --- /dev/null +++ b/homeassistant/components/device_tracker/ubus.py @@ -0,0 +1,171 @@ +""" +homeassistant.components.device_tracker.ubus +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Device tracker platform that supports scanning a OpenWRT router for device +presence. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/device_tracker.ubus.html +""" +import logging +import json +from datetime import timedelta +import re +import threading +import requests + +from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD +from homeassistant.helpers import validate_config +from homeassistant.util import Throttle +from homeassistant.components.device_tracker import DOMAIN + +# Return cached results if last scan was less then this time ago +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) + +_LOGGER = logging.getLogger(__name__) + + +def get_scanner(hass, config): + """ Validates config and returns a Luci scanner. """ + if not validate_config(config, + {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]}, + _LOGGER): + return None + + scanner = UbusDeviceScanner(config[DOMAIN]) + + return scanner if scanner.success_init else None + + +# pylint: disable=too-many-instance-attributes +class UbusDeviceScanner(object): + """ + This class queries a wireless router running OpenWrt firmware + for connected devices. Adapted from Tomato scanner. + + Configure your routers' ubus ACL based on following instructions: + + http://wiki.openwrt.org/doc/techref/ubus + + Read only access will be fine. + + To use this class you have to install rpcd-mod-file package in your OpenWrt router: + + opkg install rpcd-mod-file + + """ + + def __init__(self, config): + host = config[CONF_HOST] + username, password = config[CONF_USERNAME], config[CONF_PASSWORD] + + self.parse_api_pattern = re.compile(r"(?P\w*) = (?P.*);") + self.lock = threading.Lock() + self.last_results = {} + self.url = 'http://{}/ubus'.format(host) + + self.session_id= _get_session_id(self.url, username, password) + self.hostapd = [] + self.leasefile = None + self.mac2name = None + self.success_init = self.session_id is not None + + def scan_devices(self): + """ + Scans for new devices and return a list containing found device ids. + """ + + self._update_info() + + return self.last_results + + def get_device_name(self, device): + """ Returns 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: + self.leasefile=next (iter (result["values"].values()))["leasefile"] + else: + 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(): + [time, mac, ip, name, lid] = line.split(" ") + self.mac2name[mac.upper()] = name + else: + # Error, handled in the _req_json_rpc + return + + return self.mac2name.get(device.upper(), None) + + @Throttle(MIN_TIME_BETWEEN_SCANS) + def _update_info(self): + """ + Ensures 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") + + if not self.hostapd: + hostapd = _req_json_rpc(self.url, self.session_id, 'list', 'hostapd.*', '') + for key in hostapd.keys(): + self.hostapd.append(key) + + self.last_results = [] + results = 0 + for hostapd in self.hostapd: + result = _req_json_rpc(self.url, self.session_id, 'call', hostapd, 'get_clients') + + if result: + results = results + 1 + for key in result["clients"].keys(): + self.last_results.append(key) + + if results: + return True + else: + return False + +def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): + """ Perform one JSON RPC operation. """ + + data = json.dumps({ "jsonrpc": "2.0", + "id": 1, + "method": rpcmethod, + "params": [ session_id, + subsystem, + method, + params] + }) + + try: + res = requests.post(url, data=data, timeout=5) + + except requests.exceptions.Timeout: + return + + if res.status_code == 200: + response = res.json() + + if (rpcmethod == "call"): + return response["result"][1] + else: + return response["result"] + +def _get_session_id(url, username, password): + """ Get authentication token for the given host+username+password. """ + res = _req_json_rpc(url, "00000000000000000000000000000000", 'call', 'session', 'login', username=username, password=password) + return res["ubus_rpc_session"] + + +# root@dom:~# ubus call uci get '{ "config": "dhcp", "type": "dnsmasq" }' \ No newline at end of file From 50fbd83b3d7c131744c90cc40bc68cbc823d9eee Mon Sep 17 00:00:00 2001 From: Krzysztof Koziarek Date: Sat, 24 Oct 2015 11:20:57 +0200 Subject: [PATCH 2/5] corrected flake8 warnings --- .../components/device_tracker/ubus.py | 88 ++++++++++--------- 1 file changed, 48 insertions(+), 40 deletions(-) diff --git a/homeassistant/components/device_tracker/ubus.py b/homeassistant/components/device_tracker/ubus.py index 1e650297399..a231af02be7 100644 --- a/homeassistant/components/device_tracker/ubus.py +++ b/homeassistant/components/device_tracker/ubus.py @@ -46,13 +46,14 @@ class UbusDeviceScanner(object): Configure your routers' ubus ACL based on following instructions: http://wiki.openwrt.org/doc/techref/ubus - + Read only access will be fine. - - To use this class you have to install rpcd-mod-file package in your OpenWrt router: - + + To use this class you have to install rpcd-mod-file package + in your OpenWrt router: + opkg install rpcd-mod-file - + """ def __init__(self, config): @@ -64,9 +65,9 @@ class UbusDeviceScanner(object): self.last_results = {} self.url = 'http://{}/ubus'.format(host) - self.session_id= _get_session_id(self.url, username, password) + self.session_id = _get_session_id(self.url, username, password) self.hostapd = [] - self.leasefile = None + self.leasefile = None self.mac2name = None self.success_init = self.session_id is not None @@ -84,24 +85,28 @@ class UbusDeviceScanner(object): with self.lock: if self.leasefile is None: - result = _req_json_rpc(self.url, self.session_id, 'call', 'uci', 'get', config="dhcp", type="dnsmasq") + result = _req_json_rpc(self.url, self.session_id, + 'call', 'uci', 'get', + config="dhcp", type="dnsmasq") if result: - self.leasefile=next (iter (result["values"].values()))["leasefile"] + self.leasefile = next(iter(result["values"]. + values()))["leasefile"] else: - return - + return + if self.mac2name is None: - result = _req_json_rpc(self.url, self.session_id, 'call', 'file', 'read', path=self.leasefile) - + 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(): [time, mac, ip, name, lid] = line.split(" ") - self.mac2name[mac.upper()] = name + self.mac2name[mac.upper()] = name else: # Error, handled in the _req_json_rpc return - + return self.mac2name.get(device.upper(), None) @Throttle(MIN_TIME_BETWEEN_SCANS) @@ -115,57 +120,60 @@ class UbusDeviceScanner(object): with self.lock: _LOGGER.info("Checking ARP") - + if not self.hostapd: - hostapd = _req_json_rpc(self.url, self.session_id, 'list', 'hostapd.*', '') + hostapd = _req_json_rpc(self.url, self.session_id, + 'list', 'hostapd.*', '') for key in hostapd.keys(): self.hostapd.append(key) - + self.last_results = [] - results = 0 + results = 0 for hostapd in self.hostapd: - result = _req_json_rpc(self.url, self.session_id, 'call', hostapd, 'get_clients') - + result = _req_json_rpc(self.url, self.session_id, + 'call', hostapd, 'get_clients') + if result: - results = results + 1 + results = results + 1 for key in result["clients"].keys(): self.last_results.append(key) - - if results: + + if results: return True else: return False + def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): """ Perform one JSON RPC operation. """ - - data = json.dumps({ "jsonrpc": "2.0", - "id": 1, - "method": rpcmethod, - "params": [ session_id, - subsystem, - method, - params] - }) + + data = json.dumps({"jsonrpc": "2.0", + "id": 1, + "method": rpcmethod, + "params": [session_id, + subsystem, + method, + params] + }) try: res = requests.post(url, data=data, timeout=5) - + except requests.exceptions.Timeout: return - + if res.status_code == 200: response = res.json() - + if (rpcmethod == "call"): return response["result"][1] else: return response["result"] + def _get_session_id(url, username, password): """ Get authentication token for the given host+username+password. """ - res = _req_json_rpc(url, "00000000000000000000000000000000", 'call', 'session', 'login', username=username, password=password) + res = _req_json_rpc(url, "00000000000000000000000000000000", 'call', + 'session', 'login', username=username, + password=password) return res["ubus_rpc_session"] - - -# root@dom:~# ubus call uci get '{ "config": "dhcp", "type": "dnsmasq" }' \ No newline at end of file From c9f1dce6a2e6b0669f9775fd6973d1b886f2b6b1 Mon Sep 17 00:00:00 2001 From: Krzysztof Koziarek Date: Mon, 26 Oct 2015 11:32:00 +0100 Subject: [PATCH 3/5] Coding style fixes --- homeassistant/components/device_tracker/ubus.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/device_tracker/ubus.py b/homeassistant/components/device_tracker/ubus.py index a231af02be7..3135993e91b 100644 --- a/homeassistant/components/device_tracker/ubus.py +++ b/homeassistant/components/device_tracker/ubus.py @@ -124,8 +124,7 @@ class UbusDeviceScanner(object): if not self.hostapd: hostapd = _req_json_rpc(self.url, self.session_id, 'list', 'hostapd.*', '') - for key in hostapd.keys(): - self.hostapd.append(key) + self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 @@ -135,14 +134,9 @@ class UbusDeviceScanner(object): if result: results = results + 1 - for key in result["clients"].keys(): - self.last_results.append(key) - - if results: - return True - else: - return False + self.last_results.extend(result['clients'].keys()) + return bool(results) def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): """ Perform one JSON RPC operation. """ From fbb73dd5da7ade81683fc404c8e66ae78211b4c3 Mon Sep 17 00:00:00 2001 From: Krzysztof Koziarek Date: Mon, 26 Oct 2015 11:50:09 +0100 Subject: [PATCH 4/5] fixed pylint warnings --- homeassistant/components/device_tracker/ubus.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/device_tracker/ubus.py b/homeassistant/components/device_tracker/ubus.py index 3135993e91b..195ed33e77b 100644 --- a/homeassistant/components/device_tracker/ubus.py +++ b/homeassistant/components/device_tracker/ubus.py @@ -89,8 +89,8 @@ class UbusDeviceScanner(object): 'call', 'uci', 'get', config="dhcp", type="dnsmasq") if result: - self.leasefile = next(iter(result["values"]. - values()))["leasefile"] + values = result["values"].values() + self.leasefile = next(iter(values))["leasefile"] else: return @@ -101,8 +101,8 @@ class UbusDeviceScanner(object): if result: self.mac2name = dict() for line in result["data"].splitlines(): - [time, mac, ip, name, lid] = line.split(" ") - self.mac2name[mac.upper()] = name + hosts = line.split(" ") + self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the _req_json_rpc return @@ -138,6 +138,7 @@ class UbusDeviceScanner(object): return bool(results) + def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): """ Perform one JSON RPC operation. """ @@ -147,8 +148,7 @@ def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): "params": [session_id, subsystem, method, - params] - }) + params]}) try: res = requests.post(url, data=data, timeout=5) @@ -159,7 +159,7 @@ def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): if res.status_code == 200: response = res.json() - if (rpcmethod == "call"): + if rpcmethod == "call": return response["result"][1] else: return response["result"] From 649124d16217a744e53d6e7dfaf82933169fa3e0 Mon Sep 17 00:00:00 2001 From: Krzysztof Koziarek Date: Mon, 26 Oct 2015 11:55:20 +0100 Subject: [PATCH 5/5] Added ubus.py to .coveragerc --- .coveragerc | 1 + 1 file changed, 1 insertion(+) diff --git a/.coveragerc b/.coveragerc index 7e474d287c2..b1ec9681fef 100644 --- a/.coveragerc +++ b/.coveragerc @@ -37,6 +37,7 @@ omit = homeassistant/components/device_tracker/asuswrt.py homeassistant/components/device_tracker/ddwrt.py homeassistant/components/device_tracker/luci.py + homeassistant/components/device_tracker/ubus.py homeassistant/components/device_tracker/netgear.py homeassistant/components/device_tracker/nmap_tracker.py homeassistant/components/device_tracker/thomson.py