core/homeassistant/components/device_tracker/snmp.py

136 lines
4.2 KiB
Python
Raw Normal View History

2015-10-06 21:26:32 +00:00
"""
2016-03-07 17:12:06 +00:00
Support for fetching WiFi associations through SNMP.
2015-10-06 21:26:32 +00:00
2015-10-08 22:27:29 +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.snmp/
2015-10-06 21:26:32 +00:00
"""
2016-02-19 05:27:50 +00:00
import binascii
2015-10-06 21:26:32 +00:00
import logging
import threading
2016-02-19 05:27:50 +00:00
from datetime import timedelta
2015-10-06 21:26:32 +00:00
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
2015-10-08 08:00:30 +00:00
from homeassistant.const import CONF_HOST
2015-10-06 21:26:32 +00:00
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
2015-10-08 08:00:30 +00:00
2017-06-15 19:24:31 +00:00
REQUIREMENTS = ['pysnmp==4.3.8']
2017-02-05 10:22:32 +00:00
CONF_COMMUNITY = 'community'
CONF_AUTHKEY = 'authkey'
CONF_PRIVKEY = 'privkey'
CONF_BASEOID = 'baseoid'
2015-10-06 21:26:32 +00:00
2017-02-05 10:22:32 +00:00
DEFAULT_COMMUNITY = 'public'
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_COMMUNITY, default=DEFAULT_COMMUNITY): cv.string,
2017-02-05 10:22:32 +00:00
vol.Inclusive(CONF_AUTHKEY, 'keys'): cv.string,
vol.Inclusive(CONF_PRIVKEY, 'keys'): cv.string,
vol.Required(CONF_BASEOID): cv.string
})
2015-10-07 21:45:24 +00:00
2015-10-07 21:04:34 +00:00
# pylint: disable=unused-argument
def get_scanner(hass, config):
2016-03-07 20:18:53 +00:00
"""Validate the configuration and return an snmp scanner."""
2015-10-07 21:04:34 +00:00
scanner = SnmpScanner(config[DOMAIN])
2015-10-06 21:26:32 +00:00
return scanner if scanner.success_init else None
class SnmpScanner(DeviceScanner):
2016-03-07 20:18:53 +00:00
"""Queries any SNMP capable Access Point for connected devices."""
2015-10-06 21:26:32 +00:00
def __init__(self, config):
2016-03-07 20:18:53 +00:00
"""Initialize the scanner."""
2015-11-11 21:54:33 +00:00
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.entity import config as cfg
2015-11-11 21:54:33 +00:00
self.snmp = cmdgen.CommandGenerator()
self.host = cmdgen.UdpTransportTarget((config[CONF_HOST], 161))
if CONF_AUTHKEY not in config or CONF_PRIVKEY not in config:
self.auth = cmdgen.CommunityData(config[CONF_COMMUNITY])
else:
self.auth = cmdgen.UsmUserData(
config[CONF_COMMUNITY],
config[CONF_AUTHKEY],
config[CONF_PRIVKEY],
authProtocol=cfg.usmHMACSHAAuthProtocol,
privProtocol=cfg.usmAesCfb128Protocol
)
2015-11-11 21:54:33 +00:00
self.baseoid = cmdgen.MibVariable(config[CONF_BASEOID])
2015-10-06 21:26:32 +00:00
self.lock = threading.Lock()
2015-10-08 10:01:10 +00:00
self.last_results = []
2015-10-06 21:26:32 +00:00
# Test the router is accessible
data = self.get_snmp_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-10-06 21:26:32 +00:00
self._update_info()
return [client['mac'] for client in self.last_results
if client.get('mac')]
2015-10-06 21:26:32 +00:00
2015-10-08 10:24:55 +00:00
# Supressing no-self-use warning
2015-10-08 10:01:10 +00:00
# pylint: disable=R0201
2015-10-06 21:26:32 +00:00
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-08 08:00:30 +00:00
# We have no names
2015-10-06 21:26:32 +00:00
return None
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
"""Ensure the information from the device is up to date.
2016-03-07 20:18:53 +00:00
Return boolean if scanning successful.
2015-10-06 21:26:32 +00:00
"""
if not self.success_init:
return False
with self.lock:
data = self.get_snmp_data()
if not data:
return False
self.last_results = data
return True
def get_snmp_data(self):
"""Fetch MAC addresses from access point via SNMP."""
2015-10-07 21:04:34 +00:00
devices = []
2015-10-06 21:26:32 +00:00
2015-11-11 21:54:33 +00:00
errindication, errstatus, errindex, restable = self.snmp.nextCmd(
self.auth, self.host, self.baseoid)
2015-10-08 08:00:30 +00:00
if errindication:
2015-10-08 14:54:20 +00:00
_LOGGER.error("SNMPLIB error: %s", errindication)
2015-10-06 21:26:32 +00:00
return
# pylint: disable=no-member
2015-10-08 08:00:30 +00:00
if errstatus:
2017-02-05 10:22:32 +00:00
_LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(),
errindex and restable[int(errindex) - 1][0] or '?')
2015-10-07 16:57:01 +00:00
return
2015-10-08 08:00:30 +00:00
for resrow in restable:
for _, val in resrow:
2017-03-27 10:22:59 +00:00
try:
mac = binascii.hexlify(val.asOctets()).decode('utf-8')
except AttributeError:
continue
2017-02-05 10:22:32 +00:00
_LOGGER.debug("Found MAC %s", mac)
2015-10-07 21:45:24 +00:00
mac = ':'.join([mac[i:i+2] for i in range(0, len(mac), 2)])
devices.append({'mac': mac})
2015-10-06 21:26:32 +00:00
return devices