Beispiel #1
0
def setup(hass, config):
    """Set up Tuya Component."""
    from tuyaha import TuyaApi

    tuya = TuyaApi()
    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    country_code = config[DOMAIN][CONF_COUNTRYCODE]
    platform = config[DOMAIN][CONF_PLATFORM]

    hass.data[DATA_TUYA] = tuya
    tuya.init(username, password, country_code, platform)
    hass.data[DOMAIN] = {"entities": {}}

    def load_devices(device_list):
        """Load new devices by device_list."""
        device_type_list = {}
        for device in device_list:
            dev_type = device.device_type()
            if (dev_type in TUYA_TYPE_TO_HA and device.object_id()
                    not in hass.data[DOMAIN]["entities"]):
                ha_type = TUYA_TYPE_TO_HA[dev_type]
                if ha_type not in device_type_list:
                    device_type_list[ha_type] = []
                device_type_list[ha_type].append(device.object_id())
                hass.data[DOMAIN]["entities"][device.object_id()] = None
        for ha_type, dev_ids in device_type_list.items():
            discovery.load_platform(hass, ha_type, DOMAIN,
                                    {"dev_ids": dev_ids}, config)

    device_list = tuya.get_all_devices()
    load_devices(device_list)

    def poll_devices_update(event_time):
        """Check if accesstoken is expired and pull device list from server."""
        _LOGGER.debug("Pull devices from Tuya.")
        tuya.poll_devices_update()
        # Add new discover device.
        device_list = tuya.get_all_devices()
        load_devices(device_list)
        # Delete not exist device.
        newlist_ids = []
        for device in device_list:
            newlist_ids.append(device.object_id())
        for dev_id in list(hass.data[DOMAIN]["entities"]):
            if dev_id not in newlist_ids:
                dispatcher_send(hass, SIGNAL_DELETE_ENTITY, dev_id)
                hass.data[DOMAIN]["entities"].pop(dev_id)

    track_time_interval(hass, poll_devices_update, timedelta(minutes=5))

    hass.services.register(DOMAIN, SERVICE_PULL_DEVICES, poll_devices_update)

    def force_update(call):
        """Force all devices to pull data."""
        dispatcher_send(hass, SIGNAL_UPDATE_ENTITY)

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

    return True
Beispiel #2
0
def main():
    global api
    api = TuyaApi()
    config.module.get_token(api)
    if not config.DEVICE_ID:
        print(api.get_all_devices())
        sys.exit(0)

    global socket
    socket = api.get_device_by_id(config.DEVICE_ID)
Beispiel #3
0
    def _try_connect(self):
        """Try to connect and check auth."""
        tuya = TuyaApi()
        try:
            tuya.init(self._username, self._password, self._country_code,
                      self._platform)
        except (TuyaNetException, TuyaServerException):
            return RESULT_CONN_ERROR
        except TuyaAPIException:
            return RESULT_AUTH_FAILED

        return RESULT_SUCCESS
Beispiel #4
0
 def __init__(self, device_name):
     username = credentials.login['username']
     password = credentials.login['password']
     country_code = 'us'
     api = TuyaApi()  # https://github.com/PaulAnnekov/tuyaha
     devices = api.init(username=username,
                        password=password,
                        countryCode=country_code)
     for dev in devices:
         dev_name = dev.obj_name
         if dev_name == device_name:
             self.device = dev
async def async_setup_entry(hass, entry):
    """Set up Tuya platform."""

    tuya = TuyaApi()
    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]
    country_code = entry.data[CONF_COUNTRYCODE]
    platform = entry.data[CONF_PLATFORM]

    try:
        await hass.async_add_executor_job(tuya.init, username, password,
                                          country_code, platform)
    except (TuyaNetException, TuyaServerException) as exc:
        raise ConfigEntryNotReady() from exc

    except TuyaAPIException as exc:
        _LOGGER.error(
            "Connection error during integration setup. Error: %s",
            exc,
        )
        return False

    hass.data[DOMAIN] = {
        TUYA_DATA: tuya,
        TUYA_TRACKER: None,
        ENTRY_IS_SETUP: set(),
        "entities": {},
        "pending": {},
    }

    async def async_load_devices(device_list):
        """Load new devices by device_list."""
        device_type_list = {}
        for device in device_list:
            dev_type = device.device_type()
            if (dev_type in TUYA_TYPE_TO_HA and device.object_id()
                    not in hass.data[DOMAIN]["entities"]):
                ha_type = TUYA_TYPE_TO_HA[dev_type]
                if ha_type not in device_type_list:
                    device_type_list[ha_type] = []
                device_type_list[ha_type].append(device.object_id())
                hass.data[DOMAIN]["entities"][device.object_id()] = None

        for ha_type, dev_ids in device_type_list.items():
            config_entries_key = f"{ha_type}.tuya"
            if config_entries_key not in hass.data[DOMAIN][ENTRY_IS_SETUP]:
                hass.data[DOMAIN]["pending"][ha_type] = dev_ids
                hass.async_create_task(
                    hass.config_entries.async_forward_entry_setup(
                        entry, ha_type))
                hass.data[DOMAIN][ENTRY_IS_SETUP].add(config_entries_key)
            else:
                async_dispatcher_send(hass, TUYA_DISCOVERY_NEW.format(ha_type),
                                      dev_ids)

    device_list = await hass.async_add_executor_job(tuya.get_all_devices)
    await async_load_devices(device_list)

    def _get_updated_devices():
        tuya.poll_devices_update()
        return tuya.get_all_devices()

    async def async_poll_devices_update(event_time):
        """Check if accesstoken is expired and pull device list from server."""
        _LOGGER.debug("Pull devices from Tuya")
        # Add new discover device.
        device_list = await hass.async_add_executor_job(_get_updated_devices)
        await async_load_devices(device_list)
        # Delete not exist device.
        newlist_ids = []
        for device in device_list:
            newlist_ids.append(device.object_id())
        for dev_id in list(hass.data[DOMAIN]["entities"]):
            if dev_id not in newlist_ids:
                async_dispatcher_send(hass, SIGNAL_DELETE_ENTITY, dev_id)
                hass.data[DOMAIN]["entities"].pop(dev_id)

    hass.data[DOMAIN][TUYA_TRACKER] = async_track_time_interval(
        hass, async_poll_devices_update, timedelta(minutes=5))

    hass.services.async_register(DOMAIN, SERVICE_PULL_DEVICES,
                                 async_poll_devices_update)

    async def async_force_update(call):
        """Force all devices to pull data."""
        async_dispatcher_send(hass, SIGNAL_UPDATE_ENTITY)

    hass.services.async_register(DOMAIN, SERVICE_FORCE_UPDATE,
                                 async_force_update)

    return True
Beispiel #6
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up Tuya platform."""

    tuya = TuyaApi()
    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]
    country_code = entry.data[CONF_COUNTRYCODE]
    platform = entry.data[CONF_PLATFORM]

    try:
        await opp.async_add_executor_job(tuya.init, username, password,
                                         country_code, platform)
    except (
            TuyaNetException,
            TuyaServerException,
            TuyaFrequentlyInvokeException,
    ) as exc:
        raise ConfigEntryNotReady() from exc

    except TuyaAPIRateLimitException as exc:
        raise ConfigEntryNotReady("Tuya login rate limited") from exc

    except TuyaAPIException as exc:
        _LOGGER.error(
            "Connection error during integration setup. Error: %s",
            exc,
        )
        return False

    domain_data = opp.data[DOMAIN] = {
        TUYA_DATA: tuya,
        TUYA_DEVICES_CONF: entry.options.copy(),
        TUYA_TRACKER: None,
        ENTRY_IS_SETUP: set(),
        "entities": {},
        "pending": {},
        "listener": entry.add_update_listener(update_listener),
    }

    _update_discovery_interval(
        opp,
        entry.options.get(CONF_DISCOVERY_INTERVAL, DEFAULT_DISCOVERY_INTERVAL))

    _update_query_interval(
        opp, entry.options.get(CONF_QUERY_INTERVAL, DEFAULT_QUERY_INTERVAL))

    async def async_load_devices(device_list):
        """Load new devices by device_list."""
        device_type_list = {}
        for device in device_list:
            dev_type = device.device_type()
            if (dev_type in TUYA_TYPE_TO_HA
                    and device.object_id() not in domain_data["entities"]):
                ha_type = TUYA_TYPE_TO_HA[dev_type]
                if ha_type not in device_type_list:
                    device_type_list[ha_type] = []
                device_type_list[ha_type].append(device.object_id())
                domain_data["entities"][device.object_id()] = None

        for ha_type, dev_ids in device_type_list.items():
            config_entries_key = f"{ha_type}.tuya"
            if config_entries_key not in domain_data[ENTRY_IS_SETUP]:
                domain_data["pending"][ha_type] = dev_ids
                opp.async_create_task(
                    opp.config_entries.async_forward_entry_setup(
                        entry, ha_type))
                domain_data[ENTRY_IS_SETUP].add(config_entries_key)
            else:
                async_dispatcher_send(opp, TUYA_DISCOVERY_NEW.format(ha_type),
                                      dev_ids)

    await async_load_devices(tuya.get_all_devices())

    def _get_updated_devices():
        try:
            tuya.poll_devices_update()
        except TuyaFrequentlyInvokeException as exc:
            _LOGGER.error(exc)
        return tuya.get_all_devices()

    async def async_poll_devices_update(event_time):
        """Check if accesstoken is expired and pull device list from server."""
        _LOGGER.debug("Pull devices from Tuya")
        # Add new discover device.
        device_list = await opp.async_add_executor_job(_get_updated_devices)
        await async_load_devices(device_list)
        # Delete not exist device.
        newlist_ids = []
        for device in device_list:
            newlist_ids.append(device.object_id())
        for dev_id in list(domain_data["entities"]):
            if dev_id not in newlist_ids:
                async_dispatcher_send(opp, SIGNAL_DELETE_ENTITY, dev_id)
                domain_data["entities"].pop(dev_id)

    domain_data[TUYA_TRACKER] = async_track_time_interval(
        opp, async_poll_devices_update, timedelta(minutes=2))

    @callback
    def _async_cancel_tuya_tracker(event):
        domain_data[TUYA_TRACKER]()

    domain_data[STOP_CANCEL] = opp.bus.async_listen_once(
        EVENT_OPENPEERPOWER_STOP, _async_cancel_tuya_tracker)

    opp.services.async_register(DOMAIN, SERVICE_PULL_DEVICES,
                                async_poll_devices_update)

    async def async_force_update(call):
        """Force all devices to pull data."""
        async_dispatcher_send(opp, SIGNAL_UPDATE_ENTITY)

    opp.services.async_register(DOMAIN, SERVICE_FORCE_UPDATE,
                                async_force_update)

    return True
Beispiel #7
0
async def async_setup_entry(hass, entry):
    """Set up config entry"""

    tuya = TuyaApi()

    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]
    country_code = entry.data[CONF_COUNTRYCODE]
    platform = entry.data[CONF_PLATFORM]

    hass.data[DATA_TUYA] = tuya
    tuya.init(username, password, country_code, platform)

    hass.data[DOMAIN] = {"entities": {}}

    for component in ("climate", "cover", "fan", "light", "switch"):
        hass.async_add_job(
            hass.config_entries.async_forward_entry_setup(entry, component))

    # def load_devices(device_list):
    #     """Load new devices by device_list."""
    #     device_type_list = {}
    #     for device in device_list:
    #         dev_type = device.device_type()
    #         if (
    #                 dev_type in TUYA_TYPE_TO_HA
    #                 and device.object_id() not in hass.data[DOMAIN]["entities"]
    #         ):
    #             ha_type = TUYA_TYPE_TO_HA[dev_type]
    #             if ha_type not in device_type_list:
    #                 device_type_list[ha_type] = []
    #             device_type_list[ha_type].append(device.object_id())
    #             hass.data[DOMAIN]["entities"][device.object_id()] = None
    #     for ha_type, dev_ids in device_type_list.items():
    #         discovery.load_platform(hass, ha_type, DOMAIN, {"dev_ids": dev_ids}, entry.data)
    #
    # _LOGGER.info("debug4")
    #
    # device_list = tuya.get_all_devices()
    # #load_devices(device_list)

    # def poll_devices_update(event_time):
    #     """Check if accesstoken is expired and pull device list from server."""
    #     _LOGGER.debug("Pull devices from Tuya.")
    #     tuya.poll_devices_update()
    #     # Add new discover device.
    #     device_list = tuya.get_all_devices()
    #     load_devices(device_list)
    #     # Delete not exist device.
    #     newlist_ids = []
    #     for device in device_list:
    #         newlist_ids.append(device.object_id())
    #     for dev_id in list(hass.data[DOMAIN]["entities"]):
    #         if dev_id not in newlist_ids:
    #             dispatcher_send(hass, SIGNAL_DELETE_ENTITY, dev_id)
    #             hass.data[DOMAIN]["entities"].pop(dev_id)
    #
    # _LOGGER.info("debug5")
    #
    # # track_time_interval(hass, poll_devices_update, timedelta(minutes=5))
    # _LOGGER.info("debug5.5")
    #
    # hass.services.register(DOMAIN, SERVICE_PULL_DEVICES, poll_devices_update)

    # _LOGGER.info("debug6")
    #     #
    #     # def force_update(call):
    #     #     """Force all devices to pull data."""
    #     #     dispatcher_send(hass, SIGNAL_UPDATE_ENTITY)
    #     #
    #     # _LOGGER.info("debug6.5")
    #     #
    #     # hass.services.register(DOMAIN, SERVICE_FORCE_UPDATE, force_update)
    #     #
    #     # _LOGGER.info("debug7")

    return True
        logger.info("Starting the charge")
        socket.turn_on()
    except:
        get_token(api)


def stop_charging(socket, api):
    try:
        logger.info("Stoping the charge")
        socket.turn_off()  # maybe add reconnecting if needed
    except:
        get_token(api)


if __name__ == "__main__":
    api = TuyaApi()
    get_token(api)
    if not DEVICE_ID:
        print(api.get_all_devices())
        sys.exit(0)

    socket = api.get_device_by_id(DEVICE_ID)
    while True:
        if battery_percentage(
        ) > STOP_CHARGING_PERCENTAGE and battery_charging():
            stop_charging(socket, api)
        elif battery_percentage(
        ) < START_CHARGING_PERCENTAGE and not battery_charging():
            start_charging(socket, api)
        logger.debug("Battery percentage at " + str(battery_percentage()))
        sleep(SLEEP_TIME)
confFile = "conf.json"
opts, args = getopt.getopt(sys.argv[1:], "c:d")
for opt, arg in opts:
    if opt == '-d':
        DEBUG = True
    elif opt == '-c':
        confFile = arg

conf = ConfigurationReader.Read(confFile)

username = conf["username"]
password = conf["password"]
countryCode = conf["country_code"]
deviceId = conf["device_id"]

api = TuyaApi()

api.init(username, password, countryCode)

device = api.get_device_by_id(deviceId)

device.set_brightness(10)
device.set_color_temp(2700)

delay = 5
step = 1

if DEBUG == True:
    delay = 1
    step = 20