Ejemplo n.º 1
0
 def __init__(self):
     #print(mac_addr)
     devices = broadlink.discover(timeout=5)
     if len(devices) > 0:
         print("find dev")
         self.sw = broadlink.sp2(devices[0].host, devices[0].mac, None)
     else:
         print("auto discover faind , using default switch setting")
         mac_addr = binascii.unhexlify("78:0f:77:c8:b4:c0".encode().replace(
             b':', b''))
         self.sw = broadlink.sp2(('192.168.43.114', 80), mac_addr, None)
     if self.sw.auth() != True:
         print('认证失败,请重试')
Ejemplo n.º 2
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.host for d in devices]) + ')')
            sys.exit(2)
        return devices[0]
    else:
        host = (cf.get('device_host'), 80)
        mac = bytearray.fromhex(cf.get('device_mac').replace(':', ' '))
        if device_type == 'rm':
            return broadlink.rm(host=host, mac=mac)
        elif device_type == 'sp1':
            return broadlink.sp1(host=host, mac=mac)
        elif device_type == 'sp2':
            return broadlink.sp2(host=host, mac=mac)
        elif device_type == 'a1':
            return broadlink.a1(host=host, mac=mac)
        else:
            logging.error('Incorrect device configured: ' + device_type)
            sys.exit(2)
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
    def onStart(self):
        if Parameters["Mode6"] == "Debug":
            Domoticz.Debugging(1)

        try:
            self.delay = int(Parameters["Mode2"])
        except ValueError:
            self.delay = 1
        if (self.delay < 1): self.delay = 1

        if (len(Devices) == 0):
            Domoticz.Device(Name="SP2", Unit=1, Type=17, Switchtype=0,
                            Image=1).Create()
            Domoticz.Log("Devices SP2 created.")

        self.mySP2 = broadlink.sp2(host=(Parameters["Address"],
                                         int(Parameters["Port"])),
                                   mac=bytearray.fromhex(Parameters["Mode1"]))
        try:
            self.isFound = self.mySP2.auth()
            self.isConnected = True
        except socket.timeout:
            self.isConnected = False
            self.isFound = False

        if (self.isConnected):
            UpdateDevice(1, self.mySP2.check_power(), "")
        else:
            Domoticz.Error("Devices SP2 at " + Parameters["Address"] +
                           " not found")
        Domoticz.Heartbeat(60)
        Domoticz.Debug("onStart called. isConnected: " +
                       str(self.isConnected) + " isFound: " +
                       str(self.isFound))
        Domoticz.Debug("Delay is set " + str(self.delay) + " minutes")
Ejemplo n.º 5
0
def socket_get_energy(socket_list):
    result = {}
    for socket in socket_list:
        device = sp2((socket.ip, 80), socket.mac, devtype=38010)
        device.auth()
        result[socket.name] = device.get_energy()
    return result
Ejemplo n.º 6
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"]))
        elif (Parameters["Mode3"] == 'A1'):
            device = broadlink.a1(host=(Parameters["Address"], 80),
                                  mac=bytearray.fromhex(Parameters["Mode1"]))
        elif (Parameters["Mode3"] == 'SP1'):
            device = broadlink.sp1(host=(Parameters["Address"], 80),
                                   mac=bytearray.fromhex(Parameters["Mode1"]))
        elif (Parameters["Mode3"] == 'SP2' or Parameters["Mode3"] == 'SP3S'):
            device = broadlink.sp2(host=(Parameters["Address"], 80),
                                   mac=bytearray.fromhex(Parameters["Mode1"]))
        elif (Parameters["Mode3"] == 'MP1'):
            device = broadlink.mp1(host=(Parameters["Address"], 80),
                                   mac=bytearray.fromhex(Parameters["Mode1"]))
        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
Ejemplo n.º 7
0
def socket_get_state(socket_list):
    result = {}
    for socket in socket_list:
        if socket.editable:
            device = sp2((socket.ip, 80), socket.mac, devtype=38010)
            device.auth()
            result[socket.name] = device.check_power()
    return result
Ejemplo n.º 8
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[::-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)
    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 == '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)
        else:
            logging.error('Incorrect device configured: ' + device_type)
            sys.exit(2)
        return configure_device(device, topic_prefix)
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
    def get_SP2Device(self, deviceName, devIPAddress, devPort, devMACAddress):
        if len(self.path.split('/')) < 3:
            self.wfile.write("Failed")
            return True
        commandName = self.path.split('/')[2]

        device = broadlink.sp2((devIPAddress, devPort), devMACAddress)
        try:
            device.auth()
        except Exception, msg:
            self.wfile.write("Failed: Connect to device timed out")
            return True
 def __init__(self, interval, ip_addr, mac_addr, timeout):
     """Initialize the data object."""
     import broadlink
     self.data = None
     self._device = broadlink.sp2((ip_addr, 80), mac_addr)
     self._device.timeout = timeout
     self._schema = vol.Schema({
         vol.Optional('energy'): vol.Range(min=-0, max=3600)
         })
     self.update = Throttle(interval)(self._update)
     if not self._auth():
         _LOGGER.warning("Failed to connect to device")
Ejemplo n.º 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
Ejemplo n.º 13
0
    def __init__(self, config):
        """Initialize the sensor."""
        import broadlink

        mac = config.get(CONF_MAC).encode().replace(b':', b'')
        mac_addr = binascii.unhexlify(mac)

        self._device = broadlink.sp2((config.get(CONF_HOST), 80), mac_addr)
        self._device.timeout = config.get(CONF_TIMEOUT)

        if not self._auth():
            _LOGGER.warning("Failed to connect to device")

        self._name = config.get(CONF_NAME)
        self._state = None
        self._unit_of_measurement = "W"
Ejemplo n.º 14
0
def send_sp2(device):
	result ={}
	state = True
	host = device['ip']
	port = device['port']
	mac = device['mac']
	name = device['name']
	wantedstate = device['state']
	if int(wantedstate) == 0:
		state = False
	product = broadlink.sp2(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.set_power(state)
	time.sleep(0.1)
	result = read_sp2(device)
	return result
Ejemplo n.º 15
0
def read_sp2(device):
	result ={}
	host = device['ip']
	port = device['port']
	mac = device['mac']
	name = device['name']
	product = broadlink.sp2(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 + "....")
	result['mac']=mac
	data = product.check_power()
	if data == True:
		result['s1']=1
	else:
		result['s1']=0
	logging.debug(str(result))
	return result
Ejemplo n.º 16
0
def socket_set_state(socket_list, new_state):
    for socket in socket_list:
        if socket.editable:
            device = sp2((socket.ip, 80), socket.mac, devtype=38010)
            device.auth()
            device.set_power(new_state)
Ejemplo n.º 17
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup 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.loop.run_in_executor(None,
                                                        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.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')

    if switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
        hass.services.register(DOMAIN, SERVICE_LEARN + '_' + ip_addr,
                               _learn_command)
        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)
Ejemplo n.º 18
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)
Ejemplo n.º 19
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":
Ejemplo n.º 20
0
data_dir = os.path.abspath(os.path.dirname(data_dir +
                                           "/../../broadlink-data/"))
#print (data_dir)

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

mac = mapping_dictionary["mapping_dictionary"][switch_item_name]["MAC"]
ip = mapping_dictionary["mapping_dictionary"][switch_item_name]["IP"]

operations = ""
operations += "start"
try:
    device = broadlink.sp2(host=(ip, 80),
                           mac=bytearray.fromhex(mac),
                           devtype="sp2")

    operations += ", connecting"
    device.auth()
    operations += ", connected"
    device.host
    if switch_item_status == "ON":
        device.set_power(True)
    if switch_item_status == "OFF":
        device.set_power(False)
    if switch_item_status == "STATUS":
        device_power = device.check_power()
        operations += ", power:+++{}+++".format(device_power)

    operations += ", ==sent=="
Ejemplo n.º 21
0
#!/usr/bin/python

import broadlink
import sys

device_ip = "192.168.xxx.yyy"
device_port = 80
device_mac = "mac address"
device_type = "broadlink.sp2"

action = str(sys.argv[1])

device = broadlink.sp2(host=(device_ip, device_port),
                       mac=bytearray.fromhex(device_mac))

device.auth()

if action == "on":
    device.set_power(True)
elif action == "off":
    device.set_power(False)
elif action == "status":
    print "on" if device.check_power() else "off"
Ejemplo n.º 22
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)

    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}
    commands = config.get(CONF_COMMANDS)
    IR_COMMANDS.update(commands)

    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 IR_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
        broadlink_rm = BroadlinkRM(
            hass,
            config.get(CONF_NAME, 'broadlink_rm_' + ip_addr.replace('.', '_')),
            None, broadlink_device)
        hass.data[DATA_KEY][ip_addr] = broadlink_rm
        switches = [broadlink_rm]
    elif switch_type in RM_TYPES:
        broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
        # 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(
                    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_devices(switches)

    async def async_service_handler(service):
        """Map services to methods on Broadlink RM."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {
            key: value
            for key, value in service.data.items() if key != ATTR_ENTITY_ID
        }
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [
                device for device in hass.data[DATA_KEY].values()
                if device.entity_id in entity_ids
            ]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            if not hasattr(device, method['method']):
                continue
            await getattr(device, method['method'])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks, loop=hass.loop)

    for service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[service].get('schema', SERVICE_SCHEMA)
        hass.services.async_register(DOMAIN,
                                     service,
                                     async_service_handler,
                                     schema=schema)
Ejemplo n.º 23
0
 def sw(self, value):
     logging.info("スウィッチ: %s", value)
     sp2 = broadlink.sp2((net1["ip"], net1["port"]),
                         netaddr.EUI(net1["mac"]), net1["timeout"])
     sp2.auth()
     sp2.set_power(value)
Ejemplo n.º 24
0
 def __init__(self):
     self.prev_state = None
     self.prev_time = None
     self.boiler = broadlink.sp2(*BOILER_TARGET)
Ejemplo n.º 25
0
def readSettingsFile():
    global devices
    global DeviceByName
    global RestrictAccess
    global LearnFrom
    global OverwriteProtected
    global GlobalPassword
    global GlobalTimeout
    global settingsFile

    # A few defaults
    serverPort = 8080
    Autodetect = False
    OverwriteProtected = True
    listen_address = '0.0.0.0'
    broadcast_address = '255.255.255.255'

    settingsFile = configparser.ConfigParser()
    settingsFile.optionxform = str
    settingsFile.read(settings.settingsINI)

    Dev = settings.Dev
    GlobalTimeout = settings.GlobalTimeout
    DiscoverTimeout = settings.DiscoverTimeout

    # Override them
    if settingsFile.has_option('General', 'password'):
        GlobalPassword = settingsFile.get('General', 'password').strip()

    if settingsFile.has_option('General', 'serverPort'):
        serverPort = int(settingsFile.get('General', 'serverPort'))

    if settingsFile.has_option('General', 'serverAddress'):
        listen_address = settingsFile.get('General', 'serverAddress')
        if listen_address.strip() == '':
            listen_address = '0.0.0.0'

    if settingsFile.has_option('General', 'restrictAccess'):
        RestrictAccess = settingsFile.get('General', 'restrictAccess').strip()

    if settingsFile.has_option('General', 'learnFrom'):
        LearnFrom = settingsFile.get('General', 'learnFrom').strip()

    if settingsFile.has_option('General', 'allowOverwrite'):
        OverwriteProtected = False

    if settingsFile.has_option('General', 'broadcastAddress'):
        broadcast = settingsFile.get('General', 'broadcastAddress')
        if broadcast_address.strip() == '':
            broadcast_address = '255.255.255.255'

    if settingsFile.has_option('General', 'Autodetect'):
        try:
            DiscoverTimeout = int(
                settingsFile.get('General', 'Autodetect').strip())
        except:
            DiscoverTimeout = 5
        Autodetect = True
        settingsFile.remove_option('General', 'Autodetect')

    # Device list
    DeviceByName = {}
    if not settings.DevList:
        Autodetect = True

    if Autodetect == True:
        print("Beginning device auto-detection ... ")
        # Try to support multi-homed broadcast better
        try:
            devices = broadlink.discover(DiscoverTimeout, listen_address,
                                         broadcast_address)
        except:
            devices = broadlink.discover(DiscoverTimeout, listen_address)

        backupSettings()
        try:
            broadlinkControlIniFile = open(
                path.join(settings.applicationDir, 'settings.ini'), 'w')
            for device in devices:
                try:
                    device.hostname = socket.gethostbyaddr(device.host[0])[0]
                    if "." in device.hostname:
                        device.hostname = device.hostname.split('.')[0]
                except:
                    device.hostname = "Broadlink" + device.type.upper()
                if device.hostname in DeviceByName:
                    device.hostname = "%s-%s" % (
                        device.hostname, str(device.host).split('.')[3])
                DeviceByName[device.hostname] = device
                if not settingsFile.has_section(device.hostname):
                    settingsFile.add_section(device.hostname)
                settingsFile.set(device.hostname, 'IPAddress',
                                 str(device.host[0]))
                hexmac = ':'.join(["%02x" % (x) for x in reversed(device.mac)])
                settingsFile.set(device.hostname, 'MACAddress', hexmac)
                settingsFile.set(device.hostname, 'Device',
                                 hex(device.devtype))
                settingsFile.set(device.hostname, 'Timeout',
                                 str(device.timeout))
                settingsFile.set(device.hostname, 'Type', device.type.upper())
                device.auth()
                print("%s: Found %s on %s (%s) type: %s" %
                      (device.hostname, device.type, device.host, hexmac,
                       hex(device.devtype)))
            settingsFile.write(broadlinkControlIniFile)
            broadlinkControlIniFile.close()
        except StandardError as e:
            print("Error writing settings file: %s" % e)
            restoreSettings()
    else:
        devices = []
    if settings.DevList:
        for devname in settings.DevList:
            if Dev[devname, 'Type'] == 'RM' or Dev[devname, 'Type'] == 'RM2':
                device = broadlink.rm((Dev[devname, 'IPAddress'], 80),
                                      Dev[devname, 'MACAddress'],
                                      Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'MP1':
                device = broadlink.mp1((Dev[devname, 'IPAddress'], 80),
                                       Dev[devname, 'MACAddress'],
                                       Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'SP1':
                device = broadlink.sp1((Dev[devname, 'IPAddress'], 80),
                                       Dev[devname, 'MACAddress'],
                                       Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'SP2':
                device = broadlink.sp2((Dev[devname, 'IPAddress'], 80),
                                       Dev[devname, 'MACAddress'],
                                       Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'A1':
                device = broadlink.a1((Dev[devname, 'IPAddress'], 80),
                                      Dev[devname, 'MACAddress'],
                                      Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'HYSEN':
                device = broadlink.hysen((Dev[devname, 'IPAddress'], 80),
                                         Dev[devname, 'MACAddress'],
                                         Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'S1C':
                device = broadlink.S1C((Dev[devname, 'IPAddress'], 80),
                                       Dev[devname, 'MACAddress'],
                                       Dev[devname, 'Device'])
            if Dev[devname, 'Type'] == 'DOOYA':
                device = broadlink.dooya((Dev[devname, 'IPAddress'], 80),
                                         Dev[devname, 'MACAddress'],
                                         Dev[devname, 'Device'])
            device.timeout = Dev[devname, 'Timeout']
            if not devname in DeviceByName:
                device.hostname = devname
                device.auth()
                devices.append(device)
                print("%s: Read %s on %s (%s)" %
                      (devname, device.type, str(device.host[0]), device.mac))
            DeviceByName[devname] = device
    return {
        "port": serverPort,
        "listen": listen_address,
        "timeout": GlobalTimeout
    }
Ejemplo n.º 26
0
    )
    exit()

if '-mac' in commandArgs:
    mac = commandArgs['-mac']
else:
    print(
        "Please provide the -mac parameter (mac address of the plug, remove all ':')"
    )
    exit()

if '-port' in commandArgs:
    port = commandArgs['-port']

mac = codecs.decode(mac, 'hex')
devices = broadlink.sp2((ip, 80), mac)
devices.auth()

app = Flask(__name__)


@app.route('/')
def index():
    global devices
    return "Current status: " + str(devices.check_power())


@app.route('/turnon')
def turnon():
    global devices
    devices.set_power(True)
Ejemplo n.º 27
0
import broadlink, sys, time

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

try:
    device = broadlink.sp2(host=(ip, 80),
                           mac=bytearray.fromhex(macaddr),
                           devtype=0x2711)
    device.auth()
    time.sleep(3)
    device.host

    if state == "1":
        device.set_power(True)
        print "on"
    else:
        device.set_power(False)
        print "off"
except:
    print "error"
    pass
#!/usr/bin/python3
import broadlink
d=broadlink.sp2(host=(sys.argv[1], 80), mac=binascii.unhexlify(sys.argv[2]))
d.auth()
d.set_power(sys.argv[3]=='true')
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Broadlink switches."""

    host = config[CONF_HOST]
    mac_addr = config[CONF_MAC]
    friendly_name = config[CONF_FRIENDLY_NAME]
    model = config[CONF_TYPE]
    timeout = config[CONF_TIMEOUT]
    slots = config[CONF_SLOTS]
    devices = config[CONF_SWITCHES]

    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),
            ) 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:
        api = blk.rm((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = generate_rm_switches(devices, broadlink_device)
    elif model in RM4_TYPES:
        api = blk.rm4((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = generate_rm_switches(devices, broadlink_device)
    elif model in SP1_TYPES:
        api = blk.sp1((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif model in SP2_TYPES:
        api = blk.sp2((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
    elif model in MP1_TYPES:
        api = blk.mp1((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        parent_device = BroadlinkMP1Switch(broadlink_device)
        switches = [
            BroadlinkMP1Slot(
                get_mp1_slot_name(friendly_name, i),
                broadlink_device,
                i,
                parent_device,
            ) for i in range(1, 5)
        ]

    api.timeout = timeout
    connected = await broadlink_device.async_connect()
    if not connected:
        raise PlatformNotReady

    if model in RM_TYPES or model in RM4_TYPES:
        hass.async_create_task(
            async_setup_service(hass, host, broadlink_device))

    async_add_entities(switches)
Ejemplo n.º 31
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)
Ejemplo n.º 32
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)

    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)
Ejemplo n.º 33
0
            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)


def configure_device(device, mqtt_prefix):
Ejemplo n.º 34
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)
Ejemplo n.º 35
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)