desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get the dynamic list of tools that temperature is monitored on.'
def get_tools(self):
tools = self.printer_last_reading[0]['temperature'] return tools.keys()
'Send a get request, and return the response as a dict.'
def get(self, endpoint):
now = time.time() if (endpoint == 'job'): last_time = self.job_last_reading[1] if (last_time is not None): if ((now - last_time) < 30.0): return self.job_last_reading[0] elif (endpoint == 'printer'): last_time = self.printer_last_reading[1] if (las...
'Return the value for sensor_type from the provided endpoint.'
def update(self, sensor_type, end_point, group, tool=None):
response = self.get(end_point) if (response is not None): return get_value_from_json(response, sensor_type, group, tool) return response
'Initialize the Tellstick mappings and callbacks.'
def __init__(self, hass, tellcore_lib):
self._id_to_ha_device_map = {} self._id_to_tellcore_device_map = {} self._setup_tellcore_callback(hass, tellcore_lib)
'Handle the actual callback from Tellcore.'
def _tellcore_event_callback(self, tellcore_id, tellcore_command, tellcore_data, cid):
ha_device = self._id_to_ha_device_map.get(tellcore_id, None) if (ha_device is not None): ha_device.update_from_callback(tellcore_command, tellcore_data)
'Register the callback handler.'
def _setup_tellcore_callback(self, hass, tellcore_lib):
callback_id = tellcore_lib.register_device_event(self._tellcore_event_callback) def clean_up_callback(event): 'Unregister the callback bindings.' if (callback_id is not None): tellcore_lib.unregister_callback(callback_id) _LOGGER.debug('Tellstick callback u...
'Register a new HA device to receive callback updates.'
def register_ha_device(self, tellcore_id, ha_device):
self._id_to_ha_device_map[tellcore_id] = ha_device
'Register a list of devices.'
def register_tellcore_devices(self, tellcore_devices):
self._id_to_tellcore_device_map.update({tellcore_device.id: tellcore_device for tellcore_device in tellcore_devices})
'Return a device by tellcore_id.'
def get_tellcore_device(self, tellcore_id):
return self._id_to_tellcore_device_map.get(tellcore_id, None)
'Init the Tellstick device.'
def __init__(self, tellcore_id, tellcore_registry, signal_repetitions):
self._signal_repetitions = signal_repetitions self._state = None self._requested_state = None self._requested_data = None self._repeats_left = 0 self._tellcore_device = tellcore_registry.get_tellcore_device(tellcore_id) self._name = self._tellcore_device.name self._update_from_tellcore()...
'Tell Home Assistant not to poll this device.'
@property def should_poll(self):
return False
'Tellstick devices are always assumed state.'
@property def assumed_state(self):
return True
'Return the name of the device as reported by tellcore.'
@property def name(self):
return self._name
'Return true if the device is on.'
@property def is_on(self):
return self._state
'Turn the value from HA into something useful.'
def _parse_ha_data(self, kwargs):
raise NotImplementedError
'Turn the value recieved from tellcore into something useful.'
def _parse_tellcore_data(self, tellcore_data):
raise NotImplementedError
'Update the device entity state to match the arguments.'
def _update_model(self, new_state, data):
raise NotImplementedError
'Let tellcore update the actual device to the requested state.'
def _send_device_command(self, requested_state, requested_data):
raise NotImplementedError
'Send a tellstick command once and decrease the repeat count.'
def _send_repeated_command(self):
from tellcore.library import TelldusError with TELLSTICK_LOCK: if (self._repeats_left > 0): self._repeats_left -= 1 try: self._send_device_command(self._requested_state, self._requested_data) except TelldusError as err: _LOGGER.error(er...
'Turn on or off the device.'
def _change_device_state(self, new_state, data):
with TELLSTICK_LOCK: self._requested_state = new_state self._requested_data = data self._repeats_left = self._signal_repetitions self._send_repeated_command() self._update_model(new_state, data) self.schedule_update_ha_state()
'Turn the switch on.'
def turn_on(self, **kwargs):
self._change_device_state(True, self._parse_ha_data(kwargs))
'Turn the switch off.'
def turn_off(self, **kwargs):
self._change_device_state(False, None)
'Update the model, from a sent tellcore command and data.'
def _update_model_from_command(self, tellcore_command, tellcore_data):
from tellcore.constants import TELLSTICK_TURNON, TELLSTICK_TURNOFF, TELLSTICK_DIM if (tellcore_command not in [TELLSTICK_TURNON, TELLSTICK_TURNOFF, TELLSTICK_DIM]): _LOGGER.debug('Unhandled tellstick command: %d', tellcore_command) return self._update_model((tellcore_command != TELL...
'Handle updates from the tellcore callback.'
def update_from_callback(self, tellcore_command, tellcore_data):
self._update_model_from_command(tellcore_command, tellcore_data) self.schedule_update_ha_state() if (self._repeats_left > 0): self.hass.async_add_job(self._send_repeated_command)
'Read the current state of the device from the tellcore library.'
def _update_from_tellcore(self):
from tellcore.library import TelldusError from tellcore.constants import TELLSTICK_TURNON, TELLSTICK_TURNOFF, TELLSTICK_DIM with TELLSTICK_LOCK: try: last_command = self._tellcore_device.last_sent_command(((TELLSTICK_TURNON | TELLSTICK_TURNOFF) | TELLSTICK_DIM)) last_data = s...
'Poll the current state of the device.'
def update(self):
self._update_from_tellcore() self.schedule_update_ha_state()
'Initialize the device.'
def __init__(self, vera_device, controller):
self.vera_device = vera_device self.controller = controller self._name = self.vera_device.name self.vera_id = VERA_ID_FORMAT.format(slugify(vera_device.name), vera_device.device_id) self.controller.register(vera_device, self._update_callback) self.update()
'Update the state.'
def _update_callback(self, _device):
self.update() self.schedule_update_ha_state()
'Return the name of the device.'
@property def name(self):
return self._name
'Get polling requirement from vera device.'
@property def should_poll(self):
return self.vera_device.should_poll
'Return the state attributes of the device.'
@property def device_state_attributes(self):
attr = {} if self.vera_device.has_battery: attr[ATTR_BATTERY_LEVEL] = self.vera_device.battery_level if self.vera_device.is_armable: armed = self.vera_device.is_armed attr[ATTR_ARMED] = ('True' if armed else 'False') if self.vera_device.is_trippable: last_tripped = self.v...
'Initialize Logger object.'
def __init__(self, hass, name):
self._hass = hass self._name = name
'Input Event received.'
def received_gesture_event(self, event):
_LOGGER.debug('Received event: name=%s, gesture_id=%s,value=%s', event.name, event.gesture, event.value) self._hass.bus.fire(EVENT_NUIMO, {'type': event.name, 'value': event.value, 'name': self._name})
'Initialize thread object.'
def __init__(self, hass, mac, name):
super(NuimoThread, self).__init__() self._hass = hass self._mac = mac self._name = name self._hass_is_running = True self._nuimo = None hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop)
'Set up the connection or be idle.'
def run(self):
while self._hass_is_running: if ((not self._nuimo) or (not self._nuimo.is_connected())): self._attach() self._connect() else: time.sleep(1) if self._nuimo: self._nuimo.disconnect() self._nuimo = None
'Terminate Thread by unsetting flag.'
def stop(self, event):
_LOGGER.debug('Stopping thread for Nuimo %s', self._mac) self._hass_is_running = False
'Create a Nuimo object from MAC address or discovery.'
def _attach(self):
from nuimo import NuimoController, NuimoDiscoveryManager if self._nuimo: self._nuimo.disconnect() self._nuimo = None if self._mac: self._nuimo = NuimoController(self._mac) else: nuimo_manager = NuimoDiscoveryManager(bluetooth_adapter=DEFAULT_ADAPTER, delegate=DiscoveryLog...
'Build up connection and set event delegator and service.'
def _connect(self):
if (not self._nuimo): return try: self._nuimo.connect() _LOGGER.debug('Connected to %s', self._mac) except RuntimeError as error: _LOGGER.error('Could not connect to %s: %s', self._mac, error) time.sleep(1) return nuimo_event_delegate ...
'Discovery started.'
def discovery_started(self):
_LOGGER.info('Started discovery')
'Discovery finished.'
def discovery_finished(self):
_LOGGER.info('Finished discovery')
'Return that a controller was found.'
def controller_added(self, nuimo):
_LOGGER.info('Added Nuimo: %s', nuimo)
'Initialize the Cube Handle.'
def __init__(self, cube):
self.cube = cube self.mutex = Lock() self._updatets = time.time()
'Pull the latest data from the MAX! Cube.'
def update(self):
with self.mutex: if ((time.time() - self._updatets) >= 60): _LOGGER.debug('Updating') try: self.cube.update() except timeout: _LOGGER.error('Max!Cube connection failed') return False self._updatets = time.t...
'Initialize the feeder.'
def __init__(self, hass, host, port, prefix):
super(GraphiteFeeder, self).__init__(daemon=True) self._hass = hass self._host = host self._port = port self._prefix = prefix.rstrip('.') self._queue = queue.Queue() self._quit_object = object() self._we_started = False hass.bus.listen_once(EVENT_HOMEASSISTANT_START, self.start_liste...
'Start event-processing thread.'
def start_listen(self, event):
_LOGGER.debug('Event processing thread started') self._we_started = True self.start()
'Signal shutdown of processing event.'
def shutdown(self, event):
_LOGGER.debug('Event processing signaled exit') self._queue.put(self._quit_object)
'Queue an event for processing.'
def event_listener(self, event):
if (self.is_alive() or (not self._we_started)): _LOGGER.debug('Received event') self._queue.put(event) else: _LOGGER.error('Graphite feeder thread has died, not queuing event!')
'Send data to Graphite.'
def _send_to_graphite(self, data):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10) sock.connect((self._host, self._port)) sock.sendall(data.encode('ascii')) sock.send('\n'.encode('ascii')) sock.close()
'Report the attributes.'
def _report_attributes(self, entity_id, new_state):
now = time.time() things = dict(new_state.attributes) try: things['state'] = state.state_as_number(new_state) except ValueError: pass lines = [('%s.%s.%s %f %i' % (self._prefix, entity_id, key.replace(' ', '_'), value, now)) for (key, value) in things.items() if isinstance(v...
'Run the process to export the data.'
def run(self):
while True: event = self._queue.get() if (event == self._quit_object): _LOGGER.debug('Event processing thread stopped') self._queue.task_done() return elif ((event.event_type == EVENT_STATE_CHANGED) and event.data.get('new_state')): _L...
'Initialise the scanner.'
def __init__(self, config):
_LOGGER.info('Initialising BT Home Hub 5') self.host = config.get(CONF_HOST, '192.168.1.254') self.last_results = {} self.url = 'http://{}/nonAuth/home_status.xml'.format(self.host) data = _get_homehub_data(self.url) self.success_init = (data is not None)
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return (device for device in self.last_results)
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, device):
if (device not in self.last_results): self._update_info() if (not self.last_results): return None return self.last_results.get(device)
'Ensure the information from the BT Home Hub 5 is up to date. Return boolean if scanning successful.'
def _update_info(self):
if (not self.success_init): return False _LOGGER.info('Scanning') data = _get_homehub_data(self.url) if (not data): _LOGGER.warning('Error scanning devices') return False self.last_results = data return True
'Initialize the scanner.'
def __init__(self, host, username, password, port):
import pynetgear self.last_results = [] self._api = pynetgear.Netgear(password, host, username, port) _LOGGER.info('Logging in') results = self._api.get_attached_devices() self.success_init = (results is not None) if self.success_init: self.last_results = results else: ...
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return (device.mac for device in self.last_results)
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, mac):
try: return next((device.name for device in self.last_results if (device.mac == mac))) except StopIteration: return None
'Retrieve latest information from the Netgear router. Returns boolean if scanning successful.'
def _update_info(self):
if (not self.success_init): return _LOGGER.info('Scanning') results = self._api.get_attached_devices() if (results is None): _LOGGER.warning('Error scanning devices') self.last_results = (results or [])
'Initialize the scanner.'
def __init__(self, config):
self.host = config[CONF_HOST] self.last_results = {} data = self.get_swisscom_data() self.success_init = (data is not None)
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return [client['mac'] for client in self.last_results]
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, device):
if (not self.last_results): return None for client in self.last_results: if (client['mac'] == device): return client['host'] return None
'Ensure the information from the Swisscom router is up to date. Return boolean if scanning successful.'
def _update_info(self):
if (not self.success_init): return False _LOGGER.info('Loading data from Swisscom Internet Box') data = self.get_swisscom_data() if (not data): return False active_clients = [client for client in data.values() if client['status']] self.last_results = active_clients...
'Retrieve data from Swisscom and return parsed result.'
def get_swisscom_data(self):
url = 'http://{}/ws'.format(self.host) headers = {'Content-Type': 'application/x-sah-ws-4-call+json'} data = '\n {"service":"Devices", "method":"get",\n "parameters":{"expression":"lan and not self"}}' request = requests.post(url,...
'Initialize the scanner.'
def __init__(self, config):
self.last_results = [] self.success_init = self._update_info() _LOGGER.info('Scanner initialized')
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return [device.mac for device in self.last_results]
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, mac):
filter_named = [device.name for device in self.last_results if (device.mac == mac)] if filter_named: return filter_named[0] return None
'Check the Bbox for devices. Returns boolean if scanning successful.'
@Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self):
_LOGGER.info('Scanning...') import pybbox box = pybbox.Bbox() result = box.get_all_connected_devices() now = dt_util.now() last_results = [] for device in result: if (device['active'] != 1): continue last_results.append(Device(device['macaddress'], device['hostnam...
'Initialize the scanner.'
def __init__(self, config):
self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile('(?P<param>\\w*) = (?P<value>.*);') self.last_results = {} self.refresh_token() self.mac2name = None self.success_init = (self.token is not ...
'Get a new token.'
def refresh_token(self):
self.token = _get_token(self.host, self.username, self.password)
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return self.last_results
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, device):
if (self.mac2name is None): url = 'http://{}/cgi-bin/luci/rpc/uci'.format(self.host) result = _req_json_rpc(url, 'get_all', 'dhcp', params={'auth': self.token}) if result: hosts = [x for x in result.values() if ((x['.type'] == 'host') and ('mac' in x) and ('name' in x))] ...
'Ensure the information from the Luci router is up to date. Returns boolean if scanning successful.'
def _update_info(self):
if (not self.success_init): return False _LOGGER.info('Checking ARP') url = 'http://{}/cgi-bin/luci/rpc/sys'.format(self.host) try: result = _req_json_rpc(url, 'net.arptable', params={'auth': self.token}) except InvalidLuciTokenError: _LOGGER.info('Refreshing token') ...
'Initialize the scanner.'
def __init__(self, config):
self.last_results = {} self.host = config[CONF_HOST] self.port = config[CONF_PORT] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.connected = False self.success_init = False self.client = None self.wireless_exist = None self.success_init = self.c...
'Connect to Mikrotik method.'
def connect_to_device(self):
import librouteros try: self.client = librouteros.connect(self.host, self.username, self.password, port=int(self.port)) routerboard_info = self.client(cmd='/system/routerboard/getall') if routerboard_info: _LOGGER.info('Connected to Mikrotik %s with IP %s', ...
'Scan for new devices and return a list with found device MACs.'
def scan_devices(self):
self._update_info() return [device for device in self.last_results]
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, mac):
return self.last_results.get(mac)
'Retrieve latest information from the Mikrotik box.'
def _update_info(self):
if self.wireless_exist: devices_tracker = 'wireless' else: devices_tracker = 'ip' _LOGGER.info('Loading %s devices from Mikrotik (%s) ...', devices_tracker, self.host) device_names = self.client(cmd='/ip/dhcp-server/lease/getall') if self.wireless_exist: dev...
'Initialize the Host pinger.'
def __init__(self, ip_address, dev_id, hass, config):
self.hass = hass self.ip_address = ip_address self.dev_id = dev_id self._count = config[CONF_PING_COUNT] if (sys.platform == 'win32'): self._ping_cmd = ['ping', '-n 1', '-w', '1000', self.ip_address] else: self._ping_cmd = ['ping', '-n', '-q', '-c1', '-W1', self.ip_address]
'Send an ICMP echo request and return True if success.'
def ping(self):
pinger = subprocess.Popen(self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) try: pinger.communicate() return (pinger.returncode == 0) except subprocess.CalledProcessError: return False
'Update device state by sending one or more ping messages.'
def update(self, see):
failed = 0 while (failed < self._count): if self.ping(): see(dev_id=self.dev_id, source_type=SOURCE_TYPE_ROUTER) return True failed += 1 _LOGGER.debug('No response from %s failed=%d', self.ip_address, failed)
'Initialize the scanner.'
def __init__(self, config):
(host, http_id) = (config[CONF_HOST], config[CONF_HTTP_ID]) (username, password) = (config[CONF_USERNAME], config[CONF_PASSWORD]) self.req = requests.Request('POST', 'http://{}/update.cgi'.format(host), data={'_http_id': http_id, 'exec': 'devlist'}, auth=requests.auth.HTTPBasicAuth(username, password)).prep...
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_tomato_info() return [item[1] for item in self.last_results['wldev']]
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, device):
filter_named = [item[0] for item in self.last_results['dhcpd_lease'] if (item[2] == device)] if ((not filter_named) or (not filter_named[0])): return None return filter_named[0]
'Ensure the information from the Tomato router is up to date. Return boolean if scanning successful.'
def _update_tomato_info(self):
self.logger.info('Scanning') try: response = requests.Session().send(self.req, timeout=3) if (response.status_code == 200): for (param, value) in self.parse_api_pattern.findall(response.text): if ((param == 'wldev') or (param == 'dhcpd_lease')): se...
'Initialise the scanner.'
def __init__(self, config):
_LOGGER.info('Initialising Sky Hub') self.host = config.get(CONF_HOST, '192.168.1.254') self.last_results = {} self.url = 'http://{}/'.format(self.host) data = _get_skyhub_data(self.url) self.success_init = (data is not None)
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return (device for device in self.last_results)
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, device):
if (device not in self.last_results): self._update_info() if (not self.last_results): return None return self.last_results.get(device)
'Ensure the information from the Sky Hub is up to date. Return boolean if scanning successful.'
def _update_info(self):
if (not self.success_init): return False _LOGGER.info('Scanning') data = _get_skyhub_data(self.url) if (not data): _LOGGER.warning('Error scanning devices') return False self.last_results = data return True
'Initialize the scanner.'
def __init__(self, config):
self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.verify_ssl = config[CONF_VERIFY_SSL] self.last_results = [] response = self._make_request() if (not (response.status_code == 200)): raise ConnectionError('Cannot connect ...
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return self.last_results
'Return the name (if known) of the device. Linksys does not provide an API to get a name for a device, so we just return None'
def get_device_name(self, mac):
return None
'Check for connected devices.'
def _update_info(self):
from bs4 import BeautifulSoup as BS _LOGGER.info('Checking Linksys AP') self.last_results = [] for interface in range(INTERFACES): request = self._make_request(interface) self.last_results.extend([x.find_all('td')[1].text for x in BS(request.content, 'html.parser').find_all(class_=...
'Initialize the scanner.'
def __init__(self, controller):
self._controller = controller self._update()
'Get the clients from the device.'
def _update(self):
from pyunifi.controller import APIError try: clients = self._controller.get_clients() except APIError as ex: _LOGGER.error('Failed to scan clients: %s', ex) clients = [] self._clients = {client['mac']: client for client in clients}
'Scan for devices.'
def scan_devices(self):
self._update() return self._clients.keys()
'Return the name (if known) of the device. If a name has been set in Unifi, then return that, else return the hostname if it has been detected.'
def get_device_name(self, mac):
client = self._clients.get(mac, {}) name = (client.get('name') or client.get('hostname')) _LOGGER.debug('Device %s name %s', mac, name) return name
'Initialize the scanner.'
def __init__(self, config):
self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.last_results = [] data = self.get_actiontec_data() self.success_init = (data is not None) _LOGGER.info('canner initialized')
'Scan for new devices and return a list with found device IDs.'
def scan_devices(self):
self._update_info() return [client.mac for client in self.last_results]
'Return the name of the given device or None if we don\'t know.'
def get_device_name(self, device):
if (not self.last_results): return None for client in self.last_results: if (client.mac == device): return client.ip return None
'Ensure the information from the router is up to date. Return boolean if scanning successful.'
def _update_info(self):
_LOGGER.info('Scanning') if (not self.success_init): return False now = dt_util.now() actiontec_data = self.get_actiontec_data() if (not actiontec_data): return False self.last_results = [Device(data['mac'], name, now) for (name, data) in actiontec_data.items() if (data['timevali...