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
Exemple #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.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)
Exemple #3
0
        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):
    device.auth()
<<<<<<< HEAD
    logging.debug('Connected to \'%s\' Broadlink device at \'%s\' (MAC %s) and started listening for commands at MQTT topic having prefix \'%s\' '
                  % (device.type, device.host[0], ':'.join(format(s, '02x') for s in device.mac[::-1]), mqtt_prefix))
=======
    logging.debug('Connected to \'%s\' Broadlink device at \'%s\' (MAC %s) and started listening to MQTT commands at \'%s#\' '
Exemple #4
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)
Exemple #5
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
    }