Пример #1
0
def _mock_tado_climate_zone_from_fixture(filename):
    with patch("PyTado.interface.Tado._loginV2"), patch(
            "PyTado.interface.Tado.getMe"), patch(
                "PyTado.interface.Tado.getState",
                return_value=json.loads(load_fixture(filename)),
            ):
        tado = Tado("*****@*****.**", "mypassword")
        return tado.getZoneState(1)
Пример #2
0
 def setup(self):
     """Connect to Tado and fetch the zones."""
     self.tado = Tado(self._username, self._password)
     self.tado.setDebugging(True)
     # Load zones and devices
     self.zones = self.tado.getZones()
     self.devices = self.tado.getMe()["homes"]
     self.device_id = self.devices[0]["id"]
Пример #3
0
    def setup(self):
        """Connect to Tado and fetch the zones."""
        try:
            self.tado = Tado(self._username, self._password)
        except (RuntimeError, urllib.error.HTTPError) as exc:
            _LOGGER.error("Unable to connect: %s", exc)
            return False

        self.tado.setDebugging(True)

        # Load zones and devices
        self.zones = self.tado.getZones()
        self.devices = self.tado.getMe()["homes"]

        return True
Пример #4
0
def login():

    global t

    try:
        t = Tado(username, password)

        if (lastMessage.find("Connection Error") != -1):
            printm(
                "Connection established, everything looks good now, continuing..\n"
            )

    except KeyboardInterrupt:
        printm("Interrupted by user.")
        sys.exit(0)

    except Exception as e:
        if (str(e).find("access_token") != -1):
            printm("Login error, check the username / password !")
            sys.exit(0)
        else:
            printm(
                str(e) + "\nConnection Error, retrying in " +
                str(errorRetringInterval) + " sec..")
            time.sleep(errorRetringInterval)
            login()
Пример #5
0
class TadoHelper:
    def __init__(self, account, pwd):
        self.my_tado = Tado(account, pwd)

    def checkWindowState(self):
        zones = self.my_tado.getZones()

        for index, zone in enumerate(zones):
            if self.windowOpen(zone['id']):
                _LOG_.info('window open')
                self.my_tado.setOpenWindow(zone['id'])
            else:
                _LOG_.debug('window closed')

    def windowOpen(self, zone_id):
        window_open = self.my_tado.getOpenWindowDetected(zone_id)
        return window_open['openWindowDetected']
Пример #6
0
def setup(hass, config):
    """Set up of the Tado component."""
    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]

    try:
        tado = Tado(username, password)
        tado.setDebugging(True)
    except (RuntimeError, urllib.error.HTTPError):
        _LOGGER.error("Unable to connect to mytado with username and password")
        return False

    hass.data[DATA_TADO] = TadoDataStore(tado)

    for component in TADO_COMPONENTS:
        load_platform(hass, component, DOMAIN, {}, config)

    return True
Пример #7
0
def setup(hass, config):
    """Set up of the Tado component."""
    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]

    from PyTado.interface import Tado

    try:
        tado = Tado(username, password)
        tado.setDebugging(True)
    except (RuntimeError, urllib.error.HTTPError):
        _LOGGER.error("Unable to connect to mytado with username and password")
        return False

    hass.data[DATA_TADO] = TadoDataStore(tado)

    for component in TADO_COMPONENTS:
        load_platform(hass, component, DOMAIN, {}, config)

    return True
Пример #8
0
def setup(hass, config):
    """Your controller/hub specific code."""
    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]

    from PyTado.interface import Tado

    try:
        tado = Tado(username, password)
    except (RuntimeError, urllib.error.HTTPError):
        _LOGGER.error("Unable to connect to mytado with username and password")
        return False

    hass.data[DATA_TADO] = TadoDataStore(tado)

    for component in TADO_COMPONENTS:
        load_platform(hass, component, DOMAIN, {}, config)

    return True
Пример #9
0
import warnings

bindir = os.path.dirname(os.path.realpath(__file__))
root = os.path.dirname(bindir)
libdir = os.path.join(root, 'lib')
sys.path.append(libdir)

from PyTado.interface import Tado
import private

mysql = pymysql.connect(host=os.getenv('MYSQL_HOST', private.mysql_host),
                        user=os.getenv('MYSQL_USER', private.mysql_user),
                        password=os.getenv('MYSQL_PASSWORD', private.mysql_password),
                        db=os.getenv('MYSQL_DATABASE', private.mysql_database))

api = Tado(private.username, private.password)

weather = api.getWeather()
outsideTemperature = weather["outsideTemperature"]["celsius"]

zones = {zone["name"]: zone["id"] for zone in api.getZones()}

for name in private.zones:
    zone = zones[name]
    state = api.getState(zone)

    # create new table
    with warnings.catch_warnings(), mysql.cursor() as cursor:
        # temperatures are < 100 with up to two digits past the comma --> DECIMAL(4,2)
        # percentages are <= 100 with only one digit past the comma --> DECIMAL(4,1)
        sql = """
Пример #10
0
class TadoConnector:
    """An object to store the Tado data."""

    def __init__(self, hass, username, password):
        """Initialize Tado Connector."""
        self.hass = hass
        self._username = username
        self._password = password

        self.tado = None
        self.zones = None
        self.devices = None
        self.data = {
            "zone": {},
            "device": {},
        }

    def setup(self):
        """Connect to Tado and fetch the zones."""
        try:
            self.tado = Tado(self._username, self._password)
        except (RuntimeError, urllib.error.HTTPError) as exc:
            _LOGGER.error("Unable to connect: %s", exc)
            return False

        self.tado.setDebugging(True)

        # Load zones and devices
        self.zones = self.tado.getZones()
        self.devices = self.tado.getMe()["homes"]

        return True

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Update the registered zones."""
        for zone in self.zones:
            self.update_sensor("zone", zone["id"])
        for device in self.devices:
            self.update_sensor("device", device["id"])

    def update_sensor(self, sensor_type, sensor):
        """Update the internal data from Tado."""
        _LOGGER.debug("Updating %s %s", sensor_type, sensor)
        try:
            if sensor_type == "zone":
                data = self.tado.getState(sensor)
            elif sensor_type == "device":
                data = self.tado.getDevices()[0]
            else:
                _LOGGER.debug("Unknown sensor: %s", sensor_type)
                return
        except RuntimeError:
            _LOGGER.error(
                "Unable to connect to Tado while updating %s %s", sensor_type, sensor,
            )
            return

        self.data[sensor_type][sensor] = data

        _LOGGER.debug("Dispatching update to %s %s: %s", sensor_type, sensor, data)
        dispatcher_send(
            self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format(sensor_type, sensor)
        )

    def get_capabilities(self, zone_id):
        """Return the capabilities of the devices."""
        return self.tado.getCapabilities(zone_id)

    def reset_zone_overlay(self, zone_id):
        """Reset the zone back to the default operation."""
        self.tado.resetZoneOverlay(zone_id)
        self.update_sensor("zone", zone_id)

    def set_zone_overlay(
        self,
        zone_id,
        overlay_mode,
        temperature=None,
        duration=None,
        device_type="HEATING",
        mode=None,
    ):
        """Set a zone overlay."""
        _LOGGER.debug(
            "Set overlay for zone %s: mode=%s, temp=%s, duration=%s, type=%s, mode=%s",
            zone_id,
            overlay_mode,
            temperature,
            duration,
            device_type,
            mode,
        )
        try:
            self.tado.setZoneOverlay(
                zone_id, overlay_mode, temperature, duration, device_type, "ON", mode
            )
        except urllib.error.HTTPError as exc:
            _LOGGER.error("Could not set zone overlay: %s", exc.read())

        self.update_sensor("zone", zone_id)

    def set_zone_off(self, zone_id, overlay_mode, device_type="HEATING"):
        """Set a zone to off."""
        try:
            self.tado.setZoneOverlay(
                zone_id, overlay_mode, None, None, device_type, "OFF"
            )
        except urllib.error.HTTPError as exc:
            _LOGGER.error("Could not set zone overlay: %s", exc.read())

        self.update_sensor("zone", zone_id)
class TadoWrapper:
    CONNECTION_RETRY_INTERVAL = 60

    def __init__(self):
        self.__t = None
        self.__reconnect()

    def __connect(self):
        username, password = c.get_credentials()
        self.__t = Tado(username, password)

    def __reconnect(self):
        connected = False
        while not connected:
            LoggingHelper.log("Trying to connect to Tado... ")

            try:
                self.__connect()
                connected = True
                LoggingHelper.log("Connection to Tado established.")
            except r_exc.RequestException as e:
                LoggingHelper.log(
                    "Connection to Tado failed. Trying again in {} seconds.".
                    format(TadoWrapper.CONNECTION_RETRY_INTERVAL))
                LoggingHelper.log(e)
                time.sleep(TadoWrapper.CONNECTION_RETRY_INTERVAL)

    def get_zones(self):
        data = self.__t.getZones()
        return [{"id": d["id"], "name": d["name"]} for d in data]

    def get_devices(self):
        data = self.__t.getMobileDevices()
        return [{
            "name": d["name"],
            "id": d["id"],
            "geo_tracking": d["settings"]["geoTrackingEnabled"]
        } for d in data]

    def set_zone(self, zone, temperature):
        success = False
        while not success:
            try:
                self.__t.setZoneOverlay(zone=zone,
                                        overlayMode="MANUAL",
                                        setTemp=temperature)
                success = True
                LoggingHelper.log("Zone {} set to {} degrees.".format(
                    zone, temperature))
            except r_exc.RequestException as e:
                LoggingHelper.log("Unable to get device states.")
                LoggingHelper.log(e)
                self.__reconnect()

    def reset_zone(self, zone):
        success = False
        while not success:
            try:
                self.__t.resetZoneOverlay(zone=zone)
                success = True
                LoggingHelper.log(
                    "Zone {} reset to tado schedule.".format(zone))
            except r_exc.RequestException as e:
                LoggingHelper.log("Unable to get device states.")
                LoggingHelper.log(e)
                self.__reconnect()

    def get_device_athome_states(self):
        success = False
        data = None
        while not success:
            try:
                data = self.__t.getMobileDevices()
                if data is None:
                    raise TadoWrapperException(
                        "Mobile device data is None. Are any devices configured within Tado?"
                    )
                success = True
            except (r_exc.RequestException, TadoWrapperException) as e:
                LoggingHelper.log("Unable to get device states.")
                LoggingHelper.log(e)
                self.__reconnect()

        return {
            d["name"]: {
                "at_home": d["location"]["atHome"],
                "stale": d["location"]["stale"]
            }
            for d in data if d is not None and "location" in d
        }

    def is_presence_locked(self):
        success = False
        data = None
        result = False
        while not success:
            try:
                data = self.__t.getHomeState()
                if data == None:
                    raise TadoWrapperException(
                        "Mobile device data is None. Are any devices configured within Tado?"
                    )
                success = True
            except (r_exc.RequestException, TadoWrapperException) as e:
                LoggingHelper.log("Unable to get device states.")
                LoggingHelper.log(e)
                self.__reconnect()
        if "presenceLocked" in data:
            result = data["presenceLocked"]
        return result
Пример #12
0
def get_states(args):
    t = log_in(args.email, args.password)
    zone = tado_client.getZoneStates(t)
    print(zone)
 def __connect(self):
     username, password = c.get_credentials()
     self.__t = Tado(username, password)
Пример #14
0
class TadoConnector:
    """An object to store the Tado data."""
    def __init__(self, hass, username, password, fallback):
        """Initialize Tado Connector."""
        self.hass = hass
        self._username = username
        self._password = password
        self._fallback = fallback

        self.device_id = None
        self.tado = None
        self.zones = None
        self.devices = None
        self.data = {
            "zone": {},
            "device": {},
        }

    @property
    def fallback(self):
        """Return fallback flag to Smart Schedule."""
        return self._fallback

    def setup(self):
        """Connect to Tado and fetch the zones."""
        self.tado = Tado(self._username, self._password)
        self.tado.setDebugging(True)
        # Load zones and devices
        self.zones = self.tado.getZones()
        self.devices = self.tado.getMe()["homes"]
        self.device_id = self.devices[0]["id"]

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Update the registered zones."""
        for zone in self.zones:
            self.update_sensor("zone", zone["id"])
        for device in self.devices:
            self.update_sensor("device", device["id"])

    def update_sensor(self, sensor_type, sensor):
        """Update the internal data from Tado."""
        _LOGGER.debug("Updating %s %s", sensor_type, sensor)
        try:
            if sensor_type == "zone":
                data = self.tado.getZoneState(sensor)
            elif sensor_type == "device":
                devices_data = self.tado.getDevices()
                if not devices_data:
                    _LOGGER.info(
                        "There are no devices to setup on this tado account")
                    return

                data = devices_data[0]
            else:
                _LOGGER.debug("Unknown sensor: %s", sensor_type)
                return
        except RuntimeError:
            _LOGGER.error(
                "Unable to connect to Tado while updating %s %s",
                sensor_type,
                sensor,
            )
            return

        self.data[sensor_type][sensor] = data

        _LOGGER.debug(
            "Dispatching update to %s %s %s: %s",
            self.device_id,
            sensor_type,
            sensor,
            data,
        )
        dispatcher_send(
            self.hass,
            SIGNAL_TADO_UPDATE_RECEIVED.format(self.device_id, sensor_type,
                                               sensor),
        )

    def get_capabilities(self, zone_id):
        """Return the capabilities of the devices."""
        return self.tado.getCapabilities(zone_id)

    def reset_zone_overlay(self, zone_id):
        """Reset the zone back to the default operation."""
        self.tado.resetZoneOverlay(zone_id)
        self.update_sensor("zone", zone_id)

    def set_presence(
        self,
        presence=PRESET_HOME,
    ):
        """Set the presence to home or away."""
        if presence == PRESET_AWAY:
            self.tado.setAway()
        elif presence == PRESET_HOME:
            self.tado.setHome()

    def set_zone_overlay(
        self,
        zone_id=None,
        overlay_mode=None,
        temperature=None,
        duration=None,
        device_type="HEATING",
        mode=None,
        fan_speed=None,
        swing=None,
    ):
        """Set a zone overlay."""
        _LOGGER.debug(
            "Set overlay for zone %s: overlay_mode=%s, temp=%s, duration=%s, type=%s, mode=%s fan_speed=%s swing=%s",
            zone_id,
            overlay_mode,
            temperature,
            duration,
            device_type,
            mode,
            fan_speed,
            swing,
        )

        try:
            self.tado.setZoneOverlay(
                zone_id,
                overlay_mode,
                temperature,
                duration,
                device_type,
                "ON",
                mode,
                fanSpeed=fan_speed,
                swing=swing,
            )

        except RequestException as exc:
            _LOGGER.error("Could not set zone overlay: %s", exc)

        self.update_sensor("zone", zone_id)

    def set_zone_off(self, zone_id, overlay_mode, device_type="HEATING"):
        """Set a zone to off."""
        try:
            self.tado.setZoneOverlay(zone_id, overlay_mode, None, None,
                                     device_type, "OFF")
        except RequestException as exc:
            _LOGGER.error("Could not set zone overlay: %s", exc)

        self.update_sensor("zone", zone_id)
Пример #15
0
def get_me(args):
    t = log_in(args.email, args.password)
    me = tado_client.getMe(t)
    print(me)
Пример #16
0
class TadoConnector:
    """An object to store the Tado data."""

    def __init__(self, opp, username, password, fallback):
        """Initialize Tado Connector."""
        self.opp = opp
        self._username = username
        self._password = password
        self._fallback = fallback

        self.home_id = None
        self.home_name = None
        self.tado = None
        self.zones = None
        self.devices = None
        self.data = {
            "device": {},
            "weather": {},
            "zone": {},
        }

    @property
    def fallback(self):
        """Return fallback flag to Smart Schedule."""
        return self._fallback

    def setup(self):
        """Connect to Tado and fetch the zones."""
        self.tado = Tado(self._username, self._password)
        self.tado.setDebugging(True)
        # Load zones and devices
        self.zones = self.tado.getZones()
        self.devices = self.tado.getDevices()
        tado_home = self.tado.getMe()["homes"][0]
        self.home_id = tado_home["id"]
        self.home_name = tado_home["name"]

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Update the registered zones."""
        for device in self.devices:
            self.update_sensor("device", device["shortSerialNo"])
        for zone in self.zones:
            self.update_sensor("zone", zone["id"])
        self.data["weather"] = self.tado.getWeather()
        dispatcher_send(
            self.opp,
            SIGNAL_TADO_UPDATE_RECEIVED.format(self.home_id, "weather", "data"),
        )

    def update_sensor(self, sensor_type, sensor):
        """Update the internal data from Tado."""
        _LOGGER.debug("Updating %s %s", sensor_type, sensor)
        try:
            if sensor_type == "device":
                data = self.tado.getDeviceInfo(sensor)
                if (
                    INSIDE_TEMPERATURE_MEASUREMENT
                    in data["characteristics"]["capabilities"]
                ):
                    data[TEMP_OFFSET] = self.tado.getDeviceInfo(sensor, TEMP_OFFSET)
            elif sensor_type == "zone":
                data = self.tado.getZoneState(sensor)
            else:
                _LOGGER.debug("Unknown sensor: %s", sensor_type)
                return
        except RuntimeError:
            _LOGGER.error(
                "Unable to connect to Tado while updating %s %s",
                sensor_type,
                sensor,
            )
            return

        self.data[sensor_type][sensor] = data

        _LOGGER.debug(
            "Dispatching update to %s %s %s: %s",
            self.home_id,
            sensor_type,
            sensor,
            data,
        )
        dispatcher_send(
            self.opp,
            SIGNAL_TADO_UPDATE_RECEIVED.format(self.home_id, sensor_type, sensor),
        )

    def get_capabilities(self, zone_id):
        """Return the capabilities of the devices."""
        return self.tado.getCapabilities(zone_id)

    def reset_zone_overlay(self, zone_id):
        """Reset the zone back to the default operation."""
        self.tado.resetZoneOverlay(zone_id)
        self.update_sensor("zone", zone_id)

    def set_presence(
        self,
        presence=PRESET_HOME,
    ):
        """Set the presence to home or away."""
        if presence == PRESET_AWAY:
            self.tado.setAway()
        elif presence == PRESET_HOME:
            self.tado.setHome()

    def set_zone_overlay(
        self,
        zone_id=None,
        overlay_mode=None,
        temperature=None,
        duration=None,
        device_type="HEATING",
        mode=None,
        fan_speed=None,
        swing=None,
    ):
        """Set a zone overlay."""
        _LOGGER.debug(
            "Set overlay for zone %s: overlay_mode=%s, temp=%s, duration=%s, type=%s, mode=%s fan_speed=%s swing=%s",
            zone_id,
            overlay_mode,
            temperature,
            duration,
            device_type,
            mode,
            fan_speed,
            swing,
        )

        try:
            self.tado.setZoneOverlay(
                zone_id,
                overlay_mode,
                temperature,
                duration,
                device_type,
                "ON",
                mode,
                fanSpeed=fan_speed,
                swing=swing,
            )

        except RequestException as exc:
            _LOGGER.error("Could not set zone overlay: %s", exc)

        self.update_sensor("zone", zone_id)

    def set_zone_off(self, zone_id, overlay_mode, device_type="HEATING"):
        """Set a zone to off."""
        try:
            self.tado.setZoneOverlay(
                zone_id, overlay_mode, None, None, device_type, "OFF"
            )
        except RequestException as exc:
            _LOGGER.error("Could not set zone overlay: %s", exc)

        self.update_sensor("zone", zone_id)

    def set_temperature_offset(self, device_id, offset):
        """Set temperature offset of device."""
        try:
            self.tado.setTempOffset(device_id, offset)
        except RequestException as exc:
            _LOGGER.error("Could not set temperature offset: %s", exc)
Пример #17
0
def getWeather():
    t = Tado(os.environ['TADO_EMAIL'], os.environ['TADO_PASS'])
    w = t.getWeather()
    return f"The temperature is {w['outsideTemperature']['celsius']}C and the sun is shining on Hillerød with {w['solarIntensity']['percentage']}% intensity"
Пример #18
0
 def __init__(self, account, pwd):
     self.my_tado = Tado(account, pwd)
Пример #19
0
def get_state(args):
    t = log_in(args.email, args.password)
    zone = tado_client.getState(t, int(args.zone))
    print(zone)
Пример #20
0
def get_capabilities(args):
    t = log_in(args.email, args.password)
    capabilities = tado_client.getCapabilities(t, int(args.zone))
    print(capabilities)