Ejemplo n.º 1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up config entry."""
    if CONF_TOKEN not in entry.data:
        raise ConfigEntryAuthFailed

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    neato_session = api.ConfigEntryAuth(hass, entry, session)
    hass.data[NEATO_DOMAIN][entry.entry_id] = neato_session
    hub = NeatoHub(hass, Account(neato_session))

    try:
        await hass.async_add_executor_job(hub.update_robots)
    except NeatoException as ex:
        _LOGGER.debug("Failed to connect to Neato API")
        raise ConfigEntryNotReady from ex

    hass.data[NEATO_LOGIN] = hub

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Ejemplo n.º 2
0
def login(email, password, vendor):
    if (vendor == "Neato"):
        v = Neato()
    elif (vendor == "Vorwerk"):
        v = Vorwerk()

    try:
        account = Account(email, password, v)
        if (account is None):
            # failed login
            pyotherside.send("loginrequired")

        r_json = {
            "vendor": vendor,
            "token": account.access_token,
            "robots": []
        }
        for robot in account.robots:
            r_json["robots"].append({
                "name": robot.name,
                "serial": robot.serial,
                "secret": robot.secret
            })
        with open(CACHE_FILE, "w") as write_file:
            json.dump(r_json, write_file)
        init()
    except requests.exceptions.HTTPError as e:
        # Whoops it wasn't a 200
        pyotherside.send("loginrequired")
Ejemplo n.º 3
0
def init():
    if not os.path.exists(CACHE_DIR):
        pyotherside.send("loginrequired")
        os.makedirs(CACHE_DIR)
        return

    if not os.path.exists(CACHE_FILE):
        pyotherside.send("loginrequired")
        return

    with open(CACHE_FILE, "r") as read_file:
        global account
        global robots
        global vendor
        robots = json.load(read_file)
        if (robots["vendor"] == "Neato"):
            vendor = Neato()
        elif (robots["vendor"] == "Vorwerk"):
            vendor = Vorwerk()

        account = Account(robots["token"], None, vendor)
        for r in robots["robots"]:
            pyotherside.send("rfound", r["name"])

        pyotherside.send("loginsuccessful")
Ejemplo n.º 4
0
    def onStart(self):

        # List all robots associated with account
        botvacSession = PasswordSession(email=Parameters['Username'],
                                        password=Parameters['Password'],
                                        vendor=Neato())
        botvacAccount = Account(botvacSession).robots
        botvacDevice = next((botvac for botvac in botvacAccount
                             if botvac.name == Parameters["Mode3"]), None)
        if botvacDevice is None:
            Domoticz.Log("No robot found")
        else:
            self.DEVICE_NAME = botvacDevice.name
            self.DEVICE_SERIAL = botvacDevice.serial
            self.API_SECRET = botvacDevice.secret

        if Parameters["Mode4"] == "Debug":
            Domoticz.Debugging(1)
            DumpConfigToLog()

        #if (self.iconName not in Images): Domoticz.Image('icons.zip').Create()
        #iconID = Images[self.iconName].ID

        # Check if images are in database
        if self.iconName not in Images:
            Domoticz.Image("icons.zip").Create()
        try:
            iconID = Images[self.iconName].ID
        except:
            iconID = 0
        Domoticz.Debug("Image created. ID: " + str(iconID))

        if self.statusUnit not in Devices:
            Domoticz.Device(Name='Status',
                            Unit=self.statusUnit,
                            Type=17,
                            Switchtype=17,
                            Image=iconID,
                            Used=1).Create()

        if self.controlUnit not in Devices:
            Domoticz.Device(Name='Control',
                            Unit=self.controlUnit,
                            TypeName='Selector Switch',
                            Image=iconID,
                            Options=self.controlOptions,
                            Used=1).Create()

        if self.scheduleUnit not in Devices:
            Domoticz.Device(Name='Schedule',
                            Unit=self.scheduleUnit,
                            TypeName='Switch',
                            Image=iconID,
                            Used=1).Create()

        self.botvacGetValues()
        Domoticz.Heartbeat(self.heartbeatsInterval)
        Domoticz.Debug("onStart called")
Ejemplo n.º 5
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Neato platform."""
    from pybotvac import Account

    try:
        auth = Account(config[CONF_USERNAME], config[CONF_PASSWORD])
    except HTTPError:
        _LOGGER.error("Unable to connect to Neato API")
        return False

    dev = []
    for robot in auth.robots:
        for type_name in SWITCH_TYPES:
            dev.append(NeatoConnectedSwitch(robot, type_name))
    add_devices(dev)
Ejemplo n.º 6
0
    def try_login(username, password, vendor):
        """Try logging in to device and return any errors."""
        this_vendor = None
        if vendor == "vorwerk":
            this_vendor = Vorwerk()
        else:  # Neato
            this_vendor = Neato()

        try:
            Account(username, password, this_vendor)
        except NeatoLoginException:
            return "invalid_credentials"
        except NeatoRobotException:
            return "unexpected_error"

        return None
Ejemplo n.º 7
0
def init():
    if not os.path.exists(CACHE_DIR):
        pyotherside.send("loginrequired")
        os.makedirs(CACHE_DIR)
        return

    if not os.path.exists(CACHE_FILE):
        pyotherside.send("loginrequired")
        return

    with open(CACHE_FILE, "r") as read_file:
        global account
        global robots
        robots = json.load(read_file)
        account = Account(robots["token"])
        for r in robots["robots"]:
            pyotherside.send("rfound", r["name"])

        pyotherside.send("loginsuccessful")
Ejemplo n.º 8
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up config entry."""
    if CONF_TOKEN not in entry.data:
        raise ConfigEntryAuthFailed

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    try:
        await session.async_ensure_token_valid()
    except aiohttp.ClientResponseError as ex:
        _LOGGER.debug("API error: %s (%s)", ex.code, ex.message)
        if ex.code in (401, 403):
            raise ConfigEntryAuthFailed(
                "Token not valid, trigger renewal") from ex
        raise ConfigEntryNotReady from ex

    neato_session = api.ConfigEntryAuth(hass, entry, implementation)
    hass.data[NEATO_DOMAIN][entry.entry_id] = neato_session
    hub = NeatoHub(hass, Account(neato_session))

    await hub.async_update_entry_unique_id(entry)

    try:
        await hass.async_add_executor_job(hub.update_robots)
    except NeatoException as ex:
        _LOGGER.debug("Failed to connect to Neato API")
        raise ConfigEntryNotReady from ex

    hass.data[NEATO_LOGIN] = hub

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Ejemplo n.º 9
0
async def async_setup_entry(hass: HomeAssistantType,
                            entry: ConfigEntry) -> bool:
    """Set up config entry."""
    if CONF_TOKEN not in entry.data:
        # Init reauth flow
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                NEATO_DOMAIN,
                context={CONF_SOURCE: SOURCE_REAUTH},
            ))
        return False

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    neato_session = api.ConfigEntryAuth(hass, entry, session)
    hass.data[NEATO_DOMAIN][entry.entry_id] = neato_session
    hub = NeatoHub(hass, Account(neato_session))

    try:
        await hass.async_add_executor_job(hub.update_robots)
    except NeatoException as ex:
        _LOGGER.debug("Failed to connect to Neato API")
        raise ConfigEntryNotReady from ex

    hass.data[NEATO_LOGIN] = hub

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Ejemplo n.º 10
0
 def updateAccount(self):
     self.connected = False
     email = self.pluginPrefs.get('email', '')
     password = self.pluginPrefs.get('password', '')
     if email and password:
         try:
             self.account = Account(email, password)
             robots = self.account.robots
             self.connected = True
             self.logger.info(u'Neato account updated')
             if len(robots) > 0:
                 self.logger.info(u'Robots found:')
                 for robot in self.account.robots:
                     self.logger.info(u'     {} ({})'.format(
                         robot.name, robot.serial))
             else:
                 self.logger.error(u'No robots found')
         except:
             self.logger.error(
                 u'Error accessing Neato account - check plugin config and internet connection'
             )
     else:
         # plugin is not configured
         self.logger.error(u'No account credentials - check plugin config')
def setupThing(info):
    # Setup for the account
    if info.thing.thingClassId == accountThingClassId:
        logger.log("SetupThing for account:", info.thing.name)

        pluginStorage().beginGroup(info.thing.id)
        token = json.loads(pluginStorage().value("token"))
        logger.log("setup", token)
        pluginStorage().endGroup()

        try:
            oAuthSession = OAuthSession(token=token)
            # Login went well, finish the setup
            info.finish(nymea.ThingErrorNoError)
        except Exception as e:
            # Login error
            logger.warn("Error setting up neato account:", str(e))
            info.finish(nymea.ThingErrorAuthenticationFailure, str(e))
            return

        # Mark the account as logged-in and connected
        info.thing.setStateValue(accountLoggedInStateTypeId, True)
        info.thing.setStateValue(accountConnectedStateTypeId, True)

        # Create an account session on the session to get info about the login
        account = Account(oAuthSession)
        accountsMap[info.thing] = account

        # List all robots associated with account
        logger.log("account created. Robots:", account.robots)

        thingDescriptors = []
        for robot in account.robots:
            logger.log("Found new robot:", robot.serial)
            # Check if this robot is already added in nymea
            found = False
            for thing in myThings():
                logger.log("Comparing to existing robot:", thing.name)
                if thing.thingClassId == robotThingClassId and thing.paramValue(
                        robotThingSerialParamTypeId) == robot.serial:
                    logger.log("Already have this robot in the system")
                    # Yep, already here... skip it
                    found = True
                    break
            if found:
                continue

            logger.log("Adding new robot to the system with parent",
                       info.thing.id)
            thingDescriptor = nymea.ThingDescriptor(robotThingClassId,
                                                    robot.name,
                                                    parentId=info.thing.id)
            thingDescriptor.params = [
                nymea.Param(robotThingSerialParamTypeId, robot.serial),
                nymea.Param(robotThingSecretParamTypeId, robot.secret)
            ]
            thingDescriptors.append(thingDescriptor)

        # And let nymea know about all the users robots
        autoThingsAppeared(thingDescriptors)

        # If no poll timer is set up yet, start it now
        logger.log("Creating polltimer")
        global pollTimer
        if pollTimer is None:
            pollTimer = threading.Timer(5, pollService)
            pollTimer.start()

        return

    # Setup for the robots
    if info.thing.thingClassId == robotThingClassId:
        logger.log("SetupThing for robot:", info.thing.name)

        serial = info.thing.paramValue(robotThingSerialParamTypeId)
        secret = info.thing.paramValue(robotThingSecretParamTypeId)
        try:
            robot = Robot(serial, secret, info.thing.name)
            thingsAndRobots[info.thing] = robot
            refreshRobot(info.thing)
        except Exception as e:
            logger.warn("Error setting up robot:", e)
            info.finish(nymea.ThingErrorHardwareFailure, str(e))
            return

        info.thing.setStateValue(robotConnectedStateTypeId, True)
        # set up polling for robot status
        info.finish(nymea.ThingErrorNoError)
        return
def setupThing(info):
    # Setup for the account
    if info.thing.thingClassId == accountThingClassId:
        pluginStorage().beginGroup(info.thing.id)
        token = json.loads(pluginStorage().value("token"))
        logger.log("setup", token)
        pluginStorage().endGroup()

        try:
            oAuthSession = OAuthSession(token=token)
            # Login went well, finish the setup
            info.finish(nymea.ThingErrorNoError)
        except:
            # Login error
            info.finish(nymea.ThingErrorAuthenticationFailure, "Login error")
            return

        # Mark the account as logged-in and connected
        info.thing.setStateValue(accountLoggedInStateTypeId, True)
        info.thing.setStateValue(accountConnectedStateTypeId, True)

        # Create an account session on the session to get info about the login
        account = Account(oAuthSession)

        # List all robots associated with account
        logger.log("account created. Robots:", account.robots)

        logger.log("Persistent maps: ", account.persistent_maps)
        mapDict = account.persistent_maps
        mapKeys = mapDict.keys()
        logger.log("Keys: ", mapKeys)
        mapValues = mapDict.values()
        logger.log("Values: ", mapValues)

        thingDescriptors = []
        for robot in account.robots:
            logger.log(robot)
            # Check if this robot is already added in nymea
            found = False
            for thing in myThings():
                if thing.paramValue(
                        robotThingSerialParamTypeId) == robot.serial:
                    # Yep, already here... skip it
                    found = True
                    continue
            if found:
                continue

            thingDescriptor = nymea.ThingDescriptor(robotThingClassId,
                                                    robot.name)
            logger.log("MapID for Serial: ", robot.serial,
                       mapDict[robot.serial])
            mapInfo = mapDict[robot.serial]
            logger.log("Type mapInfo: ", type(mapInfo))
            logger.log("Contents mapInfo: ", mapInfo)
            mapInfo2 = mapInfo[0]
            logger.log("MapInfo2 type: ", type(mapInfo2),
                       " MapInfo2 contents: ", mapInfo2)
            mapId = mapInfo2['id']
            logger.log("MapId type: ", type(mapId), " MapId contents: ", mapId)
            mapName = mapInfo2['name']
            logger.log("MapName type: ", type(mapName), " MapName contents: ",
                       mapName)
            mapIDshort = mapId
            thingDescriptor.params = [
                nymea.Param(robotThingSerialParamTypeId, robot.serial),
                nymea.Param(robotThingSecretParamTypeId, robot.secret),
                nymea.Param(robotThingMapIdParamTypeId, mapIDshort)
            ]
            thingDescriptors.append(thingDescriptor)

        # And let nymea know about all the users robots
        autoThingsAppeared(thingDescriptors)
        # return

        # If no poll timer is set up yet, start it now
        logger.log("Creating polltimer")
        global pollTimer
        pollTimer = threading.Timer(5, pollService)
        pollTimer.start()
        return

    # Setup for the robots
    if info.thing.thingClassId == robotThingClassId:

        serial = info.thing.paramValue(robotThingSerialParamTypeId)
        secret = info.thing.paramValue(robotThingSecretParamTypeId)
        robot = Robot(serial, secret, info.thing.name)
        thingsAndRobots[info.thing] = robot
        logger.log(robot.get_robot_state())
        # set up polling for robot status
        info.finish(nymea.ThingErrorNoError)
        return
Ejemplo n.º 13
0
# account = Account(session)

##########################
# Authenticate via OAuth2
##########################
session = OAuthSession(
    client_id=client_id,
    client_secret=client_secret,
    redirect_uri=redirect_uri,
    vendor=vendor,
)
authorization_url = session.get_authorization_url()
print("Visit: " + authorization_url)
authorization_response = input("Enter the full callback URL: ")
token = session.fetch_token(authorization_response)
account = Account(session)

##########################
# Authenticate via One Time Password
##########################
# session = PasswordlessSession(client_id=client_id, vendor=vendor)
# session.send_email_otp(email)
# code = input("Enter the code: ")
# session.fetch_token_passwordless(email, code)
# account = Account(session)

print("Robots:")
for robot in account.robots:
    print(robot)
    print()
Ejemplo n.º 14
0
try:
    input = raw_input
except NameError:
    pass

login = str(input('Your neato account login/email: '))
passwd = str(input('Your neato account password: '******'---------------------------------------------------------------------------------------------------------'
)
# List all robots associated with account
for robot in account.robots:
    print('Robot: {}'.format(robot.name))
print(
    '---------------------------------------------------------------------------------------------------------'
)

myRobot = str(
    input('Please type the name of the robot you want to configure (None): ')
    or 'None')
if myRobot != 'None':
Ejemplo n.º 15
0
import sys

from pybotvac import Account

if sys.version_info[0] < 3:
    input = raw_input

email = input('Enter email\n')
password = input('Enter password\n')

account = Account(email, password)

print("Robots:")
for robot in account.robots:
    print(robot)
    print()

    print("State:\n", robot.state)
    print()

    print("Schedule enabled:", robot.schedule_enabled)

    print("Disabling schedule")
    robot.schedule_enabled = False

    print("Schedule enabled:", robot.schedule_enabled)

    print("Enabling schedule")
    robot.schedule_enabled = True

    print("Schedule enabled:", robot.schedule_enabled)
Ejemplo n.º 16
0
import sys

from pybotvac import Account, Vorwerk

if sys.version_info[0] < 3:
    input = raw_input

email = input('Enter email\n')
password = input('Enter password\n')

vendor = Vorwerk()

account = Account(email, password, vendor)

print("Robots:")
for robot in account.robots:
    print(robot)
    print()

    print("State:\n", robot.state)
    print()

    print("Schedule enabled:", robot.schedule_enabled)

    print("Disabling schedule")
    robot.schedule_enabled = False

    print("Schedule enabled:", robot.schedule_enabled)

    print("Enabling schedule")
    robot.schedule_enabled = True