def test_pronto_to_raw(self): for args in test_data["test_pronto_ok"]: with self.subTest(): self.assertSequenceEqual(ChuangmiIr.pronto_to_raw(*args["in"]), args["out"]) for args in test_data["test_pronto_exception"]: with self.subTest(), pytest.raises(ChuangmiIrException): ChuangmiIr.pronto_to_raw(*args["in"])
def test_pronto_to_raw(self): for args in test_data['test_pronto_ok']: with self.subTest(): self.assertSequenceEqual(ChuangmiIr.pronto_to_raw(*args['in']), args['out']) for args in test_data['test_pronto_exception']: with self.subTest(): with pytest.raises(ChuangmiIrException): ChuangmiIr.pronto_to_raw(*args['in'])
def miio_connect(self): if self.discovered: return True global ir if len(self.IP) > 0: try: Domoticz.Log( 'Attempt to connect to Chuangmi IR device with IP: {0} and token: {1}' .format(self.IP, self.token)) ir = ChuangmiIr(self.IP, self.token) info = ir.info() self.discovered = True Domoticz.Log('Connected.') return self.discovered except Exception as e: Domoticz.Log( 'Could not connect to {0} with IP {1}, check IP and Token.' .format(Parameters['Name'], self.IP))
#!/usr/bin/python3 import sys import ipaddress from typing import Any from miio import ChuangmiIr, DeviceException import time ############################################ ## ## Config ############################################## ip = 'device ip' token = 'device token' ####################NO MODIFICAR NADA MAS A PARTIR DE AQUI###### f = open('codes.txt') codeline = f.readlines() id = codeline[int(sys.argv[1]) - 1] print('vamos a enviar el codigo numero' + id) try: ir = ChuangmiIr(ip, token) except: print('esto ha petado sin decir nada flipa!') print('conexion con el ir Ok procedemos a enviar el codigo ->') ir.play(id, frequency='') print('todo ha ido bien creo!')
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Xiaomi IR Remote (Chuangmi IR) platform.""" from miio import ChuangmiIr, DeviceException host = config.get(CONF_HOST) token = config.get(CONF_TOKEN) # Create handler _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) # The Chuang Mi IR Remote Controller wants to be re-discovered every # 5 minutes. As long as polling is disabled the device should be # re-discovered (lazy_discover=False) in front of every command. device = ChuangmiIr(host, token, lazy_discover=False) # Check that we can communicate with device. try: device.info() except DeviceException as ex: _LOGGER.error("Token not accepted by device : %s", ex) return if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace('.', '_')) slot = config.get(CONF_SLOT) timeout = config.get(CONF_TIMEOUT) hidden = config.get(ATTR_HIDDEN) xiaomi_miio_remote = XiaomiMiioRemote(friendly_name, device, slot, timeout, hidden, config.get(CONF_COMMANDS)) hass.data[DATA_KEY][host] = xiaomi_miio_remote async_add_devices([xiaomi_miio_remote]) @asyncio.coroutine def async_service_handler(service): """Handle a learn command.""" if service.service != SERVICE_LEARN: _LOGGER.error("We should not handle service: %s", service.service) return entity_id = service.data.get(ATTR_ENTITY_ID) entity = None for remote in hass.data[DATA_KEY].values(): if remote.entity_id == entity_id: entity = remote if not entity: _LOGGER.error("entity_id: '%s' not found", entity_id) return device = entity.device slot = service.data.get(CONF_SLOT, entity.slot) yield from hass.async_add_job(device.learn, slot) timeout = service.data.get(CONF_TIMEOUT, entity.timeout) _LOGGER.info("Press the key you want Home Assistant to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=timeout): message = yield from hass.async_add_job(device.read, slot) _LOGGER.debug("Message recieved from device: '%s'", message) if 'code' in message and message['code']: log_msg = "Received command is: {}".format(message['code']) _LOGGER.info(log_msg) hass.components.persistent_notification.async_create( log_msg, title='Xiaomi Miio Remote') return if ('error' in message and message['error']['message'] == "learn timeout"): yield from hass.async_add_job(device.learn, slot) yield from asyncio.sleep(1, loop=hass.loop) _LOGGER.error("Timeout. No infrared command captured") hass.components.persistent_notification.async_create( "Timeout. No infrared command captured", title='Xiaomi Miio Remote') hass.services.async_register(DOMAIN, SERVICE_LEARN, async_service_handler, schema=LEARN_COMMAND_SCHEMA)
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Xiaomi IR Remote (Chuangmi IR) platform.""" from miio import ChuangmiIr, DeviceException host = config.get(CONF_HOST) token = config.get(CONF_TOKEN) # Create handler _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) # The Chuang Mi IR Remote Controller wants to be re-discovered every # 5 minutes. As long as polling is disabled the device should be # re-discovered (lazy_discover=False) in front of every command. device = ChuangmiIr(host, token, lazy_discover=False) # Check that we can communicate with device. try: device_info = device.info() model = device_info.model unique_id = "{}-{}".format(model, device_info.mac_address) _LOGGER.info("%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version) except DeviceException as ex: _LOGGER.error("Device unavailable or token incorrect: %s", ex) raise PlatformNotReady if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace('.', '_')) slot = config.get(CONF_SLOT) timeout = config.get(CONF_TIMEOUT) hidden = config.get(ATTR_HIDDEN) xiaomi_miio_remote = XiaomiMiioRemote(friendly_name, device, unique_id, slot, timeout, hidden, config.get(CONF_COMMANDS)) hass.data[DATA_KEY][host] = xiaomi_miio_remote async_add_devices([xiaomi_miio_remote]) @asyncio.coroutine def async_service_handler(service): """Handle a learn command.""" if service.service != SERVICE_LEARN: _LOGGER.error("We should not handle service: %s", service.service) return entity_id = service.data.get(ATTR_ENTITY_ID) entity = None for remote in hass.data[DATA_KEY].values(): if remote.entity_id == entity_id: entity = remote if not entity: _LOGGER.error("entity_id: '%s' not found", entity_id) return device = entity.device slot = service.data.get(CONF_SLOT, entity.slot) yield from hass.async_add_job(device.learn, slot) timeout = service.data.get(CONF_TIMEOUT, entity.timeout) _LOGGER.info("Press the key you want Home Assistant to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=timeout): message = yield from hass.async_add_job( device.read, slot) _LOGGER.debug("Message received from device: '%s'", message) if 'code' in message and message['code']: log_msg = "Received command is: {}".format(message['code']) _LOGGER.info(log_msg) hass.components.persistent_notification.async_create( log_msg, title='Xiaomi Miio Remote') return if ('error' in message and message['error']['message'] == "learn timeout"): yield from hass.async_add_job(device.learn, slot) yield from asyncio.sleep(1, loop=hass.loop) _LOGGER.error("Timeout. No infrared command captured") hass.components.persistent_notification.async_create( "Timeout. No infrared command captured", title='Xiaomi Miio Remote') hass.services.async_register(DOMAIN, SERVICE_LEARN, async_service_handler, schema=LEARN_COMMAND_SCHEMA)
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Xiaomi IR Remote (Chuangmi IR) platform.""" from miio import ChuangmiIr, DeviceException host = config.get(CONF_HOST) token = config.get(CONF_TOKEN) # Create handler _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) device = ChuangmiIr(host, token) # Check that we can communicate with device. try: device.info() except DeviceException as ex: _LOGGER.error("Token not accepted by device : %s", ex) return if PLATFORM not in hass.data: hass.data[PLATFORM] = {} friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace('.', '_')) slot = config.get(CONF_SLOT) timeout = config.get(CONF_TIMEOUT) hidden = config.get(ATTR_HIDDEN) xiaomi_miio_remote = XiaomiMiioRemote( friendly_name, device, slot, timeout, hidden, config.get(CONF_COMMANDS)) hass.data[PLATFORM][host] = xiaomi_miio_remote async_add_devices([xiaomi_miio_remote]) @asyncio.coroutine def async_service_handler(service): """Handle a learn command.""" if service.service != SERVICE_LEARN: _LOGGER.error("We should not handle service: %s", service.service) return entity_id = service.data.get(ATTR_ENTITY_ID) entity = None for remote in hass.data[PLATFORM].values(): if remote.entity_id == entity_id: entity = remote if not entity: _LOGGER.error("entity_id: '%s' not found", entity_id) return device = entity.device slot = service.data.get(CONF_SLOT, entity.slot) yield from hass.async_add_job(device.learn, slot) timeout = service.data.get(CONF_TIMEOUT, entity.timeout) _LOGGER.info("Press the key you want Home Assistant to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=timeout): message = yield from hass.async_add_job( device.read, slot) _LOGGER.debug("Message recieved from device: '%s'", message) if 'code' in message and message['code']: log_msg = "Received command is: {}".format(message['code']) _LOGGER.info(log_msg) hass.components.persistent_notification.async_create( log_msg, title='Xiaomi Miio Remote') return if ('error' in message and message['error']['message'] == "learn timeout"): yield from hass.async_add_job(device.learn, slot) yield from asyncio.sleep(1, loop=hass.loop) _LOGGER.error("Timeout. No infrared command captured") hass.components.persistent_notification.async_create( "Timeout. No infrared command captured", title='Xiaomi Miio Remote') hass.services.async_register(DOMAIN, SERVICE_LEARN, async_service_handler, schema=LEARN_COMMAND_SCHEMA)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Xiaomi IR Remote (Chuangmi IR) platform.""" host = config[CONF_HOST] token = config[CONF_TOKEN] # Create handler _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) # The Chuang Mi IR Remote Controller wants to be re-discovered every # 5 minutes. As long as polling is disabled the device should be # re-discovered (lazy_discover=False) in front of every command. device = ChuangmiIr(host, token, lazy_discover=False) # Check that we can communicate with device. try: device_info = await hass.async_add_executor_job(device.info) model = device_info.model unique_id = f"{model}-{device_info.mac_address}" _LOGGER.info( "%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version, ) except DeviceException as ex: _LOGGER.error("Device unavailable or token incorrect: %s", ex) raise PlatformNotReady from ex if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} friendly_name = config.get(CONF_NAME, f"xiaomi_miio_{host.replace('.', '_')}") slot = config.get(CONF_SLOT) timeout = config.get(CONF_TIMEOUT) xiaomi_miio_remote = XiaomiMiioRemote(friendly_name, device, unique_id, slot, timeout, config.get(CONF_COMMANDS)) hass.data[DATA_KEY][host] = xiaomi_miio_remote async_add_entities([xiaomi_miio_remote]) async def async_service_led_off_handler(entity, service): """Handle set_led_off command.""" await hass.async_add_executor_job(entity.device.set_indicator_led, False) async def async_service_led_on_handler(entity, service): """Handle set_led_on command.""" await hass.async_add_executor_job(entity.device.set_indicator_led, True) async def async_service_learn_handler(entity, service): """Handle a learn command.""" device = entity.device slot = service.data.get(CONF_SLOT, entity.slot) await hass.async_add_executor_job(device.learn, slot) timeout = service.data.get(CONF_TIMEOUT, entity.timeout) _LOGGER.info("Press the key you want Home Assistant to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=timeout): message = await hass.async_add_executor_job(device.read, slot) _LOGGER.debug("Message received from device: '%s'", message) if "code" in message and message["code"]: log_msg = "Received command is: {}".format(message["code"]) _LOGGER.info(log_msg) hass.components.persistent_notification.async_create( log_msg, title="Xiaomi Miio Remote") return if "error" in message and message["error"][ "message"] == "learn timeout": await hass.async_add_executor_job(device.learn, slot) await asyncio.sleep(1) _LOGGER.error("Timeout. No infrared command captured") hass.components.persistent_notification.async_create( "Timeout. No infrared command captured", title="Xiaomi Miio Remote") platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_LEARN, { vol.Optional(CONF_TIMEOUT, default=10): cv.positive_int, vol.Optional(CONF_SLOT, default=1): vol.All(int, vol.Range(min=1, max=1000000)), }, async_service_learn_handler, ) platform.async_register_entity_service( SERVICE_SET_REMOTE_LED_ON, {}, async_service_led_on_handler, ) platform.async_register_entity_service( SERVICE_SET_REMOTE_LED_OFF, {}, async_service_led_off_handler, )
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Xiaomi IR Remote (Chuangmi IR) platform.""" from miio import ChuangmiIr, DeviceException host = config.get(CONF_HOST) token = config.get(CONF_TOKEN) # Create handler _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) # The Chuang Mi IR Remote Controller wants to be re-discovered every # 5 minutes. As long as polling is disabled the device should be # re-discovered (lazy_discover=False) in front of every command. device = ChuangmiIr(host, token, lazy_discover=False) # Check that we can communicate with device. try: device_info = device.info() model = device_info.model unique_id = f"{model}-{device_info.mac_address}" _LOGGER.info( "%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version, ) except DeviceException as ex: _LOGGER.error("Device unavailable or token incorrect: %s", ex) raise PlatformNotReady if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace(".", "_")) slot = config.get(CONF_SLOT) timeout = config.get(CONF_TIMEOUT) hidden = config.get(ATTR_HIDDEN) xiaomi_miio_remote = XiaomiMiioRemote( friendly_name, device, unique_id, slot, timeout, hidden, config.get(CONF_COMMANDS), ) hass.data[DATA_KEY][host] = xiaomi_miio_remote async_add_entities([xiaomi_miio_remote]) async def async_service_handler(service): """Handle a learn command.""" if service.service != SERVICE_LEARN: _LOGGER.error("We should not handle service: %s", service.service) return entity_id = service.data.get(ATTR_ENTITY_ID) entity = None for remote in hass.data[DATA_KEY].values(): if remote.entity_id == entity_id: entity = remote if not entity: _LOGGER.error("entity_id: '%s' not found", entity_id) return device = entity.device slot = service.data.get(CONF_SLOT, entity.slot) await hass.async_add_executor_job(device.learn, slot) timeout = service.data.get(CONF_TIMEOUT, entity.timeout) _LOGGER.info("Press the key you want Home Assistant to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=timeout): message = await hass.async_add_executor_job(device.read, slot) _LOGGER.debug("Message received from device: '%s'", message) if "code" in message and message["code"]: log_msg = "Received command is: {}".format(message["code"]) _LOGGER.info(log_msg) hass.components.persistent_notification.async_create( log_msg, title="Xiaomi Miio Remote" ) return if "error" in message and message["error"]["message"] == "learn timeout": await hass.async_add_executor_job(device.learn, slot) await asyncio.sleep(1) _LOGGER.error("Timeout. No infrared command captured") hass.components.persistent_notification.async_create( "Timeout. No infrared command captured", title="Xiaomi Miio Remote" ) hass.services.async_register( DOMAIN, SERVICE_LEARN, async_service_handler, schema=LEARN_COMMAND_SCHEMA )
Then update the constants. Usage: python ir_learn.py power Then you have 5 seconds to point your remote at your blaster and hit the power button on your remote. Repeat with different key for each button you want to get a command for. """ import sys import time from miio import ChuangmiIr IP = '192.168.1.61' TOKEN = '' ir = ChuangmiIr(IP, TOKEN) def _main(x): ir.learn(key=1) time.sleep(5) print(x, ir.read(key=1).get('code')) if __name__ == '__main__': _main(sys.argv[1:])
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Broadlink IR Climate platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) token = config.get(CONF_TOKEN) # Create handler _LOGGER.info( "Initializing Xiaomi Remote climate component with host %s (token %s...)", host, token[:5]) from miio import ChuangmiIr, DeviceException # The Chuang Mi IR Remote Controller wants to be re-discovered every # 5 minutes. As long as polling is disabled the device should be # re-discovered (lazy_discover=False) in front of every command. device = ChuangmiIr(host, token, lazy_discover=False) # Check that we can communicate with device. try: device_info = device.info() model = device_info.model unique_id = "{}-{}".format(model, device_info.mac_address) _LOGGER.info("%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version) except DeviceException as ex: _LOGGER.error("Device unavailable or token incorrect: %s", ex) raise PlatformNotReady min_temp = config.get(CONF_MIN_TEMP) max_temp = config.get(CONF_MAX_TEMP) target_temp = config.get(CONF_TARGET_TEMP) temp_sensor_entity_id = config.get(CONF_TEMP_SENSOR) operation_list = config.get(CONF_CUSTOMIZE).get( CONF_OPERATIONS, []) or DEFAULT_OPERATION_LIST operation_list.append(STATE_OFF) fan_list = config.get(CONF_CUSTOMIZE).get(CONF_FAN_MODES, []) or DEFAULT_FAN_MODE_LIST default_operation = config.get(CONF_DEFAULT_OPERATION) default_fan_mode = config.get(CONF_DEFAULT_FAN_MODE) default_operation_from_idle = config.get(CONF_DEFAULT_OPERATION_FROM_IDLE) ircodes_ini_file = config.get(CONF_IRCODES_INI) if ircodes_ini_file.startswith("/"): ircodes_ini_file = ircodes_ini_file[1:] ircodes_ini_path = hass.config.path(ircodes_ini_file) if os.path.exists(ircodes_ini_path): ircodes_ini = ConfigParser() ircodes_ini.read(ircodes_ini_path) else: _LOGGER.error("The ini file was not found. (" + ircodes_ini_path + ")") return async_add_devices([ XiaomiIRClimate(hass, name, device, ircodes_ini, min_temp, max_temp, target_temp, temp_sensor_entity_id, operation_list, fan_list, default_operation, default_fan_mode, default_operation_from_idle) ])
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the smart mi fan platform.""" from miio import ChuangmiIr, DeviceException host = config.get(CONF_HOST) token = config.get(CONF_TOKEN) devices = config.get(CONF_SWITCHES, {}) retries = config.get(CONF_RETRIES) persistent_notification = loader.get_component('persistent_notification') _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) try: # The Chuang Mi IR Remote Controller wants to be re-discovered every # 5 minutes. As long as polling is disabled the device should be # re-discovered (lazy_discover=False) in front of every command. ir_remote = ChuangmiIr(host, token, lazy_discover=False) device_info = ir_remote.info() except DeviceException: _LOGGER.info("Connection failed.") raise PlatformNotReady @asyncio.coroutine def _learn_command(call): key = randint(1, 1000000) ir_remote.learn(key) _LOGGER.info( "Press the key to capture of your remote control") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=DEFAULT_TIMEOUT): res = ir_remote.read(key) if res["code"]: log_msg = 'Captured infrared command: %s' % res["code"] _LOGGER.info(log_msg) persistent_notification.async_create( hass, log_msg, title='Chuang Mi IR Remote Controller') return yield from asyncio.sleep(1, loop=hass.loop) log_msg = 'Timeout. No infrared command captured.' _LOGGER.error(log_msg) persistent_notification.async_create( hass, log_msg, title='Chuang Mi IR Remote Controller') @asyncio.coroutine def _send_command(call): command = str(call.data.get(ATTR_COMMAND)) if command: for retry in range(retries): try: ir_remote.play_raw(command, 38400) break except (timeout, ValueError): _LOGGER.error("Transmit infrared command failed.") else: _LOGGER.debug("Empty infrared command skipped.") hass.services.register( DOMAIN, SERVICE_LEARN + '_' + host.replace('.', '_'), _learn_command) hass.services.register( DOMAIN, SERVICE_SEND + '_' + host.replace('.', '_'), _send_command) switches = [] for object_id, device_config in devices.items(): switches.append( ChuangMiInfraredSwitch( ir_remote, device_config.get(CONF_NAME, object_id), device_config.get(CONF_COMMAND_ON), device_config.get(CONF_COMMAND_OFF), device_info ) ) add_devices(switches)
from miio import ChuangmiIr,DeviceException import time import json import os import os.path fichero ='./codes.txt' ip= 'Device ip' token = 'Device token' try: os.stat("codes.txt") print ('Existe el fichero codes.txt') except: print ('No existe codes txt vamos a crearlo') file = open("codes.txt", "w") num_lines = sum(1 for line in open('codes.txt')) print ('Stored Ir Keys ->'+ str(num_lines) ) id = num_lines + 1 ir = ChuangmiIr(ip,token) ir.learn(key=1) time.sleep(10) print (ir.read(key=1).get("code")) with open('codes.txt', 'a') as file: try: file.write(ir.read(key=1).get("code")+ '\n') except: print('cant save the Ir code readin error')