Beispiel #1
0
    def decora(self, switch_name, command, brightness):
        logging.debug('switch:' + switch_name + ' command:' + str(command) +
                      ' brightness: ' + brightness)
        username = Home.private.get('Decora', 'username')
        password = Home.private.get('Decora', 'password')

        session = DecoraWiFiSession()
        session.login(username, password)

        perms = session.user.get_residential_permissions()
        all_residences = []
        for permission in perms:
            if permission.residentialAccountId is not None:
                acct = ResidentialAccount(session,
                                          permission.residentialAccountId)
                for res in acct.get_residences():
                    all_residences.append(res)
            elif permission.residenceId is not None:
                res = Residence(session, permission.residenceId)
                all_residences.append(res)
        for residence in all_residences:
            for switch in residence.get_iot_switches():
                attribs = {}
                if switch.name == switch_name:
                    if brightness is not "None":
                        attribs['brightness'] = brightness
                    if command == 'ON':
                        attribs['power'] = 'ON'
                    else:
                        attribs['power'] = 'OFF'
                    logging.debug(switch.name + ':' + str(attribs))
                switch.update_attributes(attribs)

        Person.logout(session)
Beispiel #2
0
def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Decora WiFi platform."""

    email = config[CONF_USERNAME]
    password = config[CONF_PASSWORD]
    session = DecoraWiFiSession()

    try:
        success = session.login(email, password)

        # If login failed, notify user.
        if success is None:
            msg = "Failed to log into myLeviton Services. Check credentials."
            _LOGGER.error(msg)
            persistent_notification.create(hass,
                                           msg,
                                           title=NOTIFICATION_TITLE,
                                           notification_id=NOTIFICATION_ID)
            return

        # Gather all the available devices...
        perms = session.user.get_residential_permissions()
        all_switches = []
        for permission in perms:
            if permission.residentialAccountId is not None:
                acct = ResidentialAccount(session,
                                          permission.residentialAccountId)
                for residence in acct.get_residences():
                    for switch in residence.get_iot_switches():
                        all_switches.append(switch)
            elif permission.residenceId is not None:
                residence = Residence(session, permission.residenceId)
                for switch in residence.get_iot_switches():
                    all_switches.append(switch)

        add_entities(DecoraWifiLight(sw) for sw in all_switches)
    except ValueError:
        _LOGGER.error("Failed to communicate with myLeviton Service")

    # Listen for the stop event and log out.
    def logout(event):
        """Log out..."""
        try:
            if session is not None:
                Person.logout(session)
        except ValueError:
            _LOGGER.error("Failed to log out of myLeviton Service")

    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, logout)
Beispiel #3
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Decora WiFi platform."""
    # pylint: disable=import-error, no-name-in-module
    from decora_wifi import DecoraWiFiSession
    from decora_wifi.models.person import Person
    from decora_wifi.models.residential_account import ResidentialAccount
    from decora_wifi.models.residence import Residence

    email = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    session = DecoraWiFiSession()

    try:
        success = session.login(email, password)

        # If login failed, notify user.
        if success is None:
            msg = 'Failed to log into myLeviton Services. Check credentials.'
            _LOGGER.error(msg)
            hass.components.persistent_notification.create(
                msg, title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
            return False

        # Gather all the available devices...
        perms = session.user.get_residential_permissions()
        all_switches = []
        for permission in perms:
            if permission.residentialAccountId is not None:
                acct = ResidentialAccount(
                    session, permission.residentialAccountId)
                for residence in acct.get_residences():
                    for switch in residence.get_iot_switches():
                        all_switches.append(switch)
            elif permission.residenceId is not None:
                residence = Residence(session, permission.residenceId)
                for switch in residence.get_iot_switches():
                    all_switches.append(switch)

        add_entities(DecoraWifiLight(sw) for sw in all_switches)
    except ValueError:
        _LOGGER.error('Failed to communicate with myLeviton Service.')

    # Listen for the stop event and log out.
    def logout(event):
        """Log out..."""
        try:
            if session is not None:
                Person.logout(session)
        except ValueError:
            _LOGGER.error('Failed to log out of myLeviton Service.')

    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, logout)
Beispiel #4
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Decora WiFi platform."""
    # pylint: disable=import-error, no-name-in-module
    from decora_wifi import DecoraWiFiSession
    from decora_wifi.models.person import Person
    from decora_wifi.models.residential_account import ResidentialAccount
    from decora_wifi.models.residence import Residence

    email = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    session = DecoraWiFiSession()

    try:
        success = session.login(email, password)

        # If login failed, notify user.
        if success is None:
            msg = 'Failed to log into myLeviton Services. Check credentials.'
            _LOGGER.error(msg)
            hass.components.persistent_notification.create(
                msg, title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
            return False

        # Gather all the available devices...
        perms = session.user.get_residential_permissions()
        all_switches = []
        for permission in perms:
            if permission.residentialAccountId is not None:
                acct = ResidentialAccount(session,
                                          permission.residentialAccountId)
                for residence in acct.get_residences():
                    for switch in residence.get_iot_switches():
                        all_switches.append(switch)
            elif permission.residenceId is not None:
                residence = Residence(session, permission.residenceId)
                for switch in residence.get_iot_switches():
                    all_switches.append(switch)

        add_entities(DecoraWifiLight(sw) for sw in all_switches)
    except ValueError:
        _LOGGER.error('Failed to communicate with myLeviton Service.')

    # Listen for the stop event and log out.
    def logout(event):
        """Log out..."""
        try:
            if session is not None:
                Person.logout(session)
        except ValueError:
            _LOGGER.error('Failed to log out of myLeviton Service.')

    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, logout)
Beispiel #5
0
 def on_websettings_changed(self):
     if not self._is_setup:
         email = self.settings.get("email", "")
         password = self.settings.get("password", "")
         try:
             if email and password:
                 email = self.settings["email"]
                 password = self.settings["password"]
                 self.session = DecoraWiFiSession()
                 self.session.login(email, password)
                 self.perms = self.session.user.get_residential_permissions(
                 )
                 self._is_setup = True
                 LOG.info(
                     'Information Successfully retrieved from https://home.mycroft.ai'
                 )
         except Exception as e:
             LOG.error(e)
Beispiel #6
0
 def _authenticate(self):
     session = DecoraWiFiSession()
     session.login(self.email, self.password)
     self.session = session
if len(sys.argv) < 4:
    print(
        'Usage: ./cli-test.py [email] [pass] [switchID] [ON|OFF] [BRIGHTNESS 0-100]'
    )

decora_email = sys.argv[1]
decora_pass = sys.argv[2]
decora_switch_id = sys.argv[3]
decora_cmd = sys.argv[4]

if len(sys.argv) > 5:
    decora_bright = int(sys.argv[5])
else:
    decora_bright = None

session = DecoraWiFiSession()
session.login(decora_email, decora_pass)

# Gather all the available devices...

perms = session.user.get_residential_permissions()
all_residences = []
for permission in perms:
    if permission.residentialAccountId is not None:
        acct = ResidentialAccount(session, permission.residentialAccountId)
        for res in acct.get_residences():
            all_residences.append(res)
    elif permission.residenceId is not None:
        res = Residence(session, permission.residenceId)
        all_residences.append(res)
all_switches = []
Beispiel #8
0
class DecoraWifiSkill(MycroftSkill):

    # The constructor of the skill, which calls MycroftSkill's constructor
    def __init__(self):
        super(DecoraWifiSkill, self).__init__(name="DecoraWifiSkill")
        self.settings["email"] = ""
        self.settings["password"] = ""
        self.session = ""
        self.perms = []
        self._is_setup = False

    # This method loads the files needed for the skill's functioning, and
    # creates and registers each intent that the skill uses
    def initialize(self):
        self.load_data_files(dirname(__file__))

        # Check and then monitor for credential changes
        self.settings.set_changed_callback(self.on_websettings_changed)
        self.on_websettings_changed()

        decora_light_on_intent = IntentBuilder("DecoraWifiOnIntent").\
            require("DeviceKeyword").require("OnKeyword").\
            optionally("LightKeyword").\
            optionally("SilentKeyword").build()
        self.register_intent(decora_light_on_intent,
                             self.handle_decora_light_on_intent)

        decora_light_off_intent = IntentBuilder("DecoraWifiOffIntent").\
            require("DeviceKeyword").require("OffKeyword").\
            optionally("LightKeyword").\
            optionally("SilentKeyword").build()
        self.register_intent(decora_light_off_intent,
                             self.handle_decora_light_off_intent)

        decora_light_dim_intent = IntentBuilder("DecoraWifiDimIntent").\
            require("DimKeyword").require("DeviceKeyword").\
            optionally("LightKeyword").\
            optionally("SilentKeyword").build()
        self.register_intent(decora_light_dim_intent,
                             self.handle_decora_light_dim_intent)

        decora_light_set_intent = IntentBuilder("DecoraWifiSetIntent").\
            require("SetKeyword").require("DeviceKeyword").\
            optionally("LightKeyword").\
            optionally("SilentKeyword").build()
        self.register_intent(decora_light_set_intent,
                             self.handle_decora_light_set_intent)

    def on_websettings_changed(self):
        if not self._is_setup:
            email = self.settings.get("email", "")
            password = self.settings.get("password", "")
            try:
                if email and password:
                    email = self.settings["email"]
                    password = self.settings["password"]
                    self.session = DecoraWiFiSession()
                    self.session.login(email, password)
                    self.perms = self.session.user.get_residential_permissions(
                    )
                    self._is_setup = True
                    LOG.info(
                        'Information Successfully retrieved from https://home.mycroft.ai'
                    )
            except Exception as e:
                LOG.error(e)

    def get_switch_id(self):
        for permission in self.perms:
            acct = ResidentialAccount(self.session,
                                      permission.residentialAccountId)
            residences = acct.get_residences()
            LOG.info('Residences found :' + str(residences))
            for residence in residences:
                switches = residence.get_iot_switches()
                LOG.info('Switches found :' + str(switches))
                for switch in switches:
                    switch_id = switch
                    break
                break
            break
        return switch_id

    def delay_regex(self, req_string):  # extract the delay time
        LOG.info('processing time delay regex : ' + str(req_string))
        pri_regex = re.search(
            r'((?P<Duration>\d+) (?P<Interval>seconds|second|minutes|minute|hours|hour))',
            req_string)
        if pri_regex:
            duration_result = pri_regex.group('Duration')
            interval_result = pri_regex.group('Interval')
            if (interval_result == 'seconds') or (interval_result == 'second'):
                return_value = int(duration_result)
            if (interval_result == 'minutes') or (interval_result == 'minute'):
                return_value = int(duration_result) * 60
            if (interval_result == 'hours') or (interval_result == 'hour'):
                return_value = int(duration_result) * 3600
            LOG.info('regex returned: ' + str(return_value))
            return return_value

    def handle_decora_light_on_intent(self, message):
        silent_kw = message.data.get("SilentKeyword")
        delay_kw = self.delay_regex(message.utterance_remainder())
        if delay_kw:
            LOG.info('delay on:', delay_kw)
            sleep(int(delay_kw))
        my_switch = self.get_switch_id()
        my_switch.update_attributes({'power': 'ON', 'brightness': '100'})
        if silent_kw:
            LOG.info('Light Turned On')
        else:
            self.speak_dialog("light.on")

    def handle_decora_light_off_intent(self, message):
        silent_kw = message.data.get("SilentKeyword")
        delay_kw = self.delay_regex(message.utterance_remainder())
        if delay_kw:
            LOG.info('delay off:', delay_kw)
            sleep(int(delay_kw))
        my_switch = self.get_switch_id()
        my_switch.update_attributes({'power': 'OFF'})
        if silent_kw:
            LOG.info('Light Turned Off')
        else:
            self.speak_dialog("light.off")

    def handle_decora_light_dim_intent(self, message):
        silent_kw = message.data.get("SilentKeyword")
        my_switch = self.get_switch_id()
        my_switch.update_attributes({'brightness': '5'})
        if silent_kw:
            LOG.info('Light Dimmed')
        else:
            self.speak_dialog("light.dim")

    def handle_decora_light_set_intent(self, message):
        silent_kw = message.data.get("SilentKeyword")
        str_remainder = str(message.utterance_remainder())
        dim_level = re.findall('\d+', str_remainder)
        if dim_level:
            my_switch = self.get_switch_id()
            my_switch.update_attributes({'brightness': dim_level[0]})
            if silent_kw:
                LOG.info('Light Set To: ' + str(dim_level[0]) + '%')
            else:
                self.speak_dialog(
                    "light.set",
                    data={"result": str(dim_level[0]) + ", percent"})

    # The "stop" method defines what Mycroft does when told to stop during
    # the skill's execution. In this case, since the skill's functionality
    # is extremely simple, the method just contains the keyword "pass", which
    # does nothing.
    def stop(self):
        pass