mirror of
https://github.com/elisspace/core.git
synced 2026-10-05 16:56:19 +00:00
fixed merge conflict
This commit is contained in:
@@ -114,6 +114,8 @@ def setup(hass, config):
|
||||
os.remove(csv_path)
|
||||
|
||||
conf = config.get(DOMAIN, {})
|
||||
if isinstance(conf, list):
|
||||
conf = conf[0]
|
||||
consider_home = timedelta(
|
||||
seconds=util.convert(conf.get(CONF_CONSIDER_HOME), int,
|
||||
DEFAULT_CONSIDER_HOME))
|
||||
|
||||
@@ -46,6 +46,7 @@ MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DDWRT_DATA_REGEX = re.compile(r'\{(\w+)::([^\}]*)\}')
|
||||
_MAC_REGEX = re.compile(r'(([0-9A-Fa-f]{1,2}\:){5}[0-9A-Fa-f]{1,2})')
|
||||
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
@@ -77,7 +78,7 @@ class DdWrtDeviceScanner(object):
|
||||
|
||||
self.last_results = {}
|
||||
|
||||
self.mac2name = None
|
||||
self.mac2name = {}
|
||||
|
||||
# Test the router is accessible
|
||||
url = 'http://{}/Status_Wireless.live.asp'.format(self.host)
|
||||
@@ -98,30 +99,33 @@ class DdWrtDeviceScanner(object):
|
||||
|
||||
with self.lock:
|
||||
# if not initialised and not already scanned and not found
|
||||
if self.mac2name is None or device not in self.mac2name:
|
||||
if device not in self.mac2name:
|
||||
url = 'http://{}/Status_Lan.live.asp'.format(self.host)
|
||||
data = self.get_ddwrt_data(url)
|
||||
|
||||
if not data:
|
||||
return
|
||||
return None
|
||||
|
||||
dhcp_leases = data.get('dhcp_leases', None)
|
||||
if dhcp_leases:
|
||||
# remove leading and trailing single quotes
|
||||
cleaned_str = dhcp_leases.strip().strip('"')
|
||||
elements = cleaned_str.split('","')
|
||||
num_clients = int(len(elements)/5)
|
||||
self.mac2name = {}
|
||||
for idx in range(0, num_clients):
|
||||
# this is stupid but the data is a single array
|
||||
# every 5 elements represents one hosts, the MAC
|
||||
# is the third element and the name is the first
|
||||
mac_index = (idx * 5) + 2
|
||||
if mac_index < len(elements):
|
||||
mac = elements[mac_index]
|
||||
self.mac2name[mac] = elements[idx * 5]
|
||||
|
||||
return self.mac2name.get(device, None)
|
||||
if not dhcp_leases:
|
||||
return None
|
||||
|
||||
# remove leading and trailing single quotes
|
||||
cleaned_str = dhcp_leases.strip().strip('"')
|
||||
elements = cleaned_str.split('","')
|
||||
num_clients = int(len(elements)/5)
|
||||
self.mac2name = {}
|
||||
for idx in range(0, num_clients):
|
||||
# this is stupid but the data is a single array
|
||||
# every 5 elements represents one hosts, the MAC
|
||||
# is the third element and the name is the first
|
||||
mac_index = (idx * 5) + 2
|
||||
if mac_index < len(elements):
|
||||
mac = elements[mac_index]
|
||||
self.mac2name[mac] = elements[idx * 5]
|
||||
|
||||
return self.mac2name.get(device)
|
||||
|
||||
@Throttle(MIN_TIME_BETWEEN_SCANS)
|
||||
def _update_info(self):
|
||||
@@ -141,29 +145,25 @@ class DdWrtDeviceScanner(object):
|
||||
if not data:
|
||||
return False
|
||||
|
||||
if data:
|
||||
self.last_results = []
|
||||
active_clients = data.get('active_wireless', None)
|
||||
if active_clients:
|
||||
# This is really lame, instead of using JSON the DD-WRT UI
|
||||
# uses its own data format for some reason and then
|
||||
# regex's out values so I guess I have to do the same,
|
||||
# LAME!!!
|
||||
self.last_results = []
|
||||
|
||||
# remove leading and trailing single quotes
|
||||
clean_str = active_clients.strip().strip("'")
|
||||
elements = clean_str.split("','")
|
||||
active_clients = data.get('active_wireless', None)
|
||||
if not active_clients:
|
||||
return False
|
||||
|
||||
num_clients = int(len(elements)/9)
|
||||
for idx in range(0, num_clients):
|
||||
# get every 9th element which is the MAC address
|
||||
index = idx * 9
|
||||
if index < len(elements):
|
||||
self.last_results.append(elements[index])
|
||||
# This is really lame, instead of using JSON the DD-WRT UI
|
||||
# uses its own data format for some reason and then
|
||||
# regex's out values so I guess I have to do the same,
|
||||
# LAME!!!
|
||||
|
||||
return True
|
||||
# remove leading and trailing single quotes
|
||||
clean_str = active_clients.strip().strip("'")
|
||||
elements = clean_str.split("','")
|
||||
|
||||
return False
|
||||
self.last_results.extend(item for item in elements
|
||||
if _MAC_REGEX.match(item))
|
||||
|
||||
return True
|
||||
|
||||
def get_ddwrt_data(self, url):
|
||||
""" Retrieve data from DD-WRT and return parsed result. """
|
||||
|
||||
@@ -117,15 +117,18 @@ class NmapDeviceScanner(object):
|
||||
scanner = PortScanner()
|
||||
|
||||
options = "-F --host-timeout 5"
|
||||
exclude_targets = set()
|
||||
|
||||
if self.home_interval:
|
||||
now = dt_util.now()
|
||||
for host in self.last_results:
|
||||
if host.last_update + self.home_interval > now:
|
||||
exclude_targets.add(host)
|
||||
if len(exclude_targets) > 0:
|
||||
target_list = [t.ip for t in exclude_targets]
|
||||
options += " --exclude {}".format(",".join(target_list))
|
||||
boundary = dt_util.now() - self.home_interval
|
||||
last_results = [device for device in self.last_results
|
||||
if device.last_update > boundary]
|
||||
if last_results:
|
||||
# Pylint is confused here.
|
||||
# pylint: disable=no-member
|
||||
options += " --exclude {}".format(",".join(device.ip for device
|
||||
in last_results))
|
||||
else:
|
||||
last_results = []
|
||||
|
||||
try:
|
||||
result = scanner.scan(hosts=self.hosts, arguments=options)
|
||||
@@ -133,18 +136,17 @@ class NmapDeviceScanner(object):
|
||||
return False
|
||||
|
||||
now = dt_util.now()
|
||||
self.last_results = []
|
||||
for ipv4, info in result['scan'].items():
|
||||
if info['status']['state'] != 'up':
|
||||
continue
|
||||
name = info['hostnames'][0] if info['hostnames'] else ipv4
|
||||
name = info['hostnames'][0]['name'] if info['hostnames'] else ipv4
|
||||
# Mac address only returned if nmap ran as root
|
||||
mac = info['addresses'].get('mac') or _arp(ipv4)
|
||||
if mac is None:
|
||||
continue
|
||||
device = Device(mac.upper(), name, ipv4, now)
|
||||
self.last_results.append(device)
|
||||
self.last_results.extend(exclude_targets)
|
||||
last_results.append(Device(mac.upper(), name, ipv4, now))
|
||||
|
||||
self.last_results = last_results
|
||||
|
||||
_LOGGER.info("nmap scan successful")
|
||||
return True
|
||||
|
||||
@@ -1,34 +1,11 @@
|
||||
"""
|
||||
homeassistant.components.media_player.plex
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Provides an interface to the Plex API.
|
||||
|
||||
Provides an interface to the Plex API
|
||||
|
||||
Configuration:
|
||||
|
||||
To use Plex add something like this to your configuration:
|
||||
|
||||
media_player:
|
||||
platform: plex
|
||||
name: plex_server
|
||||
user: plex
|
||||
password: my_secure_password
|
||||
|
||||
Variables:
|
||||
|
||||
name
|
||||
*Required
|
||||
The name of the backend device (Under Plex Media Server > settings > server).
|
||||
|
||||
user
|
||||
*Required
|
||||
The Plex username
|
||||
|
||||
password
|
||||
*Required
|
||||
The Plex password
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/media_player.plex.html
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
@@ -49,10 +26,8 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
|
||||
|
||||
# pylint: disable=abstract-method
|
||||
# pylint: disable=unused-argument
|
||||
|
||||
|
||||
# pylint: disable=abstract-method, unused-argument
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
""" Sets up the plex platform. """
|
||||
from plexapi.myplex import MyPlexUser
|
||||
@@ -68,7 +43,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
|
||||
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
|
||||
def update_devices():
|
||||
""" Updates the devices objects """
|
||||
""" Updates the devices objects. """
|
||||
try:
|
||||
devices = plexuser.devices()
|
||||
except BadRequest:
|
||||
@@ -94,7 +69,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
|
||||
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
|
||||
def update_sessions():
|
||||
""" Updates the sessions objects """
|
||||
""" Updates the sessions objects. """
|
||||
try:
|
||||
sessions = plexserver.sessions()
|
||||
except BadRequest:
|
||||
@@ -113,7 +88,6 @@ class PlexClient(MediaPlayerDevice):
|
||||
""" Represents a Plex device. """
|
||||
|
||||
# pylint: disable=too-many-public-methods
|
||||
|
||||
def __init__(self, device, plex_sessions, update_devices, update_sessions):
|
||||
self.plex_sessions = plex_sessions
|
||||
self.update_devices = update_devices
|
||||
@@ -121,12 +95,12 @@ class PlexClient(MediaPlayerDevice):
|
||||
self.set_device(device)
|
||||
|
||||
def set_device(self, device):
|
||||
""" Sets the device property """
|
||||
""" Sets the device property. """
|
||||
self.device = device
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
""" Returns the session, if any """
|
||||
""" Returns the session, if any. """
|
||||
if self.device.clientIdentifier not in self.plex_sessions:
|
||||
return None
|
||||
|
||||
@@ -196,21 +170,21 @@ class PlexClient(MediaPlayerDevice):
|
||||
|
||||
@property
|
||||
def media_season(self):
|
||||
""" Season of curent playing media. (TV Show only) """
|
||||
""" Season of curent playing media (TV Show only). """
|
||||
from plexapi.video import Show
|
||||
if isinstance(self.session, Show):
|
||||
return self.session.seasons()[0].index
|
||||
|
||||
@property
|
||||
def media_series_title(self):
|
||||
""" Series title of current playing media. (TV Show only)"""
|
||||
""" Series title of current playing media (TV Show only). """
|
||||
from plexapi.video import Show
|
||||
if isinstance(self.session, Show):
|
||||
return self.session.grandparentTitle
|
||||
|
||||
@property
|
||||
def media_episode(self):
|
||||
""" Episode of current playing media. (TV Show only) """
|
||||
""" Episode of current playing media (TV Show only). """
|
||||
from plexapi.video import Show
|
||||
if isinstance(self.session, Show):
|
||||
return self.session.index
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
homeassistant.components.notify.telegram
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Telegram platform for notify component.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/notify.telegram.html
|
||||
"""
|
||||
import logging
|
||||
import urllib
|
||||
|
||||
from homeassistant.helpers import validate_config
|
||||
from homeassistant.components.notify import (
|
||||
DOMAIN, ATTR_TITLE, BaseNotificationService)
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
REQUIREMENTS = ['python-telegram-bot==2.8.7']
|
||||
|
||||
|
||||
def get_service(hass, config):
|
||||
""" Get the Telegram notification service. """
|
||||
|
||||
if not validate_config(config,
|
||||
{DOMAIN: [CONF_API_KEY, 'chat_id']},
|
||||
_LOGGER):
|
||||
return None
|
||||
|
||||
try:
|
||||
import telegram
|
||||
except ImportError:
|
||||
_LOGGER.exception(
|
||||
"Unable to import python-telegram-bot. "
|
||||
"Did you maybe not install the 'python-telegram-bot' package?")
|
||||
return None
|
||||
|
||||
try:
|
||||
bot = telegram.Bot(token=config[DOMAIN][CONF_API_KEY])
|
||||
username = bot.getMe()['username']
|
||||
_LOGGER.info("Telegram bot is' %s'", username)
|
||||
except urllib.error.HTTPError:
|
||||
_LOGGER.error("Please check your access token.")
|
||||
return None
|
||||
|
||||
return TelegramNotificationService(
|
||||
config[DOMAIN][CONF_API_KEY],
|
||||
config[DOMAIN]['chat_id'])
|
||||
|
||||
|
||||
# pylint: disable=too-few-public-methods
|
||||
class TelegramNotificationService(BaseNotificationService):
|
||||
""" Implements notification service for Telegram. """
|
||||
|
||||
def __init__(self, api_key, chat_id):
|
||||
import telegram
|
||||
self._api_key = api_key
|
||||
self._chat_id = chat_id
|
||||
self.bot = telegram.Bot(token=self._api_key)
|
||||
|
||||
def send_message(self, message="", **kwargs):
|
||||
""" Send a message to a user. """
|
||||
|
||||
title = kwargs.get(ATTR_TITLE)
|
||||
|
||||
self.bot.sendMessage(chat_id=self._chat_id,
|
||||
text=title + " " + message)
|
||||
@@ -1,20 +1,10 @@
|
||||
"""
|
||||
homeassistant.components.rfxtrx
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Connects Home Assistant to a RFXtrx device.
|
||||
|
||||
Configuration:
|
||||
|
||||
To use Rfxtrx device you will need to add the following to your
|
||||
configuration.yaml file.
|
||||
|
||||
rfxtrx:
|
||||
device: /dev/serial/by-id/usb-RFXCOM_RFXtrx433_A1YVC1P0-if00-port0
|
||||
|
||||
*Optional*
|
||||
|
||||
debug: True
|
||||
Provides support for RFXtrx components.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/rfxtrx.html
|
||||
"""
|
||||
import logging
|
||||
from homeassistant.util import slugify
|
||||
|
||||
@@ -3,51 +3,11 @@ homeassistant.components.sensor.arest
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
The arest sensor will consume an exposed aREST API of a device.
|
||||
|
||||
Configuration:
|
||||
|
||||
To use the arest sensor you will need to add something like the following
|
||||
to your configuration.yaml file.
|
||||
|
||||
sensor:
|
||||
platform: arest
|
||||
resource: http://IP_ADDRESS
|
||||
monitored_variables:
|
||||
- name: temperature
|
||||
unit: '°C'
|
||||
- name: humidity
|
||||
unit: '%'
|
||||
|
||||
Variables:
|
||||
|
||||
resource:
|
||||
*Required
|
||||
IP address of the device that is exposing an aREST API.
|
||||
|
||||
These are the variables for the monitored_variables array:
|
||||
|
||||
name
|
||||
*Required
|
||||
The name of the variable you wish to monitor.
|
||||
|
||||
unit
|
||||
*Optional
|
||||
Defines the units of measurement of the sensor, if any.
|
||||
|
||||
Details for the API: http://arest.io
|
||||
|
||||
Format of a default JSON response by aREST:
|
||||
{
|
||||
"variables":{
|
||||
"temperature":21,
|
||||
"humidity":89
|
||||
},
|
||||
"id":"device008",
|
||||
"name":"Bedroom",
|
||||
"connected":true
|
||||
}
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.arest.html
|
||||
"""
|
||||
import logging
|
||||
from requests import get, exceptions
|
||||
import requests
|
||||
from datetime import timedelta
|
||||
|
||||
from homeassistant.util import Throttle
|
||||
@@ -58,36 +18,42 @@ _LOGGER = logging.getLogger(__name__)
|
||||
# Return cached results if last scan was less then this time ago
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
|
||||
|
||||
CONF_RESOURCE = 'resource'
|
||||
CONF_MONITORED_VARIABLES = 'monitored_variables'
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
""" Get the aREST sensor. """
|
||||
|
||||
resource = config.get('resource', None)
|
||||
resource = config.get(CONF_RESOURCE)
|
||||
var_conf = config.get(CONF_MONITORED_VARIABLES)
|
||||
|
||||
if None in (resource, var_conf):
|
||||
_LOGGER.error('Not all required config keys present: %s',
|
||||
', '.join((CONF_RESOURCE, CONF_MONITORED_VARIABLES)))
|
||||
return False
|
||||
|
||||
try:
|
||||
response = get(resource, timeout=10)
|
||||
except exceptions.MissingSchema:
|
||||
response = requests.get(resource, timeout=10).json()
|
||||
except requests.exceptions.MissingSchema:
|
||||
_LOGGER.error("Missing resource or schema in configuration. "
|
||||
"Add http:// to your URL.")
|
||||
return False
|
||||
except exceptions.ConnectionError:
|
||||
except requests.exceptions.ConnectionError:
|
||||
_LOGGER.error("No route to device. "
|
||||
"Please check the IP address in the configuration file.")
|
||||
return False
|
||||
|
||||
rest = ArestData(resource)
|
||||
arest = ArestData(resource)
|
||||
|
||||
dev = []
|
||||
for variable in config['monitored_variables']:
|
||||
if 'unit' not in variable:
|
||||
variable['unit'] = ' '
|
||||
if variable['name'] not in response.json()['variables']:
|
||||
if variable['name'] not in response['variables']:
|
||||
_LOGGER.error('Variable: "%s" does not exist', variable['name'])
|
||||
else:
|
||||
dev.append(ArestSensor(rest,
|
||||
response.json()['name'],
|
||||
variable['name'],
|
||||
variable['unit']))
|
||||
continue
|
||||
|
||||
dev.append(ArestSensor(arest, response['name'], variable['name'],
|
||||
variable.get('unit')))
|
||||
|
||||
add_devices(dev)
|
||||
|
||||
@@ -95,8 +61,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
class ArestSensor(Entity):
|
||||
""" Implements an aREST sensor. """
|
||||
|
||||
def __init__(self, rest, location, variable, unit_of_measurement):
|
||||
self.rest = rest
|
||||
def __init__(self, arest, location, variable, unit_of_measurement):
|
||||
self.arest = arest
|
||||
self._name = '{} {}'.format(location.title(), variable.title())
|
||||
self._variable = variable
|
||||
self._state = 'n/a'
|
||||
@@ -116,17 +82,16 @@ class ArestSensor(Entity):
|
||||
@property
|
||||
def state(self):
|
||||
""" Returns the state of the device. """
|
||||
return self._state
|
||||
|
||||
def update(self):
|
||||
""" Gets the latest data from aREST API and updates the state. """
|
||||
self.rest.update()
|
||||
values = self.rest.data
|
||||
values = self.arest.data
|
||||
|
||||
if 'error' in values:
|
||||
self._state = values['error']
|
||||
return values['error']
|
||||
else:
|
||||
self._state = values[self._variable]
|
||||
return values.get(self._variable, 'n/a')
|
||||
|
||||
def update(self):
|
||||
""" Gets the latest data from aREST API. """
|
||||
self.arest.update()
|
||||
|
||||
|
||||
# pylint: disable=too-few-public-methods
|
||||
@@ -135,16 +100,14 @@ class ArestData(object):
|
||||
|
||||
def __init__(self, resource):
|
||||
self.resource = resource
|
||||
self.data = dict()
|
||||
self.data = {}
|
||||
|
||||
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
||||
def update(self):
|
||||
""" Gets the latest data from aREST device. """
|
||||
try:
|
||||
response = get(self.resource, timeout=10)
|
||||
if 'error' in self.data:
|
||||
del self.data['error']
|
||||
response = requests.get(self.resource, timeout=10)
|
||||
self.data = response.json()['variables']
|
||||
except exceptions.ConnectionError:
|
||||
except requests.exceptions.ConnectionError:
|
||||
_LOGGER.error("No route to device. Is device offline?")
|
||||
self.data['error'] = 'n/a'
|
||||
self.data = {'error': 'error fetching'}
|
||||
|
||||
@@ -3,38 +3,9 @@ homeassistant.components.switch.arest
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
The arest switch can control the digital pins of a device running with the
|
||||
aREST RESTful framework for Arduino, the ESP8266, and the Raspberry Pi.
|
||||
Only tested with Arduino boards so far.
|
||||
|
||||
Configuration:
|
||||
|
||||
To use the arest switch you will need to add something like the following
|
||||
to your configuration.yaml file.
|
||||
|
||||
sensor:
|
||||
platform: arest
|
||||
resource: http://IP_ADDRESS
|
||||
pins:
|
||||
11:
|
||||
name: Fan Office
|
||||
12:
|
||||
name: Light Desk
|
||||
|
||||
Variables:
|
||||
|
||||
resource:
|
||||
*Required
|
||||
IP address of the device that is exposing an aREST API.
|
||||
|
||||
pins:
|
||||
The number of the digital pin to switch.
|
||||
|
||||
These are the variables for the pins array:
|
||||
|
||||
name
|
||||
*Required
|
||||
The name for the pin that will be used in the frontend.
|
||||
|
||||
Details for the API: http://arest.io
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/switch.arest.html
|
||||
"""
|
||||
import logging
|
||||
from requests import get, exceptions
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# coding: utf-8
|
||||
""" Constants used by Home Assistant components. """
|
||||
|
||||
__version__ = "0.7.5dev0"
|
||||
__version__ = "0.7.6.dev0"
|
||||
|
||||
# Can be used to specify a catch all when registering state or event listeners.
|
||||
MATCH_ALL = '*'
|
||||
|
||||
@@ -59,14 +59,14 @@ def reproduce_state(hass, states, blocking=False):
|
||||
state.entity_id)
|
||||
continue
|
||||
|
||||
if state.domain == 'media_player' and state.state == STATE_PAUSED:
|
||||
service = SERVICE_MEDIA_PAUSE
|
||||
elif state.domain == 'media_player' and state.state == STATE_PLAYING:
|
||||
service = SERVICE_MEDIA_PLAY
|
||||
elif state.domain == 'media_player' and state.attributes and \
|
||||
if state.domain == 'media_player' and state.attributes and \
|
||||
'media_type' in state.attributes and \
|
||||
'media_id' in state.attributes:
|
||||
service = SERVICE_PLAY_MEDIA
|
||||
elif state.domain == 'media_player' and state.state == STATE_PAUSED:
|
||||
service = SERVICE_MEDIA_PAUSE
|
||||
elif state.domain == 'media_player' and state.state == STATE_PLAYING:
|
||||
service = SERVICE_MEDIA_PLAY
|
||||
elif state.state == STATE_ON:
|
||||
service = SERVICE_TURN_ON
|
||||
elif state.state == STATE_OFF:
|
||||
|
||||
@@ -233,35 +233,42 @@ class Throttle(object):
|
||||
self.limit_no_throttle = limit_no_throttle
|
||||
|
||||
def __call__(self, method):
|
||||
lock = threading.Lock()
|
||||
|
||||
if self.limit_no_throttle is not None:
|
||||
method = Throttle(self.limit_no_throttle)(method)
|
||||
|
||||
# We want to be able to differentiate between function and method calls
|
||||
# All methods have the classname in their qualname seperated by a '.'
|
||||
# Functions have a '.' in their qualname if defined inline, but will
|
||||
# be prefixed by '.<locals>.' so we strip that out.
|
||||
is_func = '.' not in method.__qualname__.split('.<locals>.')[-1]
|
||||
|
||||
@wraps(method)
|
||||
def wrapper(*args, **kwargs):
|
||||
"""
|
||||
Wrapper that allows wrapped to be called only once per min_time.
|
||||
If we cannot acquire the lock, it is running so return None.
|
||||
"""
|
||||
if not lock.acquire(False):
|
||||
# pylint: disable=protected-access
|
||||
host = wrapper if is_func else args[0]
|
||||
if not hasattr(host, '_throttle_lock'):
|
||||
host._throttle_lock = threading.Lock()
|
||||
|
||||
if not host._throttle_lock.acquire(False):
|
||||
return None
|
||||
|
||||
last_call = getattr(host, '_throttle_last_call', None)
|
||||
# Check if method is never called or no_throttle is given
|
||||
force = not last_call or kwargs.pop('no_throttle', False)
|
||||
|
||||
try:
|
||||
last_call = wrapper.last_call
|
||||
|
||||
# Check if method is never called or no_throttle is given
|
||||
force = not last_call or kwargs.pop('no_throttle', False)
|
||||
|
||||
if force or utcnow() - last_call > self.min_time:
|
||||
result = method(*args, **kwargs)
|
||||
wrapper.last_call = utcnow()
|
||||
host._throttle_last_call = utcnow()
|
||||
return result
|
||||
else:
|
||||
return None
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
wrapper.last_call = None
|
||||
host._throttle_lock.release()
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
Reference in New Issue
Block a user