Example #1
0
 def __init__(self, device, config, device_info, hass, main_mi_type):
     GenericMiotDevice.__init__(self, device, config, device_info, hass,
                                main_mi_type)
     self._current_position = None
     self._target_position = None
     self._action = None
     self._throttle1 = Throttle(timedelta(seconds=1))(self._async_update)
     self._throttle10 = Throttle(timedelta(seconds=10))(self._async_update)
     self.async_update = self._throttle10
Example #2
0
 def __init__(self, device, config, device_info, hass):
     GenericMiotDevice.__init__(self, device, config, device_info, hass)
     self._current_position = None
     self._target_position = None
     self._action = None
     # self._hass = hass
     # self._cloud = config.get(CONF_CLOUD)
     self._throttle1 = Throttle(timedelta(seconds=1))(self._async_update)
     self._throttle10 = Throttle(timedelta(seconds=10))(self._async_update)
     self.async_update = self._throttle10
    def __init__(self, name, interval, exceptions=None, inc_counter=1):
        self.__name = name
        self.__update_timestamp = datetime.today()
        self.__service_counter = 0
        self.__inc_counter = inc_counter

        self.__interval = interval
        self.__exceptions = exceptions

        self.__throttle_user_update = Throttle(interval)(self._user_update)
        self.__throttle_update = Throttle(timedelta(seconds=300))(
            self.__update_controller)
Example #4
0
 def __init__(self, session, interval):
     """Set up the headline sensor."""
     self._session = session
     self._state = None
     self._data = {}
     # TODO: decorate with throttle instead
     self.update = Throttle(interval)(self._update)
Example #5
0
    def __init__(self,
                 sensor_class: str,
                 measurement_unit: str,
                 device_method_or_property: str,
                 device: BaseDevice,
                 channel: int = 0):
        # Make sure the given device supports exposes the device_method_or_property passed as arg
        if not hasattr(device, device_method_or_property):
            _LOGGER.error(
                f"The device {device.uuid} ({device.name}) does not expose property {device_method_or_property}"
            )
            raise ValueError(
                f"The device {device} does not expose property {device_method_or_property}"
            )

        self._device = device
        self._channel_id = channel
        self._sensor_class = sensor_class
        self._device_method_or_property = device_method_or_property
        self._measurement_unit = measurement_unit

        # Each Meross Device might expose m_sensor_async_updateore than 1 sensor. In this case, we cannot rely only on the
        # uuid value to uniquely identify a sensor wrapper.
        self._id = calculate_sensor_id(uuid=device.internal_id,
                                       type=sensor_class,
                                       measurement_unit=measurement_unit,
                                       channel=channel)
        self._entity_name = "{} ({}) - {} ({}, {})".format(
            device.name, device.type, f"{sensor_class} sensor",
            measurement_unit, channel)

        # by default, set the scan_interval to the default value
        self.async_update = Throttle(SCAN_INTERVAL)(self._sensor_async_update)
Example #6
0
 def __init__(self, hass, istat, scan_interval, warnings):
     self._hass = hass
     self._istat = istat
     self._warnings = warnings
     self.dpc_output = None
     self.newlink = None
     self.async_update = Throttle(scan_interval)(self.async_update)
Example #7
0
 def __init__(self, miner_address, local_currency, update_frequency,
              id_name, name_override):
     self.data = None
     self.miner_address = miner_address
     self.local_currency = local_currency
     self.update = Throttle(update_frequency)(self._update)
     if name_override:
         self._name = SENSOR_PREFIX + name_override
     else:
         self._name = SENSOR_PREFIX + (id_name + " " if len(id_name) > 0
                                       else "") + miner_address
     self._icon = "mdi:ethereum"
     self._state = None
     self._active_workers = None
     self._current_hashrate = None
     self._invalid_shares = None
     self._last_update = None
     self._reported_hashrate = None
     self._stale_shares = None
     self._unpaid = None
     self._valid_shares = None
     self._unit_of_measurement = "\u200b"
     self._start_block = None
     self._end_block = None
     self._amount = None
     self._txhash = None
     self._paid_on = None
     self._average_hashrate_24h = None
     self._single_coin_in_local_currency = None
     self._unpaid_in_local_currency = None
     self._coins_per_minute = None
     self._current_hashrate_mh_sec = None
Example #8
0
 def __init__(self, device, scan_interval, thermostat_id, zone):
     """Initialize the thermostat."""
     self._device = device
     self._thermostat_id = thermostat_id
     self._zone = zone
     self._scan_interval = scan_interval
     self.update = Throttle(scan_interval)(self._update)
Example #9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Aria2c sensors."""

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    token = config.get(CONF_TOKEN)
   

    try:
        aria2c_api = Aria2cHomeassistant(
            host, port=port, token=token)
        aria2c_api.getVer()
    except ConnectionError as error:
        _LOGGER.error(
            "Connection to Aria2c API failed on %s:%s with message %s",
            host, port, error.original
        )
        return False

    # pylint: disable=global-statement
    global _THROTTLED_REFRESH
    _THROTTLED_REFRESH = Throttle(timedelta(seconds=1))(
        aria2c_api.getVer)

    dev = []
    for variable in config[CONF_MONITORED_VARIABLES]:
        dev.append(Aria2cSensor(variable, aria2c_api, name))

    add_devices(dev)
Example #10
0
    def __init__(self, api_key, latitude, longitude, units, realtime_fields,
                 forecast_fields, forecast_mode, forecast_observations,
                 interval):
        """Initialize the data object."""
        self._api_key = api_key
        self.latitude = latitude
        self.longitude = longitude
        self.units = units
        self.realtime_fields = realtime_fields
        self.forecast_fields = forecast_fields
        self.forecast_mode = forecast_mode
        self.forecast_observations = forecast_observations

        self.realtime_data = None
        self.forecast_data = None
        self.unit_system = None
        self.data_currently = None
        self.data_minutely = None
        self.data_hourly = None
        self.data_daily = None
        self.data_alerts = None

        self._headers = {
            'Content-Type': 'application/json',
            # 'Content-Type': 'application/json; charset=utf-8',
            'apikey': api_key,
            # 'X-Real-Ip': ip
        }

        self._params = 'lat=' + str(latitude) + '&lon=' + str(
            longitude) + '&unit_system=' + units

        # Apply throttling to methods using configured interval
        self.update = Throttle(interval)(self._update)
Example #11
0
    def __init__(self, token, scan_interval):
        """Initialise of the TeslaFi device."""

        _LOGGER.debug("Initialising TeslaFi API")

        self._baseurl = 'https://www.teslafi.com'
        self._api_actual = '/feed.php?token=' + token
        self._api_last = '/feed.php?command=lastGood&token=' + token
        self._api_command = '&command='

        self._scan_interval = scan_interval

        self._id = None
        self._vehicle_id = None
        self._display_name = None
        self._vin = None

        self._was_online = True
        self._update()
        self.update = Throttle(self._scan_interval)(self._update)

        if self.is_online():
            dataId = self._data
        else:
            dataId = self._last_data

        self._id = dataId['id']
        self._vehicle_id = dataId['vehicle_id']
        self._display_name = dataId['display_name'].replace(" ", "").lower()
        self._vin = dataId['vin']

        _LOGGER.debug("TeslaFi API Initialized")
Example #12
0
 def __init__(self, device, variable, variable_info, api, interval):
     """Initialize the Real Time Sensor."""
     super().__init__(device, variable, variable_info)
     self.site_id = self._device['id']
     self.api = api
     self.result = None
     self.update = Throttle(interval)(self.update)
Example #13
0
 def __init__(self, session, name, interval):
     """Initialize the sensor."""
     self._session = session
     self._name = name
     self._attributes = None
     self._state = None
     self.update = Throttle(interval)(self._update)
Example #14
0
    def __init__(self, hass, config):
        """Initialize the data object."""
        self._hass = hass
        self._entity_id = config.get(CONF_ENTITY_ID)
        self._data = None

        self.update = Throttle(timedelta(seconds=5))(self.update)
Example #15
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Transmission sensors."""
    import transmissionrpc
    from transmissionrpc.error import TransmissionError

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    port = config.get(CONF_PORT)

    transmission_api = transmissionrpc.Client(host,
                                              port=port,
                                              user=username,
                                              password=password)
    try:
        transmission_api.session_stats()
    except TransmissionError:
        _LOGGER.exception("Connection to Transmission API failed")
        return False

    # pylint: disable=global-statement
    global _THROTTLED_REFRESH
    _THROTTLED_REFRESH = Throttle(timedelta(seconds=1))(
        transmission_api.session_stats)

    dev = []
    for variable in config[CONF_MONITORED_VARIABLES]:
        dev.append(TransmissionSensor(variable, transmission_api, name))

    add_devices(dev)
Example #16
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the SABnzbd sensors."""
    from pysabnzbd import SabnzbdApi, SabnzbdApiException

    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    name = config.get(CONF_NAME)
    api_key = config.get(CONF_API_KEY)
    monitored_types = config.get(CONF_MONITORED_VARIABLES)
    base_url = "http://{}:{}/".format(host, port)

    sab_api = SabnzbdApi(base_url, api_key)

    try:
        sab_api.check_available()
    except SabnzbdApiException:
        _LOGGER.exception("Connection to SABnzbd API failed")
        return False

    # pylint: disable=global-statement
    global _THROTTLED_REFRESH
    _THROTTLED_REFRESH = Throttle(MIN_TIME_BETWEEN_UPDATES)(
        sab_api.refresh_queue)

    devices = []
    for variable in monitored_types:
        devices.append(SabnzbdSensor(variable, sab_api, name))

    add_devices(devices)
    def __init__(self, hass, min_colortemp, max_colortemp,
                    sunrise_offset, sunset_offset, sunrise_time, sunset_time,
                    latitude, longitude, elevation,
                    interval, transition):
        self.hass = hass
        self.data = {}
        self.data['min_colortemp'] = min_colortemp
        self.data['max_colortemp'] = max_colortemp
        self.data['sunrise_offset'] = sunrise_offset
        self.data['sunset_offset'] = sunset_offset
        self.data['sunrise_time'] = sunrise_time
        self.data['sunset_time'] = sunset_time
        self.data['latitude'] = latitude
        self.data['longitude'] = longitude
        self.data['elevation'] = elevation
        self.data['interval'] = interval
        self.data['transition'] = transition
        self.data['percent'] = self.calc_percent()
        self.data['colortemp'] = self.calc_colortemp()
        self.data['rgb_color'] = self.calc_rgb()
        self.data['xy_color'] = self.calc_xy()
        self.data['hs_color'] = self.calc_hs()

        self.update = Throttle(timedelta(seconds=interval))(self._update)

        if self.data['sunrise_time'] is not None:
            track_time_change(self.hass, self._update, hour=int(self.data['sunrise_time'].strftime("%H")), minute=int(self.data['sunrise_time'].strftime("%M")), second=int(self.data['sunrise_time'].strftime("%S")))
        else:
            track_sunrise(self.hass, self._update, self.data['sunrise_offset'])
        if self.data['sunset_time'] is not None:
            track_time_change(self.hass, self._update, hour=int(self.data['sunset_time'].strftime("%H")), minute=int(self.data['sunset_time'].strftime("%M")), second=int(self.data['sunset_time'].strftime("%S")))
        else:
            track_sunset(self.hass, self._update, self.data['sunset_offset'])
Example #18
0
 def __init__(self, client, uuid, throttle):
     """Initialize the data object."""
     self._client = client
     self._uuid = uuid
     self.data = {}
     self.attrs = {}
     self.async_update = Throttle(throttle)(self._async_update)
Example #19
0
 def __init__(self, hass, api, host):
     """Initialize the data object."""
     self.api = api
     self.hass = hass
     self.host = host
     self.update = Throttle(SCAN_INTERVAL)(self._update)
     self.data = {}
Example #20
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the SABnzbd sensors. """
    from pysabnzbd import SabnzbdApi, SabnzbdApiException

    api_key = config.get("api_key")
    base_url = config.get("base_url")
    name = config.get("name", "SABnzbd")
    if not base_url:
        _LOGGER.error('Missing config variable base_url')
        return False
    if not api_key:
        _LOGGER.error('Missing config variable api_key')
        return False

    sab_api = SabnzbdApi(base_url, api_key)

    try:
        sab_api.check_available()
    except SabnzbdApiException:
        _LOGGER.exception("Connection to SABnzbd API failed.")
        return False

    # pylint: disable=global-statement
    global _THROTTLED_REFRESH
    _THROTTLED_REFRESH = Throttle(timedelta(seconds=1))(sab_api.refresh_queue)

    dev = []
    for variable in config['monitored_variables']:
        if variable['type'] not in SENSOR_TYPES:
            _LOGGER.error('Sensor type: "%s" does not exist', variable['type'])
        else:
            dev.append(SabnzbdSensor(variable['type'], sab_api, name))

    add_devices(dev)
Example #21
0
 def __init__(self, name, carrier, interval):
     """Initialize the sensor."""
     self._carrier = carrier
     self._name = name
     self._attributes = None
     self._state = None
     self.update = Throttle(interval)(self._update)
    def __init__(self, hass, config):
        """Initialize the data object."""
        self._host = config.get(CONF_HOST)
        self._port = config.get(CONF_PORT)
        self._folder = config.get(CONF_FOLDER)
        self._user = config.get(CONF_USERNAME)
        self._pwd = config.get(CONF_PASSWORD)
        self._img_out_path = config.get(CONF_PATH)
        self._gif_duration = config.get(CONF_DURATION)
        self._image_security = config.get(CONF_IMAGE_SECURITY)
        self._scan_interval = timedelta(minutes=config.get(CONF_SCAN_INTERVAL))
        self._fedex_delivered = None
        self._fedex_delivering = None
        self._fedex_packages = None
        self._ups_packages = None
        self._ups_delivering = None
        self._ups_delivered = None
        self._usps_packages = None
        self._usps_delivering = None
        self._usps_delivered = None
        self._usps_mail = None
        self._packages_delivered = None
        self._packages_transit = None
        self._amazon_packages = None
        self._amazon_items = None
        self._image_name = None
        _LOGGER.debug("Config scan interval: %s", self._scan_interval)

        self.update = Throttle(self._scan_interval)(self.update)
Example #23
0
def setup(hass, config):
    """Set up the Verisure component."""
    import verisure
    global HUB
    HUB = VerisureHub(config[DOMAIN], verisure)
    HUB.update_overview = Throttle(
        config[DOMAIN][CONF_SCAN_INTERVAL])(HUB.update_overview)
    if not HUB.login():
        return False
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP,
                         lambda event: HUB.logout())
    HUB.update_overview()

    for component in ('sensor', 'switch', 'alarm_control_panel', 'lock',
                      'camera', 'binary_sensor'):
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    def capture_smartcam(service):
        """Capture a new picture from a smartcam."""
        device_id = service.data.get(ATTR_DEVICE_SERIAL)
        HUB.smartcam_capture(device_id)
        _LOGGER.debug("Capturing new image from %s", ATTR_DEVICE_SERIAL)

    hass.services.register(DOMAIN, SERVICE_CAPTURE_SMARTCAM,
                           capture_smartcam,
                           schema=CAPTURE_IMAGE_SCHEMA)

    return True
Example #24
0
 def __init__(self, hass, coordinator: LockManagerCoordinator):
     """Initialize the data object."""
     self._hass = hass
     self._errors = 0
     self._enabled = False
     self.update = Throttle(timedelta(seconds=30))(self.update)
     self._coordinator = coordinator
    def __init__(self, host, scan_interval):
        """Initialize the inverter."""
        self._host = host
        self._scan_interval = scan_interval
        self.result = None

        # Throttle the update method.
        self.update = Throttle(self._scan_interval)(self._update)
Example #26
0
 def __init__(self, session, interval):
     """Initialize the sensor."""
     import myusps
     self._session = session
     self._profile = myusps.get_profile(session)
     self._packages = None
     self.update = Throttle(interval)(self._update)
     self.update()
Example #27
0
 def __init__(self, api, device, billing_type, interval):
     """Initialize the Billing API wrapper class."""
     self.api = api
     self.site_id = device['id']
     self.timezone = device['timezone']
     self.type = billing_type
     self.result = None
     self.update = Throttle(interval)(self.update)
Example #28
0
 def __init__(self, zoneid, event_urgency, event_severity, latitude,
              longitude, interval):
     self._zoneid = zoneid
     self.latitude = latitude
     self.longitude = longitude
     self._event_urgency = event_urgency
     self._event_severity = event_severity
     self.update = Throttle(interval)(self._update)
Example #29
0
    def __init__(self, api_key, spot_id, units):
        """Initialize the data object."""
        self._msw = magicseaweed.MSW_Forecast(api_key, spot_id, None, units)
        self.currently = None
        self.hourly = {}

        # Apply throttling to methods using configured interval
        self.update = Throttle(MIN_TIME_BETWEEN_UPDATES)(self._update)
Example #30
0
 def __init__(self, x, y, radius, api_key, scan_interval):
     self._x = x
     self._y = y
     self._radius = radius
     self._api_key = api_key
     self.szukaj_burzy_output = None
     self.ostrzezenia_pogodowe_output = None
     self.async_update = Throttle(scan_interval)(self._async_update)