core/homeassistant/components/device_tracker/thomson.py

133 lines
4.3 KiB
Python
Raw Normal View History

2015-08-27 23:02:26 +00:00
"""
2016-03-07 17:12:06 +00:00
Support for THOMSON routers.
2015-08-27 23:02:26 +00:00
2015-10-13 18:52:30 +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.thomson/
2015-08-27 23:02:26 +00:00
"""
import logging
import re
import telnetlib
2016-02-19 05:27:50 +00:00
import threading
from datetime import timedelta
2015-08-27 23:02:26 +00:00
import voluptuous as vol
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
2015-08-27 23:02:26 +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-08-27 23:02:26 +00:00
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
_DEVICES_REGEX = re.compile(
r'(?P<mac>(([0-9a-f]{2}[:-]){5}([0-9a-f]{2})))\s'
r'(?P<ip>([0-9]{1,3}[\.]){3}[0-9]{1,3})\s+'
r'(?P<status>([^\s]+))\s+'
r'(?P<type>([^\s]+))\s+'
r'(?P<intf>([^\s]+))\s+'
r'(?P<hwintf>([^\s]+))\s+'
2015-08-27 23:02:26 +00:00
r'(?P<host>([^\s]+))')
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string
})
2015-08-27 23:09:24 +00:00
2015-08-27 23:02:26 +00:00
# pylint: disable=unused-argument
def get_scanner(hass, config):
2016-03-07 20:18:53 +00:00
"""Validate the configuration and return a THOMSON scanner."""
2015-08-27 23:02:26 +00:00
scanner = ThomsonDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None
class ThomsonDeviceScanner(DeviceScanner):
2016-03-07 20:18:53 +00:00
"""This class queries a router running THOMSON firmware."""
2015-08-27 23:02:26 +00:00
def __init__(self, config):
2016-03-07 20:18:53 +00:00
"""Initialize the scanner."""
2015-08-27 23:02:26 +00:00
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
self.password = config[CONF_PASSWORD]
self.lock = threading.Lock()
self.last_results = {}
2016-03-07 20:18:53 +00:00
# Test the router is accessible.
2015-08-27 23:02:26 +00:00
data = self.get_thomson_data()
self.success_init = data 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-08-27 23:02:26 +00:00
self._update_info()
return [client['mac'] for client in 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-08-27 23:02:26 +00:00
if not self.last_results:
return None
for client in self.last_results:
if client['mac'] == device:
return client['host']
return None
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
2016-03-07 20:18:53 +00:00
"""Ensure the information from the THOMSON router is up to date.
Return boolean if scanning successful.
"""
2015-08-27 23:02:26 +00:00
if not self.success_init:
return False
with self.lock:
_LOGGER.info('Checking ARP')
2015-08-27 23:02:26 +00:00
data = self.get_thomson_data()
if not data:
return False
2015-08-27 23:09:24 +00:00
2016-03-07 20:18:53 +00:00
# Flag C stands for CONNECTED
2015-08-27 23:02:26 +00:00
active_clients = [client for client in data.values() if
client['status'].find('C') != -1]
self.last_results = active_clients
return True
def get_thomson_data(self):
2016-03-07 17:12:06 +00:00
"""Retrieve data from THOMSON and return parsed result."""
2015-08-27 23:02:26 +00:00
try:
telnet = telnetlib.Telnet(self.host)
telnet.read_until(b'Username : ')
telnet.write((self.username + '\r\n').encode('ascii'))
telnet.read_until(b'Password : ')
telnet.write((self.password + '\r\n').encode('ascii'))
telnet.read_until(b'=>')
telnet.write(('hostmgr list\r\n').encode('ascii'))
devices_result = telnet.read_until(b'=>').split(b'\r\n')
telnet.write('exit\r\n'.encode('ascii'))
except EOFError:
_LOGGER.exception('Unexpected response from router')
2015-08-27 23:02:26 +00:00
return
except ConnectionRefusedError:
_LOGGER.exception('Connection refused by router,'
' is telnet enabled?')
2015-08-27 23:02:26 +00:00
return
devices = {}
for device in devices_result:
match = _DEVICES_REGEX.search(device.decode('utf-8'))
if match:
devices[match.group('ip')] = {
'ip': match.group('ip'),
'mac': match.group('mac').upper(),
'host': match.group('host'),
'status': match.group('status')
}
return devices