def async_setup_platform(hass, config, async_add_devices, discovery_info=None):    
    """Set up the Broadlink IR Media Player platform."""
    name = config.get(CONF_NAME)
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(config.get(CONF_MAC).encode().replace(b':', b''))
    
    import broadlink
    
    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)

    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to Broadlink RM Device")
    
    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.optionxform = str
        ircodes_ini.read(ircodes_ini_path)
    else:
        _LOGGER.error("The ini file was not found. (" + ircodes_ini_path + ")")
        return
    
    async_add_devices([BroadlinkIRMediaPlayer(hass, name, broadlink_device, ircodes_ini)], True)
def learnCommand(commandName):
    device = broadlink.rm((RMIPAddress, RMPort), RMMACAddress)
    device.auth()

    deviceKey = device.key
    deviceIV = device.iv

    device.enter_learning()
    time.sleep(RealTimeout)
    LearnedCommand = device.check_data()

    if LearnedCommand is None:
        print('Command not received')
        return False

    AdditionalData = bytearray([0x00, 0x00, 0x00, 0x00])    
    finalCommand = AdditionalData + LearnedCommand

    AESEncryption = AES.new(str(deviceKey), AES.MODE_CBC, str(deviceIV))
    decodedCommand = binascii.hexlify(AESEncryption.decrypt(str(finalCommand)))

    broadlinkControlIniFile = open(path.join(settings.applicationDir, 'settings.ini'), 'w')    
    settingsFile.set('Commands', commandName, decodedCommand)
    settingsFile.write(broadlinkControlIniFile)
    broadlinkControlIniFile.close()
    return True
def getTempRM():
    device = broadlink.rm((RMIPAddress, RMPort), RMMACAddress)
    device.auth()
    temperature = device.check_temperature()
    if temperature:
        return temperature
    return False 
def sendCommand(commandName):
    device = broadlink.rm((RMIPAddress, RMPort), RMMACAddress)
    device.auth()

    deviceKey = device.key
    deviceIV = device.iv

    if settingsFile.has_option('Commands', commandName):
        commandFromSettings = settingsFile.get('Commands', commandName)
    else:
        return False

    print('sending command %s' % commandName)
    if commandFromSettings.strip() != '':
        decodedCommand = binascii.unhexlify(commandFromSettings)
        AESEncryption = AES.new(str(deviceKey), AES.MODE_CBC, str(deviceIV))
        encodedCommand = AESEncryption.encrypt(str(decodedCommand))
        
        finalCommand = encodedCommand[0x04:]    
        
        signal.signal(signal.SIGALRM, signal_handler)
        signal.alarm(4)   # Ten seconds
        try:
            device.send_data(finalCommand)
        except Exception, msg:
            print "Probably timed out.."
            return True
Example #5
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup Broadlink switches."""
    import broadlink
    devices = config.get(CONF_SWITCHES, {})
    switches = []
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device.")

    persistent_notification = loader.get_component('persistent_notification')

    @asyncio.coroutine
    def _learn_command(call):
        try:
            yield from hass.loop.run_in_executor(None, broadlink_device.auth)
        except socket.timeout:
            _LOGGER.error("Failed to connect to device.")
            return
        yield from hass.loop.run_in_executor(None,
                                             broadlink_device.enter_learning)

        _LOGGER.info("Press the key you want HASS to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=20):
            packet = yield from hass.loop.run_in_executor(None,
                                                          broadlink_device.
                                                          check_data)
            if packet:
                log_msg = 'Recieved packet is: {}'.\
                          format(b64encode(packet).decode('utf8'))
                _LOGGER.info(log_msg)
                persistent_notification.async_create(hass, log_msg,
                                                     title='Broadlink switch')
                return
            yield from asyncio.sleep(1, loop=hass.loop)
        _LOGGER.error('Did not received any signal.')
        persistent_notification.async_create(hass,
                                             "Did not received any signal",
                                             title='Broadlink switch')
    hass.services.register(DOMAIN, SERVICE_LEARN, _learn_command)

    for object_id, device_config in devices.items():
        switches.append(
            BroadlinkRM2Switch(
                device_config.get(CONF_FRIENDLY_NAME, object_id),
                device_config.get(CONF_COMMAND_ON),
                device_config.get(CONF_COMMAND_OFF),
                broadlink_device
            )
        )

    add_devices(switches)
Example #6
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Broadlink switches."""
    import broadlink
    devices = config.get(CONF_SWITCHES)
    slots = config.get('slots', {})
    ip_addr = config.get(CONF_HOST)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    switch_type = config.get(CONF_TYPE)

    def _get_mp1_slot_name(switch_friendly_name, slot):
        """Get slot name."""
        if not slots['slot_{}'.format(slot)]:
            return '{} slot {}'.format(switch_friendly_name, slot)
        return slots['slot_{}'.format(slot)]

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
        hass.add_job(async_setup_service, hass, ip_addr, broadlink_device)

        switches = []
        for object_id, device_config in devices.items():
            switches.append(
                BroadlinkRMSwitch(
                    object_id,
                    device_config.get(CONF_FRIENDLY_NAME, object_id),
                    broadlink_device,
                    device_config.get(CONF_COMMAND_ON),
                    device_config.get(CONF_COMMAND_OFF)
                )
            )
    elif switch_type in SP1_TYPES:
        broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr, None)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif switch_type in SP2_TYPES:
        broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr, None)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
    elif switch_type in MP1_TYPES:
        switches = []
        broadlink_device = broadlink.mp1((ip_addr, 80), mac_addr, None)
        parent_device = BroadlinkMP1Switch(broadlink_device)
        for i in range(1, 5):
            slot = BroadlinkMP1Slot(
                _get_mp1_slot_name(friendly_name, i),
                broadlink_device, i, parent_device)
            switches.append(slot)

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device")

    add_entities(switches)
async def async_setup_platform(hass,
                               config,
                               async_add_devices,
                               discovery_info=None):
    """Set up the Broadlink IR Climate platform."""
    name = config.get(CONF_NAME)
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))

    min_temp = config.get(CONF_MIN_TEMP)
    max_temp = config.get(CONF_MAX_TEMP)
    target_temp_step = config.get(CONF_TARGET_TEMP_STEP)
    temp_sensor_entity_id = config.get(CONF_TEMP_SENSOR)
    operation_list = config.get(CONF_CUSTOMIZE).get(
        CONF_OPERATIONS, []) or DEFAULT_OPERATION_LIST
    operation_list = [STATE_OFF] + operation_list
    fan_list = config.get(CONF_CUSTOMIZE).get(CONF_FAN_MODES,
                                              []) or DEFAULT_FAN_MODE_LIST

    import broadlink

    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)

    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to Broadlink RM Device")

    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([
        BroadlinkIRClimate(hass, name, broadlink_device, ircodes_ini, min_temp,
                           max_temp, target_temp_step, temp_sensor_entity_id,
                           operation_list, fan_list)
    ])
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Set up the Broadlink-controlled fan platform."""
    name = config.get(CONF_NAME)
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    speed_list = config.get(CONF_CUSTOMIZE).get(CONF_SPEEDS,
                                                []) or DEFAULT_SPEED_LIST
    if not STATE_OFF in speed_list:
        speed_list.insert(0, STATE_OFF)
    default_speed = config.get(CONF_DEFAULT_SPEED)
    default_direction = config.get(CONF_DEFAULT_DIRECTION)

    import broadlink

    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)

    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to Broadlink RM Device")

    rfcodes_ini_file = config.get(CONF_RFCODES_INI)

    if rfcodes_ini_file.startswith("/"):
        rfcodes_ini_file = rfcodes_ini_file[1:]

    rfcodes_ini_path = hass.config.path(rfcodes_ini_file)

    if os.path.exists(rfcodes_ini_path):
        rfcodes_ini = ConfigParser()
        rfcodes_ini.read(rfcodes_ini_path)
    else:
        _LOGGER.error("The ini file was not found. (" + rfcodes_ini_path + ")")
        return

    if DIRECTION_ANTICLOCKWISE in rfcodes_ini.sections(
    ) and DIRECTION_CLOCKWISE in rfcodes_ini.sections():
        supported_features = SUPPORT_SPEED_AND_DIRECTION
    else:
        supported_features = LIMITED_SUPPORT
    #if 'oscillate' in rfcodes_ini.sections():
    #    supported_features = supported_features | SUPPORT_OSCILLATE

    add_devices_callback([
        BroadlinkFan(hass, name, broadlink_device, rfcodes_ini, speed_list,
                     default_speed, default_direction, supported_features)
    ])
Example #9
0
 def device(self):
     device = broadlink.rm(
         host=(self.ip, self.port), mac=dec_hex(self.mac_hex), devtype=self.devtype
     )
     try:
         device.auth()
     except broadlink.exceptions.NetworkTimeoutError:
         _LOGGER.error(
             "Can't connect to device %s (IP: %s MAC: %s)",
             self.name,
             self.ip,
             self.mac,
         )
         return None
     return device
Example #10
0
def broadlinkConnect():
    global device, brohost, bromac

    try:
        device = broadlink.rm(host=(brohost, 80),
                              mac=bytearray.fromhex(bromac),
                              devtype='RM2')
        device.auth()
        device.host
        print("Connected to Broadlink device.")
    except:
        print("Error Connecting to Broadlink device....")
        sys.exit(2)

    return True
def broadlinkConnect():
    global device, isConnected

    try:
        device = broadlink.rm(host=(Parameters["Address"],80), mac=bytearray.fromhex(Parameters["Mode1"]))
        device.auth()
        device.host
        isConnected = True
        Domoticz.Log( "Connected to Broadlink device.")        
    except:
        Domoticz.Error( "Error Connecting to Broadlink device....")
        isConnected = False
        return False

    return True
Example #12
0
def readSettings(settingsFile, devname):
    try:
        Dev = devices.Dev[devname]
        if Dev['Type'] == 'RM' or Dev['Type'] == 'RM2':
            device = broadlink.rm((Dev['IPAddress'], 80), Dev['MACAddress'],
                                  Dev['Device'])
        elif Dev['Type'] == 'MP1':
            device = broadlink.mp1((Dev['IPAddress'], 80), Dev['MACAddress'],
                                   Dev['Device'])
        elif Dev['Type'] == 'SP1':
            device = broadlink.sp1((Dev['IPAddress'], 80), Dev['MACAddress'],
                                   Dev['Device'])
        elif Dev['Type'] == 'SP2':
            device = broadlink.sp2((Dev['IPAddress'], 80), Dev['MACAddress'],
                                   Dev['Device'])
        elif Dev['Type'] == 'A1':
            device = broadlink.a1((Dev['IPAddress'], 80), Dev['MACAddress'],
                                  Dev['Device'])
        elif Dev['Type'] == 'HYSEN':
            device = broadlink.hysen((Dev['IPAddress'], 80), Dev['MACAddress'],
                                     Dev['Device'])
        elif Dev['Type'] == 'S1C':
            device = broadlink.S1C((Dev['IPAddress'], 80), Dev['MACAddress'],
                                   Dev['Device'])
        elif Dev['Type'] == 'DOOYA':
            device = broadlink.dooya((Dev['IPAddress'], 80), Dev['MACAddress'],
                                     Dev['Device'])
        else:
            return False
        Dev['BaseType'] = "broadlink"

        if 'Delay' in Dev:
            device.delay = Dev['Delay']
        else:
            device.delay = 0.0

        #- set the callbacks
        Dev['learnCommand'] = learnCommand
        Dev['sendCommand'] = sendCommand
        Dev['getStatus'] = None
        Dev['setStatus'] = None
        Dev['getSensor'] = getSensor
        return device
    except Exception as e:
        logfile(
            "Broadlink device support requires broadlink python module.\npip3 install broadlink",
            "WARN")
        return None
Example #13
0
 def onStart(self):
     if Parameters["Mode6"] == "Debug":
         Domoticz.Debugging(1)
     if (len(Devices) == 0):
         Domoticz.Device(Name="Temp", Unit=1,
                         TypeName="Temperature").Create()
     self.myRM = broadlink.rm(host=(Parameters["Address"],
                                    int(Parameters["Port"])),
                              mac=bytearray.fromhex(Parameters["Mode1"]))
     try:
         self.isFound = self.myRM.auth()
     except socket.timeout:
         self.isFound = False
         Domoticz.Error("RM not found")
     Domoticz.Heartbeat(60)
     Domoticz.Debug("onStart called")
Example #14
0
def send_rm2(device):
    result = {}
    host = device['ip']
    port = device['port']
    mac = device['mac']
    if mac[-3:] == 'sub':
        logging.debug("This is a child device original mac is " + mac[:-4])
        mac = mac[:-4]
    name = device['name']
    hex2send = device['hex2send']
    product = broadlink.rm(host=(host, int(port)), mac=bytearray.fromhex(mac))
    logging.debug("Connecting to Broadlink device with name " + name + "....")
    product.auth()
    logging.debug("Connected to Broadlink device with name " + name + "....")
    product.send_data(hex2send.decode('hex'))
    logging.debug("Code Sent....")
    return
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Set up the Broadlink-controlled fan platform."""
    name = config.get(CONF_NAME)
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(config.get(CONF_MAC).encode().replace(b':', b''))
    speed_list = config.get(CONF_CUSTOMIZE).get(CONF_SPEEDS, []) or DEFAULT_SPEED_LIST
    if not STATE_OFF in speed_list:
        speed_list.insert(0, STATE_OFF)
    default_speed = config.get(CONF_DEFAULT_SPEED)
    default_direction = config.get(CONF_DEFAULT_DIRECTION)
    
    import broadlink
    
    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)

    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to Broadlink RM Device")
    
    rfcodes_ini_file = config.get(CONF_RFCODES_INI)
    
    if rfcodes_ini_file.startswith("/"):
        rfcodes_ini_file = rfcodes_ini_file[1:]
        
    rfcodes_ini_path = hass.config.path(rfcodes_ini_file)
    
    if os.path.exists(rfcodes_ini_path):
        rfcodes_ini = ConfigParser()
        rfcodes_ini.read(rfcodes_ini_path)
    else:
        _LOGGER.error("The ini file was not found. (" + rfcodes_ini_path + ")")
        return
    
    
    if DIRECTION_ANTICLOCKWISE in rfcodes_ini.sections() and DIRECTION_CLOCKWISE in rfcodes_ini.sections():
        supported_features = SUPPORT_SPEED_AND_DIRECTION
    else:
        supported_features = LIMITED_SUPPORT
    #if 'oscillate' in rfcodes_ini.sections():
    #    supported_features = supported_features | SUPPORT_OSCILLATE
    
    add_devices_callback([
        BroadlinkFan(hass, name, broadlink_device, rfcodes_ini, speed_list, default_speed, default_direction, supported_features)
    ])
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Broadlink IR Climate platform."""
    name = config.get(CONF_NAME)
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(config.get(CONF_MAC).encode().replace(b':', b''))
    
    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
    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)
    
    import broadlink
    
    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)

    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to Broadlink RM Device")
    
    
    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([
        BroadlinkIRClimate(hass, name, broadlink_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 send_cmd(self, to_host, to_mac, to_devtype="RM2"):
		self.__build_cmd()
		#device = broadlink.rm(host=("192.168.2.96",80), mac=bytearray.fromhex("34 ea 34 8a 35 ee"),devtype="RM2")
		device = broadlink.rm(host=(to_host,80), mac=bytearray.fromhex(to_mac),devtype=to_devtype)
		if (self._log):
			print("Connecting to Broadlink device....")
		device.auth()
		time.sleep(1)
		if (self._log):
			print("Connected....")
		time.sleep(1)
		device.host
		myhex = self.__StrHexCode
		myhex = myhex.replace(' ', '').replace('\n', '')
		myhex = myhex.encode('ascii', 'strict')
		device.send_data(binascii.unhexlify(myhex))
		if (self._log):
			print("Code Sent....")
Example #18
0
 def broadlink_send_cmd(self, to_host, to_mac, to_devtype="RM2"):
     self.__build_cmd()
     #device = broadlink.rm(host=("192.168.2.96",80), mac=bytearray.fromhex("34 ea 34 8a 35 ee"),devtype="RM2")
     device = broadlink.rm(host=(to_host,80), mac=bytearray.fromhex(to_mac),devtype=to_devtype)
     if (self._log):
         print("Connecting to Broadlink device....")
     device.auth()
     time.sleep(1)
     if (self._log):
         print("Connected....")
     time.sleep(1)
     device.host
     myhex = self.__StrHexCode
     myhex = myhex.replace(' ', '').replace('\n', '')
     myhex = myhex.encode('ascii', 'strict')
     device.send_data(binascii.unhexlify(myhex))
     if (self._log):
         print("Code Sent....")
Example #19
0
async def async_setup_platform(hass,
                               config,
                               async_add_devices,
                               discovery_info=None):
    """Set up the Broadlink IR Media Player platform."""
    name = config.get(CONF_NAME)
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))

    import broadlink

    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
    broadlink_device.timeout = config.get(CONF_TIMEOUT)

    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to Broadlink RM Device")

    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.optionxform = str
        ircodes_ini.read(ircodes_ini_path)
    else:
        _LOGGER.error("The ini file was not found. (" + ircodes_ini_path + ")")
        return

    ping_host = config.get(CONF_PING_HOST)
    power_cons_entity_id = config.get(CONF_POWER_CONS_SENSOR)
    power_cons_threshold = config.get(CONF_POWER_CONS_THRESHOLD)

    async_add_devices([
        BroadlinkIRMediaPlayer(hass, name, broadlink_device, ircodes_ini,
                               ping_host, power_cons_entity_id,
                               power_cons_threshold)
    ], True)
Example #20
0
def send_broadlink_code(code, retry_num=1):
    global RMPRO_IP
    global RMPRO_MAC
    if (code != ""):
        try:
            # settings
            device = broadlink.rm(host=(RMPRO_IP, 80),
                                  mac=bytearray.fromhex(RMPRO_MAC),
                                  devtype="rm")
            device.auth()
            for i in range(retry_num):
                decode_hex = codecs.getdecoder("hex_codec")
                device.send_data(decode_hex(code)[0])
            return True
        except Exception as e:
            logger.error(e)
            return False
    else:
        logger.error("Empty code value")
Example #21
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Broadlink remote."""
    host = config[CONF_HOST]
    mac_addr = config[CONF_MAC]
    model = config[CONF_TYPE]
    timeout = config[CONF_TIMEOUT]
    name = config[CONF_NAME]
    unique_id = f"remote_{hexlify(mac_addr).decode('utf-8')}"

    if unique_id in hass.data.setdefault(DOMAIN, {}).setdefault(COMPONENT, []):
        _LOGGER.error("Duplicate: %s", unique_id)
        return
    hass.data[DOMAIN][COMPONENT].append(unique_id)

    if model in RM_TYPES:
        api = blk.rm((host, DEFAULT_PORT), mac_addr, None)
    else:
        api = blk.rm4((host, DEFAULT_PORT), mac_addr, None)
    api.timeout = timeout
    device = BroadlinkDevice(hass, api)

    code_storage = Store(hass, CODE_STORAGE_VERSION,
                         f"broadlink_{unique_id}_codes")
    flag_storage = Store(hass, FLAG_STORAGE_VERSION,
                         f"broadlink_{unique_id}_flags")

    remote = BroadlinkRemote(name, unique_id, device, code_storage,
                             flag_storage)

    connected, loaded = await asyncio.gather(device.async_connect(),
                                             remote.async_load_storage_files())
    if not connected:
        hass.data[DOMAIN][COMPONENT].remove(unique_id)
        raise PlatformNotReady
    if not loaded:
        _LOGGER.error("Failed to set up %s", unique_id)
        hass.data[DOMAIN][COMPONENT].remove(unique_id)
        return
    async_add_entities([remote], False)
Example #22
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the generic thermostat platform."""
    import broadlink
    ip_addr = config.get(CONF_HOST)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))

    name = config.get(CONF_NAME)
    sensor_entity_id = config.get(CONF_SENSOR)
    target_temp = config.get(CONF_TARGET_TEMP)
    target_fan = config.get(CONF_TARGET_FAN)

    broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, "")
    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device")
    async_add_devices([
        HitachiClimate(hass, name, target_temp, 'Low', 'off', broadlink_device,
                       sensor_entity_id)
    ])
Example #23
0
def broadlinkConnect():
    global device, isConnected

    try:
        if (Parameters["Mode3"] == 'RM2T' or Parameters["Mode3"] == 'RM2'):
            device = broadlink.rm(host=(Parameters["Address"], 80),
                                  mac=bytearray.fromhex(Parameters["Mode1"]),
                                  devtype=Parameters["Mode3"])
        elif (Parameters["Mode3"] == 'A1'):
            device = broadlink.a1(host=(Parameters["Address"], 80),
                                  mac=bytearray.fromhex(Parameters["Mode1"]),
                                  devtype=Parameters["Mode3"])
        elif (Parameters["Mode3"] == 'SP1'):
            device = broadlink.sp1(host=(Parameters["Address"], 80),
                                   mac=bytearray.fromhex(Parameters["Mode1"]),
                                   devtype=Parameters["Mode3"])
        elif (Parameters["Mode3"] == 'SP2' or Parameters["Mode3"] == 'SP3S'):
            device = broadlink.sp2(host=(Parameters["Address"], 80),
                                   mac=bytearray.fromhex(Parameters["Mode1"]),
                                   devtype=Parameters["Mode3"])
        elif (Parameters["Mode3"] == 'MP1'):
            device = broadlink.mp1(host=(Parameters["Address"], 80),
                                   mac=bytearray.fromhex(Parameters["Mode1"]),
                                   devtype=Parameters["Mode3"])
        else:
            device = 'unknown'
        device.auth()
        #device.host
        isConnected = True
        Domoticz.Log("Connected to Broadlink device: " +
                     str(Parameters["Address"]))
    except:
        Domoticz.Error("Error Connecting to Broadlink device...." +
                       str(Parameters["Address"]))
        isConnected = False
        return False

    return True
Example #24
0
def checkmod(modname):
    Sender = hvac_ir.get_sender(modname)
    if Sender is None:
        print("Unknown sender")
        exit(2)
    g = Sender()
    g.send(Sender.POWER_ON, Sender.MODE_HEAT, Sender.FAN_AUTO, 24,
           Sender.VDIR_SWING_DOWN, Sender.HDIR_SWING, False)
    durations = g.get_durations()

    # print(format_durations(durations))

    # Uncommend the following to send code over Broadlink:

    BROADLINK_IP = '192.168.0.10'
    BROADLINK_MAC = 'B4:43:0D:C3:0B:2B'
    #
    bl = convert_bl(durations)
    print(binascii.b2a_hex(bl))
    mac = binascii.unhexlify(BROADLINK_MAC.encode().replace(b':', b''))
    dev = broadlink.rm((BROADLINK_IP, 80), mac, 0x272a)
    dev.auth()
    dev.send_data(bl)
Example #25
0
async def async_setup_platform(hass,
                               config,
                               async_add_devices,
                               discovery_info=None):
    """Set up platform."""
    import broadlink

    host = (config.get(CONF_HOST),
            config.get(CONF_PORT))
    mac = get_broadlink_mac(config.get(CONF_MAC))

    link = broadlink.rm(
        host,
        mac,
        None)

    try:
        await hass.async_add_job(link.auth)
    except socket.timeout:
        _LOGGER.warning("Timeout trying to authenticate to broadlink")
        raise PlatformNotReady

    async_add_devices([BroadlinkRM(link, config)])
Example #26
0
yaml = YAML()
system_dictionary = yaml.load(content)

content = open(data_dir + "/tc2.yml", "r").read()
yaml = YAML()
mapping_dictionary = yaml.load(content)

code = mapping_dictionary["mapping_dictionary"][switch_item_name][
    switch_item_status]

operations = ""
operations += "start"

try:
    device = broadlink.rm(host=(system_dictionary["HW_RMPro"], 80),
                          mac=bytearray.fromhex(
                              system_dictionary["HW_RMPro_MAC"]),
                          devtype="rm")

    operations += ", connecting"
    device.auth()
    operations += ", connected"
    device.host
    decode_hex = codecs.getdecoder("hex_codec")
    device.send_data(decode_hex(code)[0])
    operations += ", ==sent=="
except Exception as e:
    print(e)

print("{}: {}".format(switch_item_name, operations))
Example #27
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Broadlink switches."""

    devices = config.get(CONF_SWITCHES)
    slots = config.get("slots", {})
    host = config.get(CONF_HOST)
    mac_addr = config.get(CONF_MAC)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    model = config[CONF_TYPE]
    retry_times = config.get(CONF_RETRY)

    def generate_rm_switches(switches, broadlink_device):
        """Generate RM switches."""
        return [
            BroadlinkRMSwitch(
                object_id,
                config.get(CONF_FRIENDLY_NAME, object_id),
                broadlink_device,
                config.get(CONF_COMMAND_ON),
                config.get(CONF_COMMAND_OFF),
                retry_times,
            ) for object_id, config in switches.items()
        ]

    def get_mp1_slot_name(switch_friendly_name, slot):
        """Get slot name."""
        if not slots[f"slot_{slot}"]:
            return f"{switch_friendly_name} slot {slot}"
        return slots[f"slot_{slot}"]

    if model in RM_TYPES:
        broadlink_device = blk.rm((host, DEFAULT_PORT), mac_addr, None)
        hass.add_job(async_setup_service, hass, host, broadlink_device)
        switches = generate_rm_switches(devices, broadlink_device)
    elif model in RM4_TYPES:
        broadlink_device = blk.rm4((host, DEFAULT_PORT), mac_addr, None)
        hass.add_job(async_setup_service, hass, host, broadlink_device)
        switches = generate_rm_switches(devices, broadlink_device)
    elif model in SP1_TYPES:
        broadlink_device = blk.sp1((host, DEFAULT_PORT), mac_addr, None)
        switches = [
            BroadlinkSP1Switch(friendly_name, broadlink_device, retry_times)
        ]
    elif model in SP2_TYPES:
        broadlink_device = blk.sp2((host, DEFAULT_PORT), mac_addr, None)
        switches = [
            BroadlinkSP2Switch(friendly_name, broadlink_device, retry_times)
        ]
    elif model in MP1_TYPES:
        switches = []
        broadlink_device = blk.mp1((host, DEFAULT_PORT), mac_addr, None)
        parent_device = BroadlinkMP1Switch(broadlink_device, retry_times)
        for i in range(1, 5):
            slot = BroadlinkMP1Slot(
                get_mp1_slot_name(friendly_name, i),
                broadlink_device,
                i,
                parent_device,
                retry_times,
            )
            switches.append(slot)

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except OSError:
        _LOGGER.error("Failed to connect to device")

    add_entities(switches)
Example #28
0
def get_device(cf):
    device_type = cf.get('device_type', 'lookup')
    if device_type == 'lookup':
        local_address = cf.get('local_address', None)
        lookup_timeout = cf.get('lookup_timeout', 20)
        devices = broadlink.discover(timeout=lookup_timeout) if local_address is None else \
            broadlink.discover(timeout=lookup_timeout, local_ip_address=local_address)
        if len(devices) == 0:
            logging.error('No Broadlink device found')
            sys.exit(2)
        if len(devices) > 1:
            logging.error('More than one Broadlink device found (' +
                          ', '.join([
                              d.type + '/' + d.host[0] + '/' +
                              ':'.join(format(s, '02x') for s in d.mac[::-1])
                              for d in devices
                          ]) + ')')
            sys.exit(2)
        return configure_device(devices[0], topic_prefix)
    elif device_type == 'multiple_lookup':
        local_address = cf.get('local_address', None)
        lookup_timeout = cf.get('lookup_timeout', 20)
        devices = broadlink.discover(timeout=lookup_timeout) if local_address is None else \
            broadlink.discover(timeout=lookup_timeout, local_ip_address=local_address)
        if len(devices) == 0:
            logging.error('No Broadlink devices found')
            sys.exit(2)
        mqtt_multiple_prefix_format = cf.get('mqtt_multiple_subprefix_format',
                                             None)
        devices_dict = {}
        for device in devices:
            mqtt_subprefix = mqtt_multiple_prefix_format.format(
                type=device.type,
                host=device.host[0],
                mac='_'.join(format(s, '02x') for s in device.mac),
                mac_nic='_'.join(format(s, '02x') for s in device.mac[3::]))
            device = configure_device(device, topic_prefix + mqtt_subprefix)
            devices_dict[mqtt_subprefix] = device
        return devices_dict
    elif device_type == 'test':
        return configure_device(TestDevice(cf), topic_prefix)
    else:
        host = (cf.get('device_host'), 80)
        mac = bytearray.fromhex(cf.get('device_mac').replace(':', ' '))
        if device_type == 'rm':
            device = broadlink.rm(host=host, mac=mac, devtype=0x2712)
        elif device_type == 'rm4':
            device = broadlink.rm4(host=host, mac=mac, devtype=0x51da)
        elif device_type == 'sp1':
            device = broadlink.sp1(host=host, mac=mac, devtype=0)
        elif device_type == 'sp2':
            device = broadlink.sp2(host=host, mac=mac, devtype=0x2711)
        elif device_type == 'a1':
            device = broadlink.a1(host=host, mac=mac, devtype=0x2714)
        elif device_type == 'mp1':
            device = broadlink.mp1(host=host, mac=mac, devtype=0x4EB5)
        elif device_type == 'dooya':
            device = broadlink.dooya(host=host, mac=mac, devtype=0x4E4D)
        elif device_type == 'bg1':
            device = broadlink.bg1(host=host, mac=mac, devtype=0x51E3)
        else:
            logging.error('Incorrect device configured: ' + device_type)
            sys.exit(2)
        return configure_device(device, topic_prefix)
Example #29
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Broadlink switches."""

    devices = config.get(CONF_SWITCHES)
    slots = config.get("slots", {})
    ip_addr = config.get(CONF_HOST)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b":", b""))
    switch_type = config.get(CONF_TYPE)
    retry_times = config.get(CONF_RETRY)

    def _get_mp1_slot_name(switch_friendly_name, slot):
        """Get slot name."""
        if not slots[f"slot_{slot}"]:
            return f"{switch_friendly_name} slot {slot}"
        return slots[f"slot_{slot}"]

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
        hass.add_job(async_setup_service, hass, ip_addr, broadlink_device)

        switches = []
        for object_id, device_config in devices.items():
            switches.append(
                BroadlinkRMSwitch(
                    object_id,
                    device_config.get(CONF_FRIENDLY_NAME, object_id),
                    broadlink_device,
                    device_config.get(CONF_COMMAND_ON),
                    device_config.get(CONF_COMMAND_OFF),
                    retry_times,
                ))
    elif switch_type in SP1_TYPES:
        broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr, None)
        switches = [
            BroadlinkSP1Switch(friendly_name, broadlink_device, retry_times)
        ]
    elif switch_type in SP2_TYPES:
        broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr, None)
        switches = [
            BroadlinkSP2Switch(friendly_name, broadlink_device, retry_times)
        ]
    elif switch_type in MP1_TYPES:
        switches = []
        broadlink_device = broadlink.mp1((ip_addr, 80), mac_addr, None)
        parent_device = BroadlinkMP1Switch(broadlink_device, retry_times)
        for i in range(1, 5):
            slot = BroadlinkMP1Slot(
                _get_mp1_slot_name(friendly_name, i),
                broadlink_device,
                i,
                parent_device,
                retry_times,
            )
            switches.append(slot)

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except OSError:
        _LOGGER.error("Failed to connect to device")

    add_entities(switches)
Example #30
0
import sys

str_ip = "192.168.0.36"
str_mac = "34 ea 34 e3 a5 68"

try:
    fileName = sys.argv[1]
except IndexError:
    fileName = 'null'

if fileName == 'null':
    print "Error - no file name parameter suffixed"
    sys.exit()
else:

    device = broadlink.rm(host=(str_ip, 80), mac=bytearray.fromhex(str_mac))

print "Connecting to Broadlink device...."
device.auth()
time.sleep(1)
print "Connected...."
time.sleep(1)
device.host

file = open(fileName, 'r')

myhex = file.read()

device.send_data(myhex.decode('hex'))
print "Code Sent...."
    RealMACAddress = netaddr.EUI(RealMACAddress)

if DeviceName.strip() != '':
    RealTimeout = DeviceTimeout.strip()
elif AlternativeTimeout.strip() != '':
    RealTimeout = AlternativeTimeout.strip()
else:
    RealTimeout = Settings.Timeout

if RealTimeout.strip() == '':
    print('Timeout must exist in BlackBeanControl.ini or it should be entered as a command line parameter')
    sys.exit(2)
else:
    RealTimeout = int(RealTimeout.strip())    

RM3Device = broadlink.rm((RealIPAddress, RealPort), RealMACAddress)
RM3Device.auth()

if ReKeyCommand:
    if SettingsFile.has_option('Commands', SentCommand):
        CommandFromSettings = SettingsFile.get('Commands', SentCommand)

        if CommandFromSettings[0:4] != '2600':
            RM3Key = RM3Device.key
            RM3IV = RM3Device.iv

            DecodedCommand = binascii.unhexlify(CommandFromSettings)
            AESEncryption = AES.new(str(RM3Key), AES.MODE_CBC, str(RM3IV))
            EncodedCommand = AESEncryption.encrypt(str(DecodedCommand))
            FinalCommand = EncodedCommand[0x04:]
            EncodedCommand = FinalCommand.encode('hex')
Example #32
0
                mac_nic='_'.join(format(s, '02x') for s in device.mac[2::-1]))
            print(device,topic_prefix, mqtt_subprefix)
=======
                mac='_'.join(format(s, '02x') for s in device.mac),
                mac_nic='_'.join(format(s, '02x') for s in device.mac[3::]))
>>>>>>> upstream2/master
            device = configure_device(device, topic_prefix + mqtt_subprefix)
            devices_dict[mqtt_subprefix] = device
        return devices_dict
    elif device_type == 'test':
        return configure_device(TestDevice(cf), topic_prefix)
    else:
        host = (cf.get('device_host'), 80)
        mac = bytearray.fromhex(cf.get('device_mac').replace(':', ' '))
        if device_type == 'rm':
            device = broadlink.rm(host=host, mac=mac, devtype=0x2712)
        elif device_type == 'rm4':
            device = broadlink.rm4(host=host, mac=mac, devtype=0x51da)
        elif device_type == 'sp1':
            device = broadlink.sp1(host=host, mac=mac, devtype=0)
        elif device_type == 'sp2':
            device = broadlink.sp2(host=host, mac=mac, devtype=0x2711)
        elif device_type == 'a1':
            device = broadlink.a1(host=host, mac=mac, devtype=0x2714)
        elif device_type == 'mp1':
            device = broadlink.mp1(host=host, mac=mac, devtype=0x4EB5)
        elif device_type == 'dooya':
            device = broadlink.dooya(host=host, mac=mac, devtype=0x4E4D)
        elif device_type == 'bg1':
            device = broadlink.bg1(host=host, mac=mac, devtype=0x51E3)
        else:
Example #33
0
def get_device(cf, devices_dictionary={}):
    device_type = cf.get('device_type', 'lookup')
    if device_type == 'lookup':
        local_address = cf.get('local_address', None)
        lookup_timeout = cf.get('lookup_timeout', 20)
        devices = broadlink.discover(timeout=lookup_timeout) if local_address is None else \
            broadlink.discover(timeout=lookup_timeout, local_ip_address=local_address)
        if len(devices) == 0:
            logging.error('No Broadlink device found')
            sys.exit(2)
        if len(devices) > 1:
            logging.error('More than one Broadlink device found (' +
                          ', '.join([
                              d.type + '/' + d.host[0] + '/' +
                              ':'.join(format(s, '02x') for s in d.mac[::-1])
                              for d in devices
                          ]) + ')')
            sys.exit(2)
        return configure_device(devices[0], topic_prefix)
    elif device_type == 'multiple_lookup':
        local_address = cf.get('local_address', None)
        lookup_timeout = cf.get('lookup_timeout', 20)
        devices = broadlink.discover(timeout=lookup_timeout) if local_address is None else \
            broadlink.discover(timeout=lookup_timeout, local_ip_address=local_address)
        if len(devices) == 0:
            logging.error('No Broadlink devices found')
            sys.exit(2)
        mqtt_multiple_prefix_format = cf.get('mqtt_multiple_subprefix_format',
                                             None)
        devices_dict = {}
        for device in devices:
            mqtt_subprefix = mqtt_multiple_prefix_format.format(
                type=device.type,
                host=device.host[0],
                mac='_'.join(format(s, '02x') for s in device.mac[::-1]),
                mac_nic='_'.join(format(s, '02x') for s in device.mac[2::-1]))
            device = configure_device(device, topic_prefix + mqtt_subprefix)
            devices_dict[mqtt_subprefix] = device
        return devices_dict
    elif device_type == 'test':
        return configure_device(TestDevice(cf), topic_prefix)
    elif device_type == 'dict':
        global device_rescan_required
        device_rescan_required = False
        devices_list = json.loads(cf.get('devices_dict', '[]'))
        mqtt_multiple_prefix_format = cf.get('mqtt_multiple_subprefix_format',
                                             None)
        for device in devices_list:
            if pingOk(sHost=device['host'], count=3):
                mac = bytearray.fromhex(device['mac'].replace(':', ' '))[::-1]
                host = (device['host'], 80)
                init_func = getattr(broadlink, device['class'])
                deviceObj = init_func(host=host,
                                      mac=mac,
                                      devtype=int(device['devtype'], 0))
                mqtt_subprefix = mqtt_multiple_prefix_format.format(
                    type=deviceObj.type,
                    host=deviceObj.host[0],
                    mac='_'.join(
                        format(s, '02x') for s in deviceObj.mac[::-1]),
                    mac_nic='_'.join(
                        format(s, '02x') for s in deviceObj.mac[2::-1]))
                if mqtt_subprefix not in devices_dictionary:
                    device_configured = configure_device(
                        deviceObj, topic_prefix + mqtt_subprefix)
                    devices_dictionary[mqtt_subprefix] = device_configured
                    print("Type: %s, host: %s, MQTT subprefix: %s" %
                          (deviceObj.type, deviceObj.host, mqtt_subprefix))
        if len(devices_list) != len(devices_dictionary):
            device_rescan_required = True
            logging.warning(
                'Less devices are found than expected. Rescan is required.')
        return devices_dictionary

    else:
        host = (cf.get('device_host'), 80)
        mac = bytearray.fromhex(cf.get('device_mac').replace(':', ' '))
        if device_type == 'rm':
            device = broadlink.rm(host=host, mac=mac, devtype=0x2712)
        elif device_type == 'rm4':
            device = broadlink.rm4(host=host, mac=mac, devtype=0x51da)
        elif device_type == 'sp1':
            device = broadlink.sp1(host=host, mac=mac, devtype=0)
        elif device_type == 'sp2':
            device = broadlink.sp2(host=host, mac=mac, devtype=0x2711)
        elif device_type == 'a1':
            device = broadlink.a1(host=host, mac=mac, devtype=0x2714)
        elif device_type == 'mp1':
            device = broadlink.mp1(host=host, mac=mac, devtype=0x4EB5)
        elif device_type == 'dooya':
            device = broadlink.dooya(host=host, mac=mac, devtype=0x4E4D)
        elif device_type == 'bg1':
            device = broadlink.bg1(host=host, mac=mac, devtype=0x51E3)
        elif device_type == 'SmartBulb':
            device = broadlink.lb1(host=host, mac=mac, devtype=0x60c8)
        else:
            logging.error('Incorrect device configured: ' + device_type)
            sys.exit(2)
        return configure_device(device, topic_prefix)
def execute_command(
    SentCommand, 
    DeviceName='',
    ReKeyCommand=False, 
    AlternativeIPAddress='',
    AlternativePort='',
    AlternativeMACAddress='',
    AlternativeTimeout=''    
    ):
    if SentCommand == '':
        print('Command name parameter is mandatory')
        return 2

    if SentCommand == 'DISCOVER':
        print('Scanning network for Broadlink devices ... ')

        mydevices = broadlink.discover(timeout=5)
        print(('Found ' + str(len(mydevices )) + ' broadlink device(s)'))
        time.sleep(1)
        for index, item in enumerate(mydevices):
            mydevices[index].auth()

        m = re.match(r"\('([0-9.]+)', ([0-9]+)", str(mydevices[index].host))
        ipadd = m.group(1)
        port = m.group(2)

        macadd = str(''.join(format(x, '02x') for x in mydevices[index].mac[::-1]))
        macadd = macadd[:2] + ":" + macadd[2:4] + ":" + macadd[4:6] + ":" + macadd[6:8] + ":" + macadd[8:10] + ":" + macadd[10:12]

        print(('Device ' + str(index + 1) +':\nIPAddress = ' + ipadd + '\nPort = ' + port + '\nMACAddress = ' + macadd))
        return

    if (DeviceName != '') and (
        (AlternativeIPAddress != '') or 
        (AlternativePort != '') or 
        (AlternativeMACAddress != '') or 
        (AlternativeTimeout != '')
    ):
        print('Device name parameter can not be used in conjunction with IP Address/Port/MAC Address/Timeout parameters')
        return 2

    if (
        (
            (AlternativeIPAddress != '') or 
            (AlternativePort != '') or 
            (AlternativeMACAddress != '') or 
            (AlternativeTimeout != '')
        ) and (
            (AlternativeIPAddress == '') or 
            (AlternativePort == '') or 
            (AlternativeMACAddress == '') or 
            (AlternativeTimeout == '')
        )
    ):
        print('IP Address, Port, MAC Address and Timeout parameters can not be used separately')
        return 2

    if DeviceName != '':
        if SettingsFile.has_section(DeviceName):
            if SettingsFile.has_option(DeviceName, 'IPAddress'):
                DeviceIPAddress = SettingsFile.get(DeviceName, 'IPAddress')
            else:
                DeviceIPAddress = ''

            if SettingsFile.has_option(DeviceName, 'Port'):
                DevicePort = SettingsFile.get(DeviceName, 'Port')
            else:
                DevicePort = ''

            if SettingsFile.has_option(DeviceName, 'MACAddress'):
                DeviceMACAddress = SettingsFile.get(DeviceName, 'MACAddress')
            else:
                DeviceMACAddress = ''

            if SettingsFile.has_option(DeviceName, 'Timeout'):
                DeviceTimeout = SettingsFile.get(DeviceName, 'Timeout')
            else:
                DeviceTimeout = ''
        else:
            print('Device does not exist in BlackBeanControl.ini')
            return 2

    if (DeviceName != '') and (DeviceIPAddress == ''):
        print('IP address must exist in BlackBeanControl.ini for the selected device')
        return 2

    if (DeviceName != '') and (DevicePort == ''):
        print('Port must exist in BlackBeanControl.ini for the selected device')
        return 2

    if (DeviceName != '') and (DeviceMACAddress == ''):
        print('MAC address must exist in BlackBeanControl.ini for the selected device')
        return 2

    if (DeviceName != '') and (DeviceTimeout == ''):
        print('Timeout must exist in BlackBeanControl.ini for the selected device')
        return 2

    if DeviceName != '':
        RealIPAddress = DeviceIPAddress
    elif AlternativeIPAddress != '':
        RealIPAddress = AlternativeIPAddress
    else:
        RealIPAddress = Settings.IPAddress

    if RealIPAddress == '':
        print('IP address must exist in BlackBeanControl.ini or it should be entered as a command line parameter')
        return 2

    if DeviceName != '':
        RealPort = DevicePort
    elif AlternativePort != '':
        RealPort = AlternativePort
    else:
        RealPort = Settings.Port

    if RealPort == '':
        print('Port must exist in BlackBeanControl.ini or it should be entered as a command line parameter')
        return 2
    else:
        RealPort = int(RealPort)

    if DeviceName != '':
        RealMACAddress = DeviceMACAddress
    elif AlternativeMACAddress != '':
        RealMACAddress = AlternativeMACAddress
    else:
        RealMACAddress = Settings.MACAddress

    if RealMACAddress == '':
        print('MAC address must exist in BlackBeanControl.ini or it should be entered as a command line parameter')
        return 2
    else:
        RealMACAddress = netaddr.EUI(RealMACAddress)

    if DeviceName != '':
        RealTimeout = DeviceTimeout
    elif AlternativeTimeout != '':
        RealTimeout = AlternativeTimeout
    else:
        RealTimeout = Settings.Timeout

    if RealTimeout == '':
        print('Timeout must exist in BlackBeanControl.ini or it should be entered as a command line parameter')
        return 2
    else:
        RealTimeout = int(RealTimeout)

    RM3Device = broadlink.rm((RealIPAddress, RealPort), RealMACAddress)
    RM3Device.auth()

    if ReKeyCommand:
        if SettingsFile.has_option('Commands', SentCommand):
            CommandFromSettings = SettingsFile.get('Commands', SentCommand)

            if CommandFromSettings[0:4] != '2600':
                RM3Key = RM3Device.key
                RM3IV = RM3Device.iv

                DecodedCommand = binascii.unhexlify(CommandFromSettings)
                AESEncryption = AES.new(str(RM3Key), AES.MODE_CBC, str(RM3IV))
                EncodedCommand = AESEncryption.encrypt(str(DecodedCommand))
                FinalCommand = EncodedCommand[0x04:]
                EncodedCommand = binascii.hexlify(FinalCommand).decode("ascii")

                BlackBeanControlIniFile = open(path.join(Settings.ApplicationDir, 'BlackBeanControl.ini'), 'w')
                SettingsFile.set('Commands', SentCommand, EncodedCommand)
                SettingsFile.write(BlackBeanControlIniFile)
                BlackBeanControlIniFile.close()
                sys.exit()
            else:
                print("Command appears to already be re-keyed.")
                return 2
        else:
            print("Command not found in ini file for re-keying.")
            return 2


    if SettingsFile.has_option('Commands', SentCommand):
        CommandFromSettings = SettingsFile.get('Commands', SentCommand)
    else:
        CommandFromSettings = ''

    if CommandFromSettings != '':
        DecodedCommand = binascii.unhexlify(CommandFromSettings)
        RM3Device.send_data(DecodedCommand)
    else:
        RM3Device.enter_learning()
        time.sleep(RealTimeout)
        LearnedCommand = RM3Device.check_data()

        if LearnedCommand is None:
            print('Command not received')
            sys.exit()

        print(LearnedCommand)
        # EncodedCommand = LearnedCommand.encode('hex')
        EncodedCommand = binascii.hexlify(LearnedCommand).decode("ascii")
        print(EncodedCommand)

        if EncodedCommand:
            BlackBeanControlIniFile = open(path.join(Settings.ApplicationDir, 'BlackBeanControl.ini'), 'w')
            SettingsFile.set('Commands', SentCommand, EncodedCommand)
            SettingsFile.write(BlackBeanControlIniFile)
            BlackBeanControlIniFile.close()
            print('Set command {0}'.format(SentCommand))
Example #35
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Broadlink switches."""
    import broadlink
    devices = config.get(CONF_SWITCHES)
    slots = config.get('slots', {})
    ip_addr = config.get(CONF_HOST)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    switch_type = config.get(CONF_TYPE)

    async def _learn_command(call):
        """Handle a learn command."""
        try:
            auth = await hass.async_add_job(broadlink_device.auth)
        except socket.timeout:
            _LOGGER.error("Failed to connect to device, timeout")
            return
        if not auth:
            _LOGGER.error("Failed to connect to device")
            return

        await hass.async_add_job(broadlink_device.enter_learning)

        _LOGGER.info("Press the key you want Home Assistant to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=20):
            packet = await hass.async_add_job(
                broadlink_device.check_data)
            if packet:
                log_msg = "Received packet is: {}".\
                          format(b64encode(packet).decode('utf8'))
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title='Broadlink switch')
                return
            await asyncio.sleep(1, loop=hass.loop)
        _LOGGER.error("Did not received any signal")
        hass.components.persistent_notification.async_create(
            "Did not received any signal", title='Broadlink switch')

    async def _send_packet(call):
        """Send a packet."""
        packets = call.data.get('packet', [])
        for packet in packets:
            for retry in range(DEFAULT_RETRY):
                try:
                    extra = len(packet) % 4
                    if extra > 0:
                        packet = packet + ('=' * (4 - extra))
                    payload = b64decode(packet)
                    await hass.async_add_job(
                        broadlink_device.send_data, payload)
                    break
                except (socket.timeout, ValueError):
                    try:
                        await hass.async_add_job(
                            broadlink_device.auth)
                    except socket.timeout:
                        if retry == DEFAULT_RETRY-1:
                            _LOGGER.error("Failed to send packet to device")

    def _get_mp1_slot_name(switch_friendly_name, slot):
        """Get slot name."""
        if not slots['slot_{}'.format(slot)]:
            return '{} slot {}'.format(switch_friendly_name, slot)
        return slots['slot_{}'.format(slot)]

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
        hass.services.register(DOMAIN, SERVICE_LEARN + '_' +
                               slugify(ip_addr.replace('.', '_')),
                               _learn_command)
        hass.services.register(DOMAIN, SERVICE_SEND + '_' +
                               slugify(ip_addr.replace('.', '_')),
                               _send_packet,
                               vol.Schema({'packet': cv.ensure_list}))
        switches = []
        for object_id, device_config in devices.items():
            switches.append(
                BroadlinkRMSwitch(
                    object_id,
                    device_config.get(CONF_FRIENDLY_NAME, object_id),
                    broadlink_device,
                    device_config.get(CONF_COMMAND_ON),
                    device_config.get(CONF_COMMAND_OFF)
                )
            )
    elif switch_type in SP1_TYPES:
        broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr, None)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif switch_type in SP2_TYPES:
        broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr, None)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
    elif switch_type in MP1_TYPES:
        switches = []
        broadlink_device = broadlink.mp1((ip_addr, 80), mac_addr, None)
        parent_device = BroadlinkMP1Switch(broadlink_device)
        for i in range(1, 5):
            slot = BroadlinkMP1Slot(
                _get_mp1_slot_name(friendly_name, i),
                broadlink_device, i, parent_device)
            switches.append(slot)

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device")

    add_entities(switches)
Example #36
0
with open(os.path.join(__location__,'config.json')) as data_file:
    config = json.load(data_file)

print "Device IP: " + config['str_ip'] +" Mac : " + config['str_mac'] +" !"

try:
    fileName = sys.argv[1]
except IndexError:
    fileName = 'null'

if fileName == 'null':
   print "Error - no file name parameter suffixed"
   sys.exit()
else:
   device = broadlink.rm(host=(config['str_ip'],80), mac=bytearray.fromhex(config['str_mac']))

print "Connecting to Broadlink device...."
device.auth()
time.sleep(1)
print "Connected...."
time.sleep(1)
device.host
print os.path.join(__location__,fileName)
file = open(os.path.join(__location__,fileName), 'r')

myhex = file.read()

device.send_data(myhex.decode('hex'))
print "Code Sent...."
Example #37
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up Broadlink switches."""
    import broadlink
    devices = config.get(CONF_SWITCHES, {})
    ip_addr = config.get(CONF_HOST)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    switch_type = config.get(CONF_TYPE)

    @asyncio.coroutine
    def _learn_command(call):
        try:
            auth = yield from hass.async_add_job(broadlink_device.auth)
        except socket.timeout:
            _LOGGER.error("Failed to connect to device, timeout")
            return
        if not auth:
            _LOGGER.error("Failed to connect to device")
            return

        yield from hass.async_add_job(broadlink_device.enter_learning)

        _LOGGER.info("Press the key you want HASS to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=20):
            packet = yield from hass.async_add_job(
                broadlink_device.check_data)
            if packet:
                log_msg = "Recieved packet is: {}".\
                          format(b64encode(packet).decode('utf8'))
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title='Broadlink switch')
                return
            yield from asyncio.sleep(1, loop=hass.loop)
        _LOGGER.error("Did not received any signal")
        hass.components.persistent_notification.async_create(
            "Did not received any signal", title='Broadlink switch')

    @asyncio.coroutine
    def _send_packet(call):
        packets = call.data.get('packet', [])
        for packet in packets:
            for retry in range(DEFAULT_RETRY):
                try:
                    payload = b64decode(packet)
                    yield from hass.async_add_job(
                        broadlink_device.send_data, payload)
                    break
                except (socket.timeout, ValueError):
                    try:
                        yield from hass.async_add_job(
                            broadlink_device.auth)
                    except socket.timeout:
                        if retry == DEFAULT_RETRY-1:
                            _LOGGER.error("Failed to send packet to device")

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
        hass.services.register(DOMAIN, SERVICE_LEARN + '_' +
                               ip_addr.replace('.', '_'), _learn_command)
        hass.services.register(DOMAIN, SERVICE_SEND + '_' +
                               ip_addr.replace('.', '_'), _send_packet)
        switches = []
        for object_id, device_config in devices.items():
            switches.append(
                BroadlinkRMSwitch(
                    device_config.get(CONF_FRIENDLY_NAME, object_id),
                    broadlink_device,
                    device_config.get(CONF_COMMAND_ON),
                    device_config.get(CONF_COMMAND_OFF)
                )
            )
    elif switch_type in SP1_TYPES:
        broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif switch_type in SP2_TYPES:
        broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device")

    add_devices(switches)
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up Broadlink switches."""
    import broadlink
    devices = config.get(CONF_SWITCHES, {})
    ip_addr = config.get(CONF_HOST)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    switch_type = config.get(CONF_TYPE)

    persistent_notification = loader.get_component('persistent_notification')

    @asyncio.coroutine
    def _learn_command(call):
        try:
            auth = yield from hass.async_add_job(broadlink_device.auth)
        except socket.timeout:
            _LOGGER.error("Failed to connect to device, timeout")
            return
        if not auth:
            _LOGGER.error("Failed to connect to device")
            return

        yield from hass.async_add_job(broadlink_device.enter_learning)

        _LOGGER.info("Press the key you want HASS to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=20):
            packet = yield from hass.async_add_job(broadlink_device.check_data)
            if packet:
                log_msg = "Recieved packet is: {}".\
                          format(b64encode(packet).decode('utf8'))
                _LOGGER.info(log_msg)
                persistent_notification.async_create(hass,
                                                     log_msg,
                                                     title='Broadlink switch')
                return
            yield from asyncio.sleep(1, loop=hass.loop)
        _LOGGER.error("Did not received any signal")
        persistent_notification.async_create(hass,
                                             "Did not received any signal",
                                             title='Broadlink switch')

    @asyncio.coroutine
    def _send_packet(call):
        packets = call.data.get('packet', [])
        for packet in packets:
            for retry in range(DEFAULT_RETRY):
                try:
                    payload = b64decode(packet)
                    yield from hass.async_add_job(broadlink_device.send_data,
                                                  payload)
                    break
                except (socket.timeout, ValueError):
                    try:
                        yield from hass.async_add_job(broadlink_device.auth)
                    except socket.timeout:
                        if retry == DEFAULT_RETRY - 1:
                            _LOGGER.error("Failed to send packet to device")

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
        hass.services.register(DOMAIN,
                               SERVICE_LEARN + '_' + ip_addr.replace('.', '_'),
                               _learn_command)
        hass.services.register(DOMAIN,
                               SERVICE_SEND + '_' + ip_addr.replace('.', '_'),
                               _send_packet)
        switches = []
        for object_id, device_config in devices.items():
            switches.append(
                BroadlinkRMSwitch(
                    device_config.get(CONF_FRIENDLY_NAME, object_id),
                    broadlink_device, device_config.get(CONF_COMMAND_ON),
                    device_config.get(CONF_COMMAND_OFF)))
    elif switch_type in SP1_TYPES:
        broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif switch_type in SP2_TYPES:
        broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device")

    add_devices(switches)
Example #39
0
import broadlink, sys, time

ip = sys.argv[1]
macaddr = sys.argv[2]
state = sys.argv[3]

try:
    broadlink.rm(host=(ip, 80), mac=bytearray.fromhex(macaddr))
    # it mean that is not a rm device
    if (state != "3"):
        device = broadlink.sp2(host=(ip, 80), mac=bytearray.fromhex(macaddr))
        device.auth()
        time.sleep(3)

        # Add option to only check power without change it
        if state == "2":
            print device.check_power()
        elif state == "1":
            device.set_power(True)
            print "on"
        elif state == "0":
            device.set_power(False)
            print "off"
    else:
        device = broadlink.rm(host=(ip, 80), mac=bytearray.fromhex(macaddr))
        device.auth()
        time.sleep(3)

        ir_value = sys.argv[4]

        if ir_value != "CheckAlive":
    RealMACAddress = netaddr.EUI(RealMACAddress)

if DeviceName.strip() != '':
    RealTimeout = DeviceTimeout.strip()
elif AlternativeTimeout.strip() != '':
    RealTimeout = AlternativeTimeout.strip()
else:
    RealTimeout = Settings.Timeout

if RealTimeout.strip() == '':
    print('Timeout must exist in BlackBeanControl.ini or it should be entered as a command line parameter')
    sys.exit(2)
else:
    RealTimeout = int(RealTimeout.strip())    

RM3Device = broadlink.rm((RealIPAddress, RealPort), RealMACAddress)
RM3Device.auth()

RM3Key = RM3Device.key
RM3IV = RM3Device.iv

if SettingsFile.has_option('Commands', SentCommand):
    CommandFromSettings = SettingsFile.get('Commands', SentCommand)
else:
    CommandFromSettings = ''

if CommandFromSettings.strip() != '':
    DecodedCommand = binascii.unhexlify(CommandFromSettings)

    AESEncryption = AES.new(str(RM3Key), AES.MODE_CBC, str(RM3IV))
    EncodedCommand = AESEncryption.encrypt(str(DecodedCommand))
Example #41
0
#!/usr/bin/python
import broadlink
import time
import sys

device = broadlink.rm(host=("ip_of_broadlink_rm", 80),
                      mac=bytearray.fromhex("mac_address_of_broadlink_rm"))
device.auth()
device.host

myhex = "get_your_hex_code"

device.send_data(myhex.decode('hex'))
Example #42
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Broadlink switches."""
    import broadlink
    devices = config.get(CONF_SWITCHES)
    slots = config.get('slots', {})
    ip_addr = config.get(CONF_HOST)
    friendly_name = config.get(CONF_FRIENDLY_NAME)
    mac_addr = binascii.unhexlify(
        config.get(CONF_MAC).encode().replace(b':', b''))
    switch_type = config.get(CONF_TYPE)

    @asyncio.coroutine
    def _learn_command(call):
        """Handle a learn command."""
        try:
            auth = yield from hass.async_add_job(broadlink_device.auth)
        except socket.timeout:
            _LOGGER.error("Failed to connect to device, timeout")
            return
        if not auth:
            _LOGGER.error("Failed to connect to device")
            return

        yield from hass.async_add_job(broadlink_device.enter_learning)

        _LOGGER.info("Press the key you want Home Assistant to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=20):
            packet = yield from hass.async_add_job(broadlink_device.check_data)
            if packet:
                log_msg = "Received packet is: {}".\
                          format(b64encode(packet).decode('utf8'))
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title='Broadlink switch')
                return
            yield from asyncio.sleep(1, loop=hass.loop)
        _LOGGER.error("Did not received any signal")
        hass.components.persistent_notification.async_create(
            "Did not received any signal", title='Broadlink switch')

    @asyncio.coroutine
    def _send_packet(call):
        """Send a packet."""
        packets = call.data.get('packet', [])
        for packet in packets:
            for retry in range(DEFAULT_RETRY):
                try:
                    extra = len(packet) % 4
                    if extra > 0:
                        packet = packet + ('=' * (4 - extra))
                    payload = b64decode(packet)
                    yield from hass.async_add_job(broadlink_device.send_data,
                                                  payload)
                    break
                except (socket.timeout, ValueError):
                    try:
                        yield from hass.async_add_job(broadlink_device.auth)
                    except socket.timeout:
                        if retry == DEFAULT_RETRY - 1:
                            _LOGGER.error("Failed to send packet to device")

    def _get_mp1_slot_name(switch_friendly_name, slot):
        """Get slot name."""
        if not slots['slot_{}'.format(slot)]:
            return '{} slot {}'.format(switch_friendly_name, slot)
        return slots['slot_{}'.format(slot)]

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
        hass.services.register(DOMAIN,
                               SERVICE_LEARN + '_' + ip_addr.replace('.', '_'),
                               _learn_command)
        hass.services.register(DOMAIN,
                               SERVICE_SEND + '_' + ip_addr.replace('.', '_'),
                               _send_packet,
                               vol.Schema({'packet': cv.ensure_list}))
        switches = []
        for object_id, device_config in devices.items():
            switches.append(
                BroadlinkRMSwitch(
                    device_config.get(CONF_FRIENDLY_NAME, object_id),
                    broadlink_device, device_config.get(CONF_COMMAND_ON),
                    device_config.get(CONF_COMMAND_OFF)))
    elif switch_type in SP1_TYPES:
        broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif switch_type in SP2_TYPES:
        broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
    elif switch_type in MP1_TYPES:
        switches = []
        broadlink_device = broadlink.mp1((ip_addr, 80), mac_addr)
        parent_device = BroadlinkMP1Switch(broadlink_device)
        for i in range(1, 5):
            slot = BroadlinkMP1Slot(_get_mp1_slot_name(friendly_name, i),
                                    broadlink_device, i, parent_device)
            switches.append(slot)

    broadlink_device.timeout = config.get(CONF_TIMEOUT)
    try:
        broadlink_device.auth()
    except socket.timeout:
        _LOGGER.error("Failed to connect to device")

    add_devices(switches)
Example #43
0
#--- Script ---#

try:
    fileName_0 = sys.argv[1]

except IndexError:
    fileName_0 = 'null'

if fileName_0 == 'null':
    print "Erreur - arguments non-valides"
    print "Utilisation: play_multi.py <délai> <fichier 1> <délai> <fichier 2>..."
    sys.exit()
else:

    device = broadlink.rm((ip, port), mac, timeout)
    arg_list = list(sys.argv)
    arg_numb = len(sys.argv)
    var_time = 1
    var_agmt = 2

    print "Connexion au module Broadlink..."
    device.auth()
    time.sleep(1)

    print "Connecté..."

    time.sleep(1)
    device.host

    while not var_time == arg_numb: