Example #1
0
def discoverThings(info):
    logger.log("Discovery started for", info.thingClassId,
               "with result count:", info.params[0].value)
    time.sleep(10)  # Some delay for giving a feeling of a discovery
    # Add 2 new discovery results
    for i in range(0, info.params[0].value):
        info.addDescriptor(
            nymea.ThingDescriptor(pyMockDiscoveryPairingThingClassId,
                                  "Python mock thing %i" % i))
    # Also add existing ones again so reconfiguration is possible
    for thing in myThings():
        if thing.thingClassId == pyMockDiscoveryPairingThingClassId:
            info.addDescriptor(
                nymea.ThingDescriptor(pyMockDiscoveryPairingThingClassId,
                                      thing.name,
                                      thingId=thing.id))

    info.finish(nymea.ThingErrorNoError)
def discoverThings(info):
    request = Request("http://ip-api.com/json")
    data = simplejson.load(urlopen(request))
    descriptor = nymea.ThingDescriptor(
        sunPositionThingClassId, "%s - %s" % (data["city"], data["country"]),
        "%s - %s" % (data["lat"], data["lon"]))
    descriptor.params = [
        nymea.Param(sunPositionThingLatitudeParamTypeId, data["lat"]),
        nymea.Param(sunPositionThingLongitudeParamTypeId, data["lon"])
    ]
    info.addDescriptor(descriptor)
    info.finish(nymea.ThingErrorNoError)
Example #3
0
def configValueChanged(paramTypeId, value):
    logger.log("Plugin config value changed:", paramTypeId, value)
    if paramTypeId == pyMockPluginAutoThingCountParamTypeId:
        logger.log("Auto Thing Count plugin config changed:", value,
                   "Currently there are:", len(autoThings()), "auto things")
        things = autoThings()
        for i in range(len(things), value):
            logger.log("Creating new auto thing")
            descriptor = nymea.ThingDescriptor(pyMockAutoThingClassId,
                                               "Python Mock auto thing")
            descriptor.params = [
                nymea.Param(pyMockAutoThingParam1ParamTypeId, True)
            ]
            autoThingsAppeared([descriptor])

        for i in range(value, len(things)):
            logger.log("Removing auto thing")
            autoThingDisappeared(things[i].id)
Example #4
0
def startMonitoringAutoThings():
    logger.log(
        "Start monitoring auto things. Have %i auto devices. Need %i." % (len(
            autoThings()), configValue(pyMockPluginAutoThingCountParamTypeId)))
    things = autoThings()
    for i in range(len(things),
                   configValue(pyMockPluginAutoThingCountParamTypeId)):
        logger.log("Creating new auto thing")
        descriptor = nymea.ThingDescriptor(pyMockAutoThingClassId,
                                           "Python Mock auto thing")
        descriptor.params = [
            nymea.Param(pyMockAutoThingParam1ParamTypeId, True)
        ]
        autoThingsAppeared([descriptor])
    for i in range(configValue(pyMockPluginAutoThingCountParamTypeId),
                   len(things)):
        logger.log("Removing auto thing")
        autoThingDisappeared(things[i].id)

    logger.log("Done start monitoring auto things")
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
def setupThing(info):
    # Setup for the account
    if info.thing.thingClassId == accountThingClassId:
        logger.log("SetupThing for account:", info.thing.name)

        region = regions[info.thing.paramValue(accountThingRegionParamTypeId)]
        pluginStorage().beginGroup(info.thing.id)
        username = pluginStorage().value("username")
        password = pluginStorage().value("password")
        pluginStorage().endGroup()

        try:
            account = ConnectedDriveAccount(username, password, region)
            account.update_vehicle_states()

            accountsMap[info.thing.id] = account
        except Exception as e:
            # Login error
            logger.warn(f"Error setting up BMW 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)

        # Login went well, finish the setup
        info.finish(nymea.ThingErrorNoError)

        logger.log(
            f"Found {len(account.vehicles)} vehicles: {', '.join([v.name for v in account.vehicles])}"
        )

        thingDescriptors = []
        for vehicle in account.vehicles:
            if any(thing.thingClassId == vehicleThingClassId and
                   thing.paramValue(vehicleThingVinParamTypeId) == vehicle.vin
                   for thing in myThings()):
                continue

            if not vehicle.has_hv_battery:
                logger.log(
                    f"Ignoring combustion vehicle {vehicle.name} ({vehicle.vin[-7:]})"
                )
                continue

            logger.log(
                f"Adding new vehicle {vehicle.name} ({vehicle.vin[-7:]}) to the system with parent {info.thing.id}"
            )
            thingDescriptor = nymea.ThingDescriptor(
                vehicleThingClassId,
                "BMW {} ({})".format(vehicle.name, vehicle.vin[-7:]),
                parentId=info.thing.id,
            )
            thingDescriptor.params = [
                nymea.Param(vehicleThingVinParamTypeId, vehicle.vin)
            ]
            thingDescriptors.append(thingDescriptor)

        autoThingsAppeared(thingDescriptors)

        # If no poll timer is set up yet, start it now
        logger.log("Creating polltimer @ setupThing")
        global pollTimer
        if pollTimer is None:
            pollTimer = nymea.PluginTimer(60 * 5, pollService)
            logger.log("timer interval @ setupThing", pollTimer.interval)

    # Setup for the vehicles
    if info.thing.thingClassId == vehicleThingClassId:
        info.finish(nymea.ThingErrorNoError)