desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initialize the service.'
def __init__(self, twilio_client, from_number):
self.client = twilio_client self.from_number = from_number
'Call to specified target users.'
def send_message(self, message='', **kwargs):
from twilio import TwilioRestException targets = kwargs.get(ATTR_TARGET) if (not targets): _LOGGER.info('At least 1 target is required') return if message.startswith(('http://', 'https://')): twimlet_url = message else: twimlet_url = 'http://twimlets.co...
'Initialize the service.'
def __init__(self, hass, filename, add_timestamp):
self.filepath = os.path.join(hass.config.config_dir, filename) self.add_timestamp = add_timestamp
'Send a message to a file.'
def send_message(self, message='', **kwargs):
with open(self.filepath, 'a') as file: if (os.stat(self.filepath).st_size == 0): title = '{} notifications (Log started: {})\n{}\n'.format(kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT), dt_util.utcnow().isoformat(), ('-' * 80)) file.write(title) if self.add_timestamp...
'Return a dictionary of registered targets.'
@property def targets(self):
return ios.devices_with_push()
'Send a message to the Lambda APNS gateway.'
def send_message(self, message='', **kwargs):
data = {ATTR_MESSAGE: message} if (kwargs.get(ATTR_TITLE) is not None): if (kwargs.get(ATTR_TITLE) != ATTR_TITLE_DEFAULT): data[ATTR_TITLE] = kwargs.get(ATTR_TITLE) targets = kwargs.get(ATTR_TARGET) if (not targets): targets = ios.enabled_push_ids() if (kwargs.get(ATTR_DA...
'Initialize the service.'
def __init__(self, api_key):
self._api_key = api_key
'Send a message to a user.'
def send_message(self, message='', **kwargs):
data = {'apikey': self._api_key, 'application': 'home-assistant', 'event': kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT), 'description': message, 'priority': 0} response = requests.get('{}{}'.format(_RESOURCE, 'notify'), params=data, timeout=5) tree = ET.fromstring(response.content) if (tree[0].tag == 'err...
'Initialize the service.'
def __init__(self, api_key, sender, recipient):
from sendgrid import SendGridAPIClient self.api_key = api_key self.sender = sender self.recipient = recipient self._sg = SendGridAPIClient(apikey=self.api_key)
'Send an email to a user via SendGrid.'
def send_message(self, message='', **kwargs):
subject = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) data = {'personalizations': [{'to': [{'email': self.recipient}], 'subject': subject}], 'from': {'email': self.sender}, 'content': [{'type': 'text/plain', 'value': message}]} response = self._sg.client.mail.send.post(request_body=data) if (response.sta...
'Initialize the service.'
def __init__(self, twilio_client, from_number):
self.client = twilio_client self.from_number = from_number
'Send SMS to specified target user cell.'
def send_message(self, message='', **kwargs):
targets = kwargs.get(ATTR_TARGET) if (not targets): _LOGGER.info('At least 1 target is required') return for target in targets: self.client.messages.create(to=target, body=message, from_=self.from_number)
'Initialize the service.'
def __init__(self, api_key, app_secret, event, tracker):
self._api_key = api_key self._app_secret = app_secret self._event = event self._tracker = tracker self._headers = {HTTP_HEADER_APPID: self._api_key, HTTP_HEADER_APPSECRET: self._app_secret, HTTP_HEADER_CONTENT_TYPE: CONTENT_TYPE_JSON}
'Send a message to a user.'
def send_message(self, message='', **kwargs):
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) data = {'event': self._event, 'trackers': {self._tracker: '{} : {}'.format(title, message)}} response = requests.post('{}{}'.format(_RESOURCE, 'post'), data=json.dumps(data), headers=self._headers, timeout=DEFAULT_TIMEOUT) if (response.json()['sta...
'Set up the client.'
def __init__(self, config_file, homeserver, default_room, verify_ssl, username, password):
self.session_filepath = config_file self.auth_tokens = self.get_auth_tokens() self.homeserver = homeserver self.default_room = default_room self.verify_tls = verify_ssl self.username = username self.password = password self.mx_id = '{user}@{homeserver}'.format(user=username, homeserver=u...
'Read sorted authentication tokens from disk. Returns the auth_tokens dictionary.'
def get_auth_tokens(self):
if (not os.path.exists(self.session_filepath)): return {} try: with open(self.session_filepath) as handle: data = json.load(handle) auth_tokens = {} for (mx_id, token) in data.items(): auth_tokens[mx_id] = token return auth_tokens except (OSErr...
'Store authentication token to session and persistent storage.'
def store_auth_token(self, token):
self.auth_tokens[self.mx_id] = token try: with open(self.session_filepath, 'w') as handle: handle.write(json.dumps(self.auth_tokens)) except (OSError, IOError, PermissionError) as ex: _LOGGER.warning("Storing authentication tokens to file '%s' failed: %s", se...
'Login to the matrix homeserver and return the client instance.'
def login(self):
from matrix_client.client import MatrixRequestError client = None if (self.mx_id in self.auth_tokens): try: client = self.login_by_token() _LOGGER.debug('Logged in using stored token.') except MatrixRequestError as ex: _LOGGER.warning('Login ...
'Login using authentication token and return the client.'
def login_by_token(self):
from matrix_client.client import MatrixClient return MatrixClient(base_url=self.homeserver, token=self.auth_tokens[self.mx_id], user_id=self.username, valid_cert_check=self.verify_tls)
'Login using password authentication and return the client.'
def login_by_password(self):
from matrix_client.client import MatrixClient _client = MatrixClient(base_url=self.homeserver, valid_cert_check=self.verify_tls) _client.login_with_password(self.username, self.password) self.store_auth_token(_client.token) return _client
'Send the message to the matrix server.'
def send_message(self, message, **kwargs):
from matrix_client.client import MatrixRequestError target_rooms = (kwargs.get(ATTR_TARGET) or [self.default_room]) rooms = self.client.get_rooms() for target_room in target_rooms: try: if (target_room in rooms): room = rooms[target_room] else: ...
'Initialize the service.'
def __init__(self, hass, chat_id):
self._chat_id = chat_id self.hass = hass
'Send a message to a user.'
def send_message(self, message='', **kwargs):
service_data = dict(target=kwargs.get(ATTR_TARGET, self._chat_id)) if (ATTR_TITLE in kwargs): service_data.update({ATTR_TITLE: kwargs.get(ATTR_TITLE)}) if message: service_data.update({ATTR_MESSAGE: message}) data = kwargs.get(ATTR_DATA) if ((data is not None) and (ATTR_KEYBOARD in d...
'Initialize the service.'
def __init__(self, access_token):
self.page_access_token = access_token
'Send some message.'
def send_message(self, message='', **kwargs):
payload = {'access_token': self.page_access_token} targets = kwargs.get(ATTR_TARGET) data = kwargs.get(ATTR_DATA) body_message = {'text': message} if (data is not None): body_message.update(data) if ('attachment' in body_message): body_message.pop('text') if (not targ...
'Initialize the service.'
def __init__(self, sns_client):
self.client = sns_client
'Send notification to specified SNS ARN.'
def send_message(self, message='', **kwargs):
targets = kwargs.get(ATTR_TARGET) if (not targets): _LOGGER.info('At least 1 target is required') return message_attributes = {k: {'StringValue': json.dumps(v), 'DataType': 'String'} for (k, v) in kwargs.items() if v} for target in targets: self.client.publish(Targ...
'Initialize the service.'
def __init__(self, hass):
self.hass = hass
'Return a dictionary of registered targets.'
@property def targets(self):
return {'test target name': 'test target id'}
'Send a message to a user.'
def send_message(self, message='', **kwargs):
kwargs['message'] = message self.hass.bus.fire(EVENT_NOTIFY, kwargs)
'Initialize the service.'
def __init__(self, hasslametricmanager, icon, display_time):
self.hasslametricmanager = hasslametricmanager self._icon = icon self._display_time = display_time
'Send a message to some LaMetric deviced.'
def send_message(self, message='', **kwargs):
from lmnotify import SimpleFrame, Sound, Model targets = kwargs.get(ATTR_TARGET) data = kwargs.get(ATTR_DATA) _LOGGER.debug('Targets/Data: %s/%s', targets, data) icon = self._icon sound = None if (data is not None): if ('icon' in data): icon = data['icon'] if (...
'Initialize Tado data store.'
def __init__(self, tado):
self.tado = tado self.sensors = {} self.data = {}
'Update the internal data from mytado.com.'
@Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self):
for (data_id, sensor) in list(self.sensors.items()): data = None try: if ('zone' in sensor): _LOGGER.info('Querying mytado.com for zone %s %s', sensor['id'], sensor['name']) data = self.tado.getState(sensor['id']) if ('device' in...
'Add a sensor to update in _update().'
def add_sensor(self, data_id, sensor):
self.sensors[data_id] = sensor self.data[data_id] = None
'Get the cached data.'
def get_data(self, data_id):
data = {'error': 'no data'} if (data_id in self.data): data = self.data[data_id] return data
'Wrap for getZones().'
def get_zones(self):
return self.tado.getZones()
'Wrap for getCapabilities(..).'
def get_capabilities(self, tado_id):
return self.tado.getCapabilities(tado_id)
'Wrap for getMet().'
def get_me(self):
return self.tado.getMe()
'Wrap for resetZoneOverlay(..).'
def reset_zone_overlay(self, zone_id):
return self.tado.resetZoneOverlay(zone_id)
'Wrap for setZoneOverlay(..).'
def set_zone_overlay(self, zone_id, mode, temperature=None, duration=None):
return self.tado.setZoneOverlay(zone_id, mode, temperature, duration)
'Initialize the EnOcean dongle.'
def __init__(self, hass, ser):
from enocean.communicators.serialcommunicator import SerialCommunicator self.__communicator = SerialCommunicator(port=ser, callback=self.callback) self.__communicator.start() self.__devices = []
'Register another device.'
def register_device(self, dev):
self.__devices.append(dev)
'Send a command from the EnOcean dongle.'
def send_command(self, command):
self.__communicator.send(command)
'Combine list of integer values to one big integer.'
def _combine_hex(self, data):
output = 0 for (i, j) in enumerate(reversed(data)): output |= (j << (i * 8)) return output
'Handle EnOcean device\'s callback. This is the callback function called by python-enocan whenever there is an incoming packet.'
def callback(self, temp):
from enocean.protocol.packet import RadioPacket if isinstance(temp, RadioPacket): rxtype = None value = None if (temp.data[6] == 48): rxtype = 'wallswitch' value = 1 elif (temp.data[6] == 32): rxtype = 'wallswitch' value = 0 ...
'Initialize the device.'
def __init__(self):
ENOCEAN_DONGLE.register_device(self) self.stype = '' self.sensorid = [0, 0, 0, 0]
'Send a command via the EnOcean dongle.'
def send_command(self, data, optional, packet_type):
from enocean.protocol.packet import Packet packet = Packet(packet_type, data=data, optional=optional) ENOCEAN_DONGLE.send_command(packet)
'Initialize the vacuum.'
def __init__(self, name, supported_features):
self._name = name self._supported_features = supported_features self._state = False self._status = 'Charging' self._fan_speed = FAN_SPEEDS[1] self._cleaned_area = 0 self._battery_level = 100
'Return the name of the vacuum.'
@property def name(self):
return self._name
'Return the icon for the vacuum.'
@property def icon(self):
return DEFAULT_ICON
'No polling needed for a demo vacuum.'
@property def should_poll(self):
return False
'Return true if vacuum is on.'
@property def is_on(self):
return self._state
'Return the status of the vacuum.'
@property def status(self):
if ((self.supported_features & SUPPORT_STATUS) == 0): return return self._status
'Return the status of the vacuum.'
@property def fan_speed(self):
if ((self.supported_features & SUPPORT_FAN_SPEED) == 0): return return self._fan_speed
'Return the status of the vacuum.'
@property def fan_speed_list(self):
assert ((self.supported_features & SUPPORT_FAN_SPEED) != 0) return FAN_SPEEDS
'Return the status of the vacuum.'
@property def battery_level(self):
if ((self.supported_features & SUPPORT_BATTERY) == 0): return return max(0, min(100, self._battery_level))
'Return device state attributes.'
@property def device_state_attributes(self):
return {ATTR_CLEANED_AREA: round(self._cleaned_area, 2)}
'Flag supported features.'
@property def supported_features(self):
return self._supported_features
'Turn the vacuum on.'
def turn_on(self, **kwargs):
if ((self.supported_features & SUPPORT_TURN_ON) == 0): return self._state = True self._cleaned_area += 5.32 self._battery_level -= 2 self._status = 'Cleaning' self.schedule_update_ha_state()
'Turn the vacuum off.'
def turn_off(self, **kwargs):
if ((self.supported_features & SUPPORT_TURN_OFF) == 0): return self._state = False self._status = 'Charging' self.schedule_update_ha_state()
'Turn the vacuum off.'
def stop(self, **kwargs):
if ((self.supported_features & SUPPORT_STOP) == 0): return self._state = False self._status = 'Stopping the current task' self.schedule_update_ha_state()
'Perform a spot clean-up.'
def clean_spot(self, **kwargs):
if ((self.supported_features & SUPPORT_CLEAN_SPOT) == 0): return self._state = True self._cleaned_area += 1.32 self._battery_level -= 1 self._status = 'Cleaning spot' self.schedule_update_ha_state()
'Turn the vacuum off.'
def locate(self, **kwargs):
if ((self.supported_features & SUPPORT_LOCATE) == 0): return self._status = "Hi, I'm over here!" self.schedule_update_ha_state()
'Start, pause or resume the cleaning task.'
def start_pause(self, **kwargs):
if ((self.supported_features & SUPPORT_PAUSE) == 0): return self._state = (not self._state) if self._state: self._status = 'Resuming the current task' self._cleaned_area += 1.32 self._battery_level -= 1 else: self._status = 'Pausing the current t...
'Tell the vacuum to return to its dock.'
def set_fan_speed(self, fan_speed, **kwargs):
if ((self.supported_features & SUPPORT_FAN_SPEED) == 0): return if (fan_speed in self.fan_speed_list): self._fan_speed = fan_speed self.schedule_update_ha_state()
'Tell the vacuum to return to its dock.'
def return_to_base(self, **kwargs):
if ((self.supported_features & SUPPORT_RETURN_HOME) == 0): return self._state = False self._status = 'Returning home...' self._battery_level += 5 self.schedule_update_ha_state()
'Send a command to the vacuum.'
def send_command(self, command, params=None, **kwargs):
if ((self.supported_features & SUPPORT_SEND_COMMAND) == 0): return self._status = 'Executing {}({})'.format(command, params) self._state = True self.schedule_update_ha_state()
'Initialize the Digital Ocean connection.'
def __init__(self, access_token):
import digitalocean self._access_token = access_token self.data = None self.manager = digitalocean.Manager(token=self._access_token)
'Get the status of a Digital Ocean droplet.'
def get_droplet_id(self, droplet_name):
droplet_id = None all_droplets = self.manager.get_all_droplets() for droplet in all_droplets: if (droplet_name == droplet.name): droplet_id = droplet.id return droplet_id
'Use the data from Digital Ocean API.'
@Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self):
self.data = self.manager.get_all_droplets()
'Initialize the proximity.'
def __init__(self, hass, zone_friendly_name, dist_to, dir_of_travel, nearest, ignored_zones, proximity_devices, tolerance, proximity_zone, unit_of_measurement):
self.hass = hass self.friendly_name = zone_friendly_name self.dist_to = dist_to self.dir_of_travel = dir_of_travel self.nearest = nearest self.ignored_zones = ignored_zones self.proximity_devices = proximity_devices self.tolerance = tolerance self.proximity_zone = proximity_zone ...
'Return the name of the entity.'
@property def name(self):
return self.friendly_name
'Return the state.'
@property def state(self):
return self.dist_to
'Return the unit of measurement of this entity.'
@property def unit_of_measurement(self):
return self._unit_of_measurement
'Return the state attributes.'
@property def state_attributes(self):
return {ATTR_DIR_OF_TRAVEL: self.dir_of_travel, ATTR_NEAREST: self.nearest}
'Perform the proximity checking.'
def check_proximity_state_change(self, entity, old_state, new_state):
entity_name = new_state.name devices_to_calculate = False devices_in_zone = '' zone_state = self.hass.states.get(self.proximity_zone) proximity_latitude = zone_state.attributes.get('latitude') proximity_longitude = zone_state.attributes.get('longitude') for device in self.proximity_devices: ...
'Initialize Prometheus Metrics.'
def __init__(self, prometheus_client, exclude, include):
self.prometheus_client = prometheus_client self.exclude = (exclude.get(CONF_ENTITIES, []) + exclude.get(CONF_DOMAINS, [])) self.include_domains = include.get(CONF_DOMAINS, []) self.include_entities = include.get(CONF_ENTITIES, []) self._metrics = {}
'Listen for new messages on the bus, and add them to Prometheus.'
def handle_event(self, event):
state = event.data.get('new_state') if (state is None): return entity_id = state.entity_id _LOGGER.debug('Handling state update for %s', entity_id) (domain, _) = hacore.split_entity_id(entity_id) if (entity_id in self.exclude): return if ((domain in self.exclude) ...
'Initialize Prometheus view.'
def __init__(self, prometheus_client):
self.prometheus_client = prometheus_client
'Handle request for Prometheus metrics.'
@asyncio.coroutine def get(self, request):
_LOGGER.debug('Received Prometheus metrics request') return web.Response(body=self.prometheus_client.generate_latest(), content_type='text/plain')
'Return true so entity knows we have new data.'
def update(self):
return True
'Set the event to a future event.'
def __init__(self):
one_hour_from_now = (dt_util.now() + dt_util.dt.timedelta(minutes=30)) self.event = {'start': {'dateTime': one_hour_from_now.isoformat()}, 'end': {'dateTime': (one_hour_from_now + dt_util.dt.timedelta(minutes=60)).isoformat()}, 'summary': 'Future Event'}
'Set the event data.'
def __init__(self):
middle_of_event = (dt_util.now() - dt_util.dt.timedelta(minutes=30)) self.event = {'start': {'dateTime': middle_of_event.isoformat()}, 'end': {'dateTime': (middle_of_event + dt_util.dt.timedelta(minutes=60)).isoformat()}, 'summary': 'Current Event'}
'Initialize Google Calendar but without the API calls.'
def __init__(self, hass, calendar_data, data):
self.data = calendar_data super().__init__(hass, data)
'Create the Calendar event device.'
def __init__(self, hass, calendar_service, calendar, data):
self.data = GoogleCalendarData(calendar_service, calendar, data.get('search', None)) super().__init__(hass, data)
'Set up how we are going to search the google calendar.'
def __init__(self, calendar_service, calendar_id, search=None):
self.calendar_service = calendar_service self.calendar_id = calendar_id self.search = search self.event = None
'Get the latest data.'
@Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self):
service = self.calendar_service.get() params = dict(DEFAULT_GOOGLE_SEARCH_PARAMS) params['timeMin'] = dt.now().isoformat('T') params['calendarId'] = self.calendar_id if self.search: params['q'] = self.search events = service.events() result = events.list(**params).execute() items...
'Initialize the switch.'
def __init__(self, smartplug, name):
self.smartplug = smartplug self._name = name self._now_power = None self._now_energy_day = None self._state = False
'Return the name of the Smart Plug, if any.'
@property def name(self):
return self._name
'Return the current power usage in W.'
@property def current_power_w(self):
return self._now_power
'Return the today total energy usage in kWh.'
@property def today_energy_kwh(self):
return self._now_energy_day
'Return true if switch is on.'
@property def is_on(self):
return self._state
'Turn the switch on.'
def turn_on(self, **kwargs):
self.smartplug.state = 'ON'
'Turn the switch off.'
def turn_off(self):
self.smartplug.state = 'OFF'
'Update edimax switch.'
def update(self):
try: self._now_power = (float(self.smartplug.now_power) / 1000000.0) except (TypeError, ValueError): self._now_power = None try: self._now_energy_day = (float(self.smartplug.now_energy_day) / 1000.0) except (TypeError, ValueError): self._now_energy_day = None self._st...
'Initialize the switch.'
def __init__(self, resource, location, name):
self._resource = resource self._name = '{} {}'.format(location.title(), name.title()) self._state = None self._available = True
'Return the name of the switch.'
@property def name(self):
return self._name
'Return true if device is on.'
@property def is_on(self):
return self._state
'Could the device be accessed during the last update call.'
@property def available(self):
return self._available