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
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)
async def async_setup_entry(hass: HomeAssistant, 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 hass.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: _LOGGER.error("Tuya login rate limited") 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_DEVICES_CONF: entry.options.copy(), TUYA_TRACKER: None, ENTRY_IS_SETUP: set(), "entities": {}, "pending": {}, "listener": entry.add_update_listener(update_listener), } _update_discovery_interval( hass, entry.options.get(CONF_DISCOVERY_INTERVAL, DEFAULT_DISCOVERY_INTERVAL) ) _update_query_interval( hass, 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 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) 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 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=2) ) 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
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) #plugged = "Plugged In" if plugged else "Not Plugged In" #print(percent+'% | '+plugged)