コード例 #1
0
ファイル: wink.py プロジェクト: GadgetReactor/home-assistant
def setup(hass, config):
    """Setup the Wink component."""
    import pywink

    user_agent = config[DOMAIN][CONF_USER_AGENT]

    if user_agent:
        pywink.set_user_agent(user_agent)

    from pubnub import Pubnub
    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)

    if access_token:
        pywink.set_bearer_token(access_token)
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id,
                                    client_secret)

    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub(
        'N/A', pywink.get_subscription_key(), ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        discovery.load_platform(hass, component, DOMAIN, {}, config)
    return True
コード例 #2
0
ファイル: wink.py プロジェクト: saouinet/home-assistant
def setup(hass, config):
    """Setup the Wink component."""
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])

    # Load components for the devices in the Wink that we support
    for component_name, func_exists in (
            ('light', pywink.get_bulbs),
            ('switch', lambda: pywink.get_switches or pywink.get_sirens or
             pywink.get_powerstrip_outlets),
            ('binary_sensor', pywink.get_sensors),
            ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays),
            ('lock', pywink.get_locks),
            ('rollershutter', pywink.get_shades),
            ('garage_door', pywink.get_garage_doors)):

        if func_exists():
            discovery.load_platform(hass, component_name, DOMAIN, {}, config)

    return True
コード例 #3
0
def setup(hass, config):
    """Setup the Wink component."""
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    from pubnub import Pubnub
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])
    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub("N/A", pywink.get_subscription_key(),
                                  ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in the Wink that we support
    for component_name, func_exists in (
            ('light', pywink.get_bulbs),
            ('switch', lambda: pywink.get_switches or pywink.get_sirens or
             pywink.get_powerstrip_outlets),
            ('binary_sensor', pywink.get_sensors),
            ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays),
            ('lock', pywink.get_locks),
            ('rollershutter', pywink.get_shades),
            ('garage_door', pywink.get_garage_doors)):

        if func_exists():
            discovery.load_platform(hass, component_name, DOMAIN, {}, config)

    return True
コード例 #4
0
ファイル: wink.py プロジェクト: Baltibu/home-assistant
def setup(hass, config):
    """ Sets up the Wink component. """
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])

    # Load components for the devices in the Wink that we support
    for component_name, func_exists, discovery_type in (
            ('light', pywink.get_bulbs, DISCOVER_LIGHTS),
            ('switch', pywink.get_switches, DISCOVER_SWITCHES),
            ('sensor', pywink.get_sensors, DISCOVER_SENSORS)):

        if func_exists():
            component = get_component(component_name)

            # Ensure component is loaded
            bootstrap.setup_component(hass, component.DOMAIN, config)

            # Fire discovery event
            hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {
                ATTR_SERVICE: discovery_type,
                ATTR_DISCOVERED: {}
            })

    return True
コード例 #5
0
ファイル: wink.py プロジェクト: mysticbalance/homeassistant
def setup(hass, config):
    """Set up the Wink component."""
    import pywink
    import requests
    from pubnubsubhandler import PubNubSubscriptionHandler

    user_agent = config[DOMAIN].get(CONF_USER_AGENT)

    if user_agent:
        pywink.set_user_agent(user_agent)

    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)
    client_id = config[DOMAIN].get('client_id')

    if access_token:
        pywink.set_bearer_token(access_token)
    elif client_id:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id, client_secret)
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        payload = {'username': email, 'password': password}
        token_response = requests.post(CONF_TOKEN_URL, data=payload)
        token = token_response.text.split(':')[1].split()[0].rstrip('<br')
        pywink.set_bearer_token(token)

    hass.data[DOMAIN] = {}
    hass.data[DOMAIN]['entities'] = []
    hass.data[DOMAIN]['pubnub'] = PubNubSubscriptionHandler(
        pywink.get_subscription_key(), pywink.wink_api_fetch)

    def start_subscription(event):
        """Start the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].subscribe()

    hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription)

    def stop_subscription(event):
        """Stop the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].unsubscribe()

    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription)

    def force_update(call):
        """Force all devices to poll the Wink API."""
        _LOGGER.info("Refreshing Wink states from API")
        for entity in hass.data[DOMAIN]['entities']:
            entity.update_ha_state(True)

    hass.services.register(DOMAIN, 'Refresh state from Wink', force_update)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
コード例 #6
0
def setup(hass, config):
    """Setup the Wink component."""
    import pywink

    user_agent = config[DOMAIN][CONF_USER_AGENT]

    if user_agent:
        pywink.set_user_agent(user_agent)

    from pubnub import Pubnub
    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)

    if access_token:
        pywink.set_bearer_token(access_token)
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id, client_secret)

    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub('N/A',
                                  pywink.get_subscription_key(),
                                  ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        discovery.load_platform(hass, component, DOMAIN, {}, config)
    return True
コード例 #7
0
def setup(hass, config):
    """ Sets up the Wink component. """
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])

    # Load components for the devices in the Wink that we support
    for component_name, func_exists, discovery_type in (
        ('light', pywink.get_bulbs, DISCOVER_LIGHTS),
        ('switch', lambda: pywink.get_switches or pywink.get_sirens or pywink.
         get_powerstrip_outlets, DISCOVER_SWITCHES),
        ('binary_sensor', pywink.get_sensors, DISCOVER_BINARY_SENSORS),
        ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays,
         DISCOVER_SENSORS), ('lock', pywink.get_locks, DISCOVER_LOCKS),
        ('garage_door', pywink.get_garage_doors, DISCOVER_GARAGE_DOORS)):

        if func_exists():
            component = get_component(component_name)

            # Ensure component is loaded
            bootstrap.setup_component(hass, component.DOMAIN, config)

            # Fire discovery event
            hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {
                ATTR_SERVICE: discovery_type,
                ATTR_DISCOVERED: {}
            })

    return True
コード例 #8
0
ファイル: wink.py プロジェクト: Teagan42/home-assistant
def setup(hass, config):
    """Set up the Wink component."""
    import pywink
    import requests
    from pubnubsubhandler import PubNubSubscriptionHandler

    user_agent = config[DOMAIN].get(CONF_USER_AGENT)

    if user_agent:
        pywink.set_user_agent(user_agent)

    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)
    client_id = config[DOMAIN].get('client_id')

    if access_token:
        pywink.set_bearer_token(access_token)
    elif client_id:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id,
                                    client_secret)
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        payload = {'username': email, 'password': password}
        token_response = requests.post(CONF_TOKEN_URL, data=payload)
        token = token_response.text.split(':')[1].split()[0].rstrip('<br')
        pywink.set_bearer_token(token)

    hass.data[DOMAIN] = {}
    hass.data[DOMAIN]['entities'] = []
    hass.data[DOMAIN]['pubnub'] = PubNubSubscriptionHandler(
        pywink.get_subscription_key(),
        pywink.wink_api_fetch)

    def start_subscription(event):
        """Start the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].subscribe()
    hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription)

    def stop_subscription(event):
        """Stop the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].unsubscribe()
    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription)

    def force_update(call):
        """Force all devices to poll the Wink API."""
        _LOGGER.info("Refreshing Wink states from API")
        for entity in hass.data[DOMAIN]['entities']:
            entity.update_ha_state(True)
    hass.services.register(DOMAIN, 'Refresh state from Wink', force_update)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
コード例 #9
0
ファイル: wink.py プロジェクト: xiaogangzzg123/home-assistant
    def _get_wink_token_from_web():
        email = hass.data[DOMAIN]["oath"]["email"]
        password = hass.data[DOMAIN]["oath"]["password"]

        payload = {'username': email, 'password': password}
        token_response = requests.post(CONF_TOKEN_URL, data=payload)
        try:
            token = token_response.text.split(':')[1].split()[0].rstrip('<br')
        except IndexError:
            _LOGGER.error("Error getting token. Please check email/password.")
            return False
        pywink.set_bearer_token(token)
コード例 #10
0
ファイル: wink.py プロジェクト: fripsy/home-assistant
    def _get_wink_token_from_web():
        _email = hass.data[DOMAIN]["oauth"]["email"]
        _password = hass.data[DOMAIN]["oauth"]["password"]

        payload = {'username': _email, 'password': _password}
        token_response = requests.post(CONF_TOKEN_URL, data=payload)
        try:
            token = token_response.text.split(':')[1].split()[0].rstrip('<br')
        except IndexError:
            _LOGGER.error("Error getting token. Please check email/password.")
            return False
        pywink.set_bearer_token(token)
コード例 #11
0
ファイル: wink.py プロジェクト: vkrizan/home-assistant
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Find and return Wink lights. """
    import pywink

    token = config.get(CONF_ACCESS_TOKEN)

    if not pywink.is_token_set() and token is None:
        logging.getLogger(__name__).error(
            "Missing wink access_token - "
            "get one at https://winkbearertoken.appspot.com/")
        return

    elif token is not None:
        pywink.set_bearer_token(token)

    add_devices_callback(WinkLight(light) for light in pywink.get_bulbs())
コード例 #12
0
ファイル: wink.py プロジェクト: naggie/home-assistant
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the Wink platform. """
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token - "
                "get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    add_devices(WinkSensorDevice(sensor) for sensor in pywink.get_sensors())
コード例 #13
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Wink platform."""
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    add_devices(WinkLockDevice(lock) for lock in pywink.get_locks())
コード例 #14
0
ファイル: wink.py プロジェクト: Jocke1970/home-assistant
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Find and return Wink lights. """
    import pywink

    token = config.get(CONF_ACCESS_TOKEN)

    if not pywink.is_token_set() and token is None:
        logging.getLogger(__name__).error(
            "Missing wink access_token - "
            "get one at https://winkbearertoken.appspot.com/")
        return

    elif token is not None:
        pywink.set_bearer_token(token)

    add_devices_callback(
        WinkLight(light) for light in pywink.get_bulbs())
コード例 #15
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Wink cover platform."""
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    add_devices(WinkCoverDevice(shade) for shade in pywink.get_shades())
    add_devices(WinkCoverDevice(door) for door in pywink.get_garage_doors())
コード例 #16
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the Wink platform. """
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    add_devices(WinkSensorDevice(sensor) for sensor in pywink.get_sensors())
    add_devices(WinkEggMinder(eggtray) for eggtray in pywink.get_eggtrays())
コード例 #17
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Wink platform."""
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    for sensor in pywink.get_sensors():
        if sensor.capability() in SENSOR_TYPES:
            add_devices([WinkBinarySensorDevice(sensor)])
コード例 #18
0
ファイル: wink.py プロジェクト: 1lann/home-assistant
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Wink platform."""
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    for sensor in pywink.get_sensors():
        if sensor.capability() in SENSOR_TYPES:
            add_devices([WinkBinarySensorDevice(sensor)])
コード例 #19
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the Wink platform. """
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    add_devices(WinkToggleDevice(switch) for switch in pywink.get_switches())
    add_devices(WinkToggleDevice(switch) for switch in
                pywink.get_powerstrip_outlets())
コード例 #20
0
def setup(hass, config):
    """Setup the Wink component."""
    import pywink

    user_agent = config[DOMAIN][CONF_USER_AGENT]

    if user_agent:
        pywink.set_user_agent(user_agent)

    from pubnub import Pubnub
    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)

    if access_token:
        pywink.set_bearer_token(access_token)
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id,
                                    client_secret)

    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub(
        'N/A', pywink.get_subscription_key(), ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in Wink that we support
    for component_name, func_exists in (
            ('light', pywink.get_bulbs),
            ('switch', lambda: pywink.get_switches or pywink.get_sirens or
             pywink.get_powerstrip_outlets),
            ('binary_sensor', pywink.get_sensors),
            ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays),
            ('lock', pywink.get_locks),
            ('cover', pywink.get_shades),
            ('cover', pywink.get_garage_doors)):

        if func_exists():
            discovery.load_platform(hass, component_name, DOMAIN, {}, config)

    return True
コード例 #21
0
def main():
    infile = open('inputs.txt', 'r')

    # Wasting first 7 lines because that's how I formatted it
    for x in range(0, 7):
        infile.readline()

    # Read in client secrets and the like
    clientId = infile.readline().rstrip('\n')
    clientSecret = infile.readline().rstrip('\n')
    authUrl = infile.readline().rstrip('\n')
    accessTokenUrl = infile.readline().rstrip('\n')
    refreshToken = infile.readline().rstrip('\n')
    # print clientId, clientSecret, authUrl, accessTokenUrl, refreshToken

    accessToken = AcquireAccessToken(clientId, clientSecret, refreshToken)
    # print accessToken

    pywink.set_bearer_token(accessToken)

    DimLights()
    ToggleSwitches()

    return 0
コード例 #22
0
def setup(hass, config):
    """Set up the Wink component."""
    import pywink
    import requests
    from pubnubsubhandler import PubNubSubscriptionHandler

    hass.data[DOMAIN] = {}
    hass.data[DOMAIN]['entities'] = []
    hass.data[DOMAIN]['unique_ids'] = []
    hass.data[DOMAIN]['entities'] = {}

    user_agent = config[DOMAIN].get(CONF_USER_AGENT)

    if user_agent:
        pywink.set_user_agent(user_agent)

    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)
    client_id = config[DOMAIN].get('client_id')

    def _get_wink_token_from_web():
        email = hass.data[DOMAIN]["oath"]["email"]
        password = hass.data[DOMAIN]["oath"]["password"]

        payload = {'username': email, 'password': password}
        token_response = requests.post(CONF_TOKEN_URL, data=payload)
        try:
            token = token_response.text.split(':')[1].split()[0].rstrip('<br')
        except IndexError:
            _LOGGER.error("Error getting token. Please check email/password.")
            return False
        pywink.set_bearer_token(token)

    if access_token:
        pywink.set_bearer_token(access_token)
    elif client_id:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id, client_secret)
        hass.data[DOMAIN]['oath'] = {"email": email,
                                     "password": password,
                                     "client_id": client_id,
                                     "client_secret": client_secret}
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        hass.data[DOMAIN]['oath'] = {"email": email, "password": password}
        _get_wink_token_from_web()

    hass.data[DOMAIN]['pubnub'] = PubNubSubscriptionHandler(
        pywink.get_subscription_key())

    def keep_alive_call(event_time):
        """Call the Wink API endpoints to keep PubNub working."""
        _LOGGER.info("Getting a new Wink token.")
        if hass.data[DOMAIN]["oath"].get("client_id") is not None:
            _email = hass.data[DOMAIN]["oath"]["email"]
            _password = hass.data[DOMAIN]["oath"]["password"]
            _client_id = hass.data[DOMAIN]["oath"]["client_id"]
            _client_secret = hass.data[DOMAIN]["oath"]["client_secret"]
            pywink.set_wink_credentials(_email, _password, _client_id,
                                        _client_secret)
        else:
            _LOGGER.info("Getting a new Wink token.")
            _get_wink_token_from_web()
        time.sleep(1)
        _LOGGER.info("Polling the Wink API to keep PubNub updates flowing.")
        _LOGGER.debug(str(json.dumps(pywink.wink_api_fetch())))
        time.sleep(1)
        _LOGGER.debug(str(json.dumps(pywink.get_user())))

    # Call the Wink API every hour to keep PubNub updates flowing
    if access_token is None:
        track_time_interval(hass, keep_alive_call, timedelta(minutes=120))

    def start_subscription(event):
        """Start the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].subscribe()
    hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription)

    def stop_subscription(event):
        """Stop the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].unsubscribe()
    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription)

    def force_update(call):
        """Force all devices to poll the Wink API."""
        _LOGGER.info("Refreshing Wink states from API")
        for entity_list in hass.data[DOMAIN]['entities'].values():
            # Throttle the calls to Wink API
            for entity in entity_list:
                time.sleep(1)
                entity.schedule_update_ha_state(True)
    hass.services.register(DOMAIN, SERVICE_REFRESH_STATES, force_update)

    def pull_new_devices(call):
        """Pull new devices added to users Wink account since startup."""
        _LOGGER.info("Getting new devices from Wink API")
        for component in WINK_COMPONENTS:
            discovery.load_platform(hass, component, DOMAIN, {}, config)
    hass.services.register(DOMAIN, SERVICE_ADD_NEW_DEVICES, pull_new_devices)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        hass.data[DOMAIN]['entities'][component] = []
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
コード例 #23
0
ファイル: wink_test.py プロジェクト: BryonCLewis/python-wink
import pywink
pywink.set_bearer_token('302fe8af509dc1cc9fb389760b223c07')

"""
for switch in pywink.get_switches():
    if "living room lights" in switch.name():
        switch.set_state(True)

"""
for air in pywink.get_air_conditioners():
    air.set_state(True,"eco","low", 73)

コード例 #24
0
ファイル: wink.py プロジェクト: xiaogangzzg123/home-assistant
def setup(hass, config):
    """Set up the Wink component."""
    import pywink
    import requests
    from pubnubsubhandler import PubNubSubscriptionHandler

    hass.data[DOMAIN] = {}
    hass.data[DOMAIN]['entities'] = []
    hass.data[DOMAIN]['unique_ids'] = []
    hass.data[DOMAIN]['entities'] = {}

    user_agent = config[DOMAIN].get(CONF_USER_AGENT)

    if user_agent:
        pywink.set_user_agent(user_agent)

    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)
    client_id = config[DOMAIN].get('client_id')

    def _get_wink_token_from_web():
        email = hass.data[DOMAIN]["oath"]["email"]
        password = hass.data[DOMAIN]["oath"]["password"]

        payload = {'username': email, 'password': password}
        token_response = requests.post(CONF_TOKEN_URL, data=payload)
        try:
            token = token_response.text.split(':')[1].split()[0].rstrip('<br')
        except IndexError:
            _LOGGER.error("Error getting token. Please check email/password.")
            return False
        pywink.set_bearer_token(token)

    if access_token:
        pywink.set_bearer_token(access_token)
    elif client_id:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id, client_secret)
        hass.data[DOMAIN]['oath'] = {
            "email": email,
            "password": password,
            "client_id": client_id,
            "client_secret": client_secret
        }
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        hass.data[DOMAIN]['oath'] = {"email": email, "password": password}
        _get_wink_token_from_web()

    hass.data[DOMAIN]['pubnub'] = PubNubSubscriptionHandler(
        pywink.get_subscription_key())

    def keep_alive_call(event_time):
        """Call the Wink API endpoints to keep PubNub working."""
        _LOGGER.info("Getting a new Wink token.")
        if hass.data[DOMAIN]["oath"].get("client_id") is not None:
            _email = hass.data[DOMAIN]["oath"]["email"]
            _password = hass.data[DOMAIN]["oath"]["password"]
            _client_id = hass.data[DOMAIN]["oath"]["client_id"]
            _client_secret = hass.data[DOMAIN]["oath"]["client_secret"]
            pywink.set_wink_credentials(_email, _password, _client_id,
                                        _client_secret)
        else:
            _LOGGER.info("Getting a new Wink token.")
            _get_wink_token_from_web()
        time.sleep(1)
        _LOGGER.info("Polling the Wink API to keep PubNub updates flowing.")
        _LOGGER.debug(str(json.dumps(pywink.wink_api_fetch())))
        time.sleep(1)
        _LOGGER.debug(str(json.dumps(pywink.get_user())))

    # Call the Wink API every hour to keep PubNub updates flowing
    if access_token is None:
        track_time_interval(hass, keep_alive_call, timedelta(minutes=120))

    def start_subscription(event):
        """Start the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].subscribe()

    hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription)

    def stop_subscription(event):
        """Stop the pubnub subscription."""
        hass.data[DOMAIN]['pubnub'].unsubscribe()

    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription)

    def force_update(call):
        """Force all devices to poll the Wink API."""
        _LOGGER.info("Refreshing Wink states from API")
        for entity_list in hass.data[DOMAIN]['entities'].values():
            # Throttle the calls to Wink API
            for entity in entity_list:
                time.sleep(1)
                entity.schedule_update_ha_state(True)

    hass.services.register(DOMAIN, SERVICE_REFRESH_STATES, force_update)

    def pull_new_devices(call):
        """Pull new devices added to users Wink account since startup."""
        _LOGGER.info("Getting new devices from Wink API")
        for component in WINK_COMPONENTS:
            discovery.load_platform(hass, component, DOMAIN, {}, config)

    hass.services.register(DOMAIN, SERVICE_ADD_NEW_DEVICES, pull_new_devices)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        hass.data[DOMAIN]['entities'][component] = []
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True