desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get the ups alias from NUT.'
def _get_alias(self):
try: return next(iter(self._client.list_ups())) except self.pynuterror as err: _LOGGER.error('Failure getting NUT ups alias, %s', err) return None
'Get the ups status from NUT.'
def _get_status(self):
if (self._alias is None): self._alias = self._get_alias() try: return self._client.list_vars(self._alias) except (self.pynuterror, ConnectionResetError) as err: _LOGGER.debug('Error getting NUT vars for host %s: %s', self._host, err) return None
'Fetch the latest status from APCUPSd.'
@Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self, **kwargs):
self._status = self._get_status()
'Initialize a BloomSky sensor.'
def __init__(self, bs, device, sensor_name):
self._bloomsky = bs self._device_id = device['DeviceID'] self._sensor_name = sensor_name self._name = '{} {}'.format(device['DeviceName'], sensor_name) self._unique_id = 'bloomsky_sensor {}'.format(self._name) self._state = None
'Return the name of the BloomSky device and this sensor.'
@property def name(self):
return self._name
'Return the unique ID for this sensor.'
@property def unique_id(self):
return self._unique_id
'Return the current state, eg. value, of this sensor.'
@property def state(self):
return self._state
'Return the sensor units.'
@property def unit_of_measurement(self):
return SENSOR_UNITS.get(self._sensor_name, None)
'Request an update from the BloomSky API.'
def update(self):
self._bloomsky.refresh_devices() state = self._bloomsky.devices[self._device_id]['Data'][self._sensor_name] if (self._sensor_name in FORMAT_NUMBERS): self._state = '{0:.2f}'.format(state) else: self._state = state
'Initialize the Email Reader.'
def __init__(self, user, password, server, port):
self._user = user self._password = password self._server = server self._port = port self._last_id = None self._unread_ids = deque([]) self.connection = None
'Login and setup the connection.'
def connect(self):
import imaplib try: self.connection = imaplib.IMAP4_SSL(self._server, self._port) self.connection.login(self._user, self._password) return True except imaplib.IMAP4.error: _LOGGER.error('Failed to login to %s', self._server) return False
'Get an email message from a message id.'
def _fetch_message(self, message_uid):
(_, message_data) = self.connection.uid('fetch', message_uid, '(RFC822)') raw_email = message_data[0][1] email_message = email.message_from_bytes(raw_email) return email_message
'Read the next email from the email server.'
def read_next(self):
import imaplib try: self.connection.select() if (not self._unread_ids): search = 'SINCE {0:%d-%b-%Y}'.format(datetime.date.today()) if (self._last_id is not None): search = 'UID {}:*'.format(self._last_id) (_, data) = self.connection.uid(...
'Initialize the sensor.'
def __init__(self, hass, email_reader, name, allowed_senders, value_template):
self.hass = hass self._email_reader = email_reader self._name = name self._allowed_senders = [sender.upper() for sender in allowed_senders] self._value_template = value_template self._last_id = None self._message = None self._state_attributes = None self.connected = self._email_reade...
'Return the name of the sensor.'
@property def name(self):
return self._name
'Return the current email state.'
@property def state(self):
return self._message
'Return other state attributes for the message.'
@property def device_state_attributes(self):
return self._state_attributes
'Render the message template.'
def render_template(self, email_message):
variables = {ATTR_FROM: EmailContentSensor.get_msg_sender(email_message), ATTR_SUBJECT: EmailContentSensor.get_msg_subject(email_message), ATTR_DATE: email_message['Date'], ATTR_BODY: EmailContentSensor.get_msg_text(email_message)} return self._value_template.render(variables)
'Check if the sender is in the allowed senders list.'
def sender_allowed(self, email_message):
return (EmailContentSensor.get_msg_sender(email_message).upper() in (sender for sender in self._allowed_senders))
'Get the parsed message sender from the email.'
@staticmethod def get_msg_sender(email_message):
return str(email.utils.parseaddr(email_message['From'])[1])
'Decode the message subject.'
@staticmethod def get_msg_subject(email_message):
decoded_header = email.header.decode_header(email_message['Subject']) header = email.header.make_header(decoded_header) return str(header)
'Get the message text from the email. Will look for text/plain or use text/html if not found.'
@staticmethod def get_msg_text(email_message):
message_text = None message_html = None message_untyped_text = None for part in email_message.walk(): if (part.get_content_type() == CONTENT_TYPE_TEXT_PLAIN): if (message_text is None): message_text = part.get_payload() elif (part.get_content_type() == 'text/h...
'Read emails and publish state change.'
def update(self):
email_message = self._email_reader.read_next() if (email_message is None): return if self.sender_allowed(email_message): message_body = EmailContentSensor.get_msg_text(email_message) if (self._value_template is not None): message_body = self.render_template(email_message)...
'Initialize the sensor.'
def __init__(self, sensor_type, app_token, utc_offset, period, currency, sid=None):
self.sid = sid if sid: self._name = ('efergy_' + sid) else: self._name = SENSOR_TYPES[sensor_type][0] self.type = sensor_type self.app_token = app_token self.utc_offset = utc_offset self._state = None self.period = period self.currency = currency if (self.type == ...
'Return the name of the sensor.'
@property def name(self):
return self._name
'Return the state of the sensor.'
@property def state(self):
return self._state
'Return the unit of measurement of this entity, if any.'
@property def unit_of_measurement(self):
return self._unit_of_measurement
'Get the Efergy monitor data from the web service.'
def update(self):
try: if (self.type == 'instant_readings'): url_string = ((_RESOURCE + 'getInstant?token=') + self.app_token) response = get(url_string, timeout=10) self._state = response.json()['reading'] elif (self.type == 'amount'): url_string = ((((((_RESOURCE + 'g...
'Initialize the sensor.'
def __init__(self, api):
self._api = api self._state = None
'Return the name of the sensor.'
@property def name(self):
return SENSOR_NAME
'Return the sensor state.'
@property def state(self):
return self._state
'Return the icon for the sensor.'
@property def icon(self):
return ICON
'Update sensor values.'
def update(self):
try: self._state = len(self._api.new_episodes_released()) _LOGGER.debug('Found %d new episodes', self._state) except OSError as err: _LOGGER.warning('Failed to contact server: %s', err)
'Set all the config values if they exist and get initial state.'
def __init__(self, hass, config):
value_template = config.get(CONF_VALUE_TEMPLATE) if (value_template is not None): value_template.hass = hass self._hass = hass self._config = {CONF_NAME: config.get(CONF_NAME), CONF_HOST: config.get(CONF_HOST), CONF_PORT: config.get(CONF_PORT), CONF_TIMEOUT: config.get(CONF_TIMEOUT), CONF_PAYLOA...
'Return the name of this sensor.'
@property def name(self):
name = self._config[CONF_NAME] if (name is not None): return name return super(TcpSensor, self).name
'Return the state of the device.'
@property def state(self):
return self._state
'Return the unit of measurement of this entity.'
@property def unit_of_measurement(self):
return self._config[CONF_UNIT_OF_MEASUREMENT]
'Get the latest value for this sensor.'
def update(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.settimeout(self._config[CONF_TIMEOUT]) try: sock.connect((self._config[CONF_HOST], self._config[CONF_PORT])) except socket.error as err: _LOGGER.error('Unable to connect to %s on po...
'Handle sensor specific args and super init.'
def __init__(self, device_id, hass, sensor_type, unit_of_measurement, **kwargs):
self._sensor_type = sensor_type self._unit_of_measurement = unit_of_measurement super().__init__(device_id, hass, **kwargs)
'Domain specific event handler.'
def _handle_event(self, event):
self._state = event['value']
'Return measurement unit.'
@property def unit_of_measurement(self):
return self._unit_of_measurement
'Return value.'
@property def state(self):
return self._state
'Return possible sensor specific icon.'
@property def icon(self):
if (self._sensor_type in SENSOR_ICONS): return SENSOR_ICONS[self._sensor_type]
'Initialize the sensor.'
def __init__(self, hass, influx_conf, query):
from influxdb import InfluxDBClient, exceptions self._name = query.get(CONF_NAME) self._unit_of_measurement = query.get(CONF_UNIT_OF_MEASUREMENT) value_template = query.get(CONF_VALUE_TEMPLATE) if (value_template is not None): self._value_template = value_template self._value_templat...
'Return the name of the sensor.'
@property def name(self):
return self._name
'Return the state of the sensor.'
@property def state(self):
return self._state
'Return the unit of measurement of this entity, if any.'
@property def unit_of_measurement(self):
return self._unit_of_measurement
'Return the polling state.'
@property def should_poll(self):
return True
'Get the latest data from Influxdb and updates the states.'
def update(self):
self.data.update() value = self.data.value if (value is None): value = STATE_UNKNOWN if (self._value_template is not None): value = self._value_template.render_with_possible_json_value(str(value), STATE_UNKNOWN) self._state = value
'Initialize the data object.'
def __init__(self, influx, group, field, measurement, where):
self.influx = influx self.group = group self.field = field self.measurement = measurement self.where = where self.value = None self.query = None
'Get the latest data with a shell command.'
@Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self):
_LOGGER.info('Rendering where: %s', self.where) try: where_clause = self.where.render() except TemplateError as ex: _LOGGER.error('Could not render where clause template: %s', ex) return self.query = 'select {}({}) as value from {} where ...
'Initialize of the Tado Sensor.'
def __init__(self, store, zone_name, zone_id, zone_variable, data_id):
self._store = store self.zone_name = zone_name self.zone_id = zone_id self.zone_variable = zone_variable self._unique_id = '{} {}'.format(zone_variable, zone_id) self._data_id = data_id self._state = None self._state_attributes = None
'Return the unique id.'
@property def unique_id(self):
return self._unique_id
'Return the name of the sensor.'
@property def name(self):
return '{} {}'.format(self.zone_name, self.zone_variable)
'Return the state of the sensor.'
@property def state(self):
return self._state
'Return the state attributes.'
@property def device_state_attributes(self):
return self._state_attributes
'Return the unit of measurement.'
@property def unit_of_measurement(self):
if (self.zone_variable == 'temperature'): return self.hass.config.units.temperature_unit elif (self.zone_variable == 'humidity'): return '%' elif (self.zone_variable == 'heating'): return '%'
'Icon for the sensor.'
@property def icon(self):
if (self.zone_variable == 'temperature'): return 'mdi:thermometer' elif (self.zone_variable == 'humidity'): return 'mdi:water-percent'
'Update method called when should_poll is true.'
def update(self):
self._store.update() data = self._store.get_data(self._data_id) if (data is None): _LOGGER.debug('Recieved no data for zone %s', self.zone_name) return unit = TEMP_CELSIUS if (self.zone_variable == 'temperature'): if ('sensorDataPoints' in data): se...
'Initialize the Pushbullet sensor.'
def __init__(self, pb, element):
self.pushbullet = pb self._element = element self._state = None self._state_attributes = None
'Fetch the latest data from the sensor. This will fetch the \'sensor reading\' into self._state but also all attributes into self._state_attributes.'
def update(self):
try: self._state = self.pushbullet.data[self._element] self._state_attributes = self.pushbullet.data except (KeyError, TypeError): pass
'Return the name of the sensor.'
@property def name(self):
return '{} {}'.format('Pushbullet', self._element)
'Return the current state of the sensor.'
@property def state(self):
return self._state
'Return all known attributes of the sensor.'
@property def device_state_attributes(self):
return self._state_attributes
'Start to retrieve pushes from the given Pushbullet instance.'
def __init__(self, pb):
import threading self.pushbullet = pb self._data = None self.listener = None self.thread = threading.Thread(target=self.retrieve_pushes) self.thread.daemon = True self.thread.start()
'Update the current data. Currently only monitors pushes but might be extended to monitor different kinds of Pushbullet events.'
def on_push(self, data):
if (data['type'] == 'push'): self._data = data['push']
'Return the current data stored in the provider.'
@property def data(self):
return self._data
'Retrieve_pushes. Spawn a new Listener and links it to self.on_push.'
def retrieve_pushes(self):
from pushbullet import Listener self.listener = Listener(account=self.pushbullet, on_push=self.on_push) _LOGGER.debug('Getting pushes') try: self.listener.run_forever() finally: self.listener.close()
'Initialize the EnOcean sensor device.'
def __init__(self, dev_id, devname):
enocean.EnOceanDevice.__init__(self) self.stype = 'powersensor' self.power = None self.dev_id = dev_id self.which = (-1) self.onoff = (-1) self.devname = devname
'Return the name of the device.'
@property def name(self):
return ('Power %s' % self.devname)
'Update the internal state of the device.'
def value_changed(self, value):
self.power = value self.schedule_update_ha_state()
'Return the state of the device.'
@property def state(self):
return self.power
'Return the unit of measurement.'
@property def unit_of_measurement(self):
return 'W'
'Initialize the sensor.'
def __init__(self, name):
self._name = name self._state = None self.info = None self._unit_of_measurement = 'GHz'
'Return the name of the sensor.'
@property def name(self):
return self._name
'Return the state of the sensor.'
@property def state(self):
return self._state
'Return the unit the value is expressed in.'
@property def unit_of_measurement(self):
return self._unit_of_measurement
'Return the state attributes.'
@property def device_state_attributes(self):
if (self.info is not None): return {ATTR_ARCH: self.info['arch'], ATTR_BRAND: self.info['brand'], ATTR_HZ: round((self.info['hz_advertised_raw'][0] / (10 ** 9)), 2)}
'Return the icon to use in the frontend, if any.'
@property def icon(self):
return ICON
'Get the latest data and updates the state.'
def update(self):
from cpuinfo import cpuinfo self.info = cpuinfo.get_cpu_info() self._state = round((float(self.info['hz_actual_raw'][0]) / (10 ** 9)), 2)
'Initialize the sensor.'
def __init__(self, session, name, interval):
self._session = session self._name = name self._attributes = None self._state = None self.update = Throttle(interval)(self._update)
'Return the name of the sensor.'
@property def name(self):
return (self._name or DOMAIN)
'Return the state of the sensor.'
@property def state(self):
return self._state
'Update device state.'
def _update(self):
import fedexdeliverymanager status_counts = defaultdict(int) for package in fedexdeliverymanager.get_packages(self._session): status = slugify(package['primary_status']) skip = ((status == STATUS_DELIVERED) and (parse_date(package['delivery_date']) < now().date())) if skip: ...
'Return the state attributes.'
@property def device_state_attributes(self):
return self._attributes
'Icon to use in the frontend.'
@property def icon(self):
return ICON
'Initialize a sensor for Amcrest camera.'
def __init__(self, name, camera, sensor_type):
self._attrs = {} self._camera = camera self._sensor_type = sensor_type self._name = '{0}_{1}'.format(name, SENSORS.get(self._sensor_type)[0]) self._icon = 'mdi:{}'.format(SENSORS.get(self._sensor_type)[2]) self._state = STATE_UNKNOWN
'Return the name of the sensor.'
@property def name(self):
return self._name
'Return the state of the sensor.'
@property def state(self):
return self._state
'Return the state attributes.'
@property def device_state_attributes(self):
return self._attrs
'Icon to use in the frontend, if any.'
@property def icon(self):
return self._icon
'Return the units of measurement.'
@property def unit_of_measurement(self):
return SENSORS.get(self._sensor_type)[1]
'Get the latest data and updates the state.'
def update(self):
_LOGGER.debug('Pulling data from %s sensor.', self._name) try: (version, build_date) = self._camera.software_information self._attrs['Build Date'] = build_date.split('=')[(-1)] self._attrs['Version'] = version.split('=')[(-1)] except ValueError: self._attrs['Bu...
'Initialize the sensor.'
def __init__(self, ip_address, name):
self._url = 'http://{}/instantaneousdemand'.format(ip_address) self._name = name self._unit_of_measurement = 'kW' self._state = None
'Return the name of th sensor.'
@property def name(self):
return self._name
'Return the state of the sensor.'
@property def state(self):
return self._state
'Return the unit of measurement of this entity, if any.'
@property def unit_of_measurement(self):
return self._unit_of_measurement
'Icon to use in the frontend, if any.'
@property def icon(self):
return ICON
'Get the energy usage data from the DTE energy bridge.'
def update(self):
import requests try: response = requests.get(self._url, timeout=5) except (requests.exceptions.RequestException, ValueError): _LOGGER.warning('Could not update status for DTE Energy Bridge (%s)', self._name) return if (response.status_code != 200): ...
'Initialize the API wrapper class.'
def __init__(self, host, port, username, password, temp_unit):
from SynologyDSM import SynologyDSM self.temp_unit = temp_unit try: self._api = SynologyDSM(host, port, username, password) except: _LOGGER.error('Error setting up Synology DSM') self.utilisation = self._api.utilisation self.storage = self._api.storage