def getA1Sensor(sensor): device = broadlink.a1((A1IPAddress, A1Port), A1MACAddress) device.auth() result = device.check_sensors() if result: return result[sensor] return False
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
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)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Broadlink device sensors.""" host = config[CONF_HOST] mac_addr = config[CONF_MAC] model = config[CONF_TYPE] name = config[CONF_NAME] timeout = config[CONF_TIMEOUT] update_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) if model in RM4_TYPES: api = blk.rm4((host, DEFAULT_PORT), mac_addr, None) check_sensors = api.check_sensors else: api = blk.a1((host, DEFAULT_PORT), mac_addr, None) check_sensors = api.check_sensors_raw api.timeout = timeout device = BroadlinkDevice(hass, api) connected = await device.async_connect() if not connected: raise PlatformNotReady broadlink_data = BroadlinkData(device, check_sensors, update_interval) sensors = [ BroadlinkSensor(name, broadlink_data, variable) for variable in config[CONF_MONITORED_CONDITIONS] ] async_add_entities(sensors, True)
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)
def __init__(self, interval, ip_addr, mac_addr, timeout): """Initialize the data object.""" import broadlink self.data = None self._device = broadlink.a1((ip_addr, 80), mac_addr) self._device.timeout = timeout self.update = Throttle(interval)(self._update) if not self._auth(): _LOGGER.error("Failed to connect to device.")
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
def __init__(self, interval, ip_addr, mac_addr, timeout): """Initialize the data object.""" import broadlink self.data = None self._device = broadlink.a1((ip_addr, 80), mac_addr) self._device.timeout = timeout self._schema = vol.Schema({ vol.Optional('temperature'): vol.Range(min=-50, max=150), vol.Optional('humidity'): vol.Range(min=0, max=100), vol.Optional('light'): vol.Any(0, 1, 2, 3), vol.Optional('air_quality'): vol.Any(0, 1, 2, 3), vol.Optional('noise'): vol.Any(0, 1, 2), }) self.update = Throttle(interval)(self._update) if not self._auth(): _LOGGER.warning("Failed to connect to device")
def onStart(self): if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) if (len(Devices) == 0): Domoticz.Device(Name="A1", Unit=1, TypeName="Temp+Hum").Create() Domoticz.Device(Name="Sound", Unit=2, TypeName="Alert").Create() Domoticz.Device(Name="Air", Unit=3, TypeName="Alert").Create() Domoticz.Device(Name="Light", Unit=4, TypeName="Alert").Create() self.myA1=broadlink.a1(host=(Parameters["Address"], int(Parameters["Port"])), mac=bytearray.fromhex(Parameters["Mode1"])) try: self.isFound = self.myA1.auth() except socket.timeout: self.isFound = False Domoticz.Error("A1 not found") Domoticz.Heartbeat(60) Domoticz.Debug("onStart called")
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Broadlink device sensors.""" host = config[CONF_HOST] mac_addr = config[CONF_MAC] model = config[CONF_TYPE] name = config[CONF_NAME] timeout = config[CONF_TIMEOUT] update_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) if model in RM4_TYPES: api = blk.rm4((host, DEFAULT_PORT), mac_addr, None) check_sensors = api.check_sensors else: api = blk.a1((host, DEFAULT_PORT), mac_addr, None) check_sensors = api.check_sensors_raw api.timeout = timeout broadlink_data = BroadlinkData(api, check_sensors, update_interval) dev = [] for variable in config[CONF_MONITORED_CONDITIONS]: dev.append(BroadlinkSensor(name, broadlink_data, variable)) add_entities(dev, True)
def read_a1(device): result = {} host = device['ip'] port = device['port'] mac = device['mac'] name = device['name'] product = broadlink.a1(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 raw = product.check_sensors_raw() human = product.check_sensors() result['temperature'] = raw['temperature'] result['humidity'] = raw['humidity'] result['luminosity'] = raw['light'] result['air'] = raw['air_quality'] result['noise'] = raw['noise'] result['luminosity_human'] = human['light'] result['air_human'] = human['air_quality'] result['noise_human'] = human['noise'] logging.debug(str(result)) return result
TAG_NAME = 'sensors' CONFIG = get_config(TAG_NAME) DISCONNECTED_FIELD = 'power' DATA_MAPPING = { 'RM2': ('temperature',), 'MP1': ('power',), 'SP2': ('power', 'nightlight'), } DEVICE_COLUMNS = ['power', 'nightlight', 'temperature', 'humidity', 'light', 'air_quality', 'noise', 'voltage', 'proto_version', 'status', 'model', 'rgb', 'short_id', 'proto'] INJECT_DEVICES = ( broadlink.sp2(('192.168.86.78', 80), bytearray(b'@\xb3\xbd4\xea4'), 30023), broadlink.sp2(('192.168.86.67', 80), bytearray(b'\x93\xc5Lw\x0fx'), 10035), broadlink.sp2(('192.168.86.68', 80), bytearray(b'\x1a\xc6\x19w\x0fx'), 10035), broadlink.a1(('192.168.86.77', 80), bytearray(b'q\xd9\x994\xea4'), 10004), broadlink.rm(('192.168.86.81', 80), bytearray(b'\xa5\x82X4\xea4'), 10039), ) + tuple(CONFIG['SENSORS_XIAOMI_GATEWAYS']) FRIENDLY_XIOMI_NAMES = CONFIG['SENSORS_XIAOMI_FRIENDLY_NAMES'] def get_devices(): devices = broadlink.discover(timeout=CONFIG['SENSORS_BROADLINK_TIMEOUT']) devices = [device for device in devices if device.type != 'unknown'] devices_hosts = {device.host for device in devices} for device in INJECT_DEVICES: if isinstance(device, dict): device = XiaomiGateway(**device) for sensor in chain(device.devices.get('sensor', []), device.devices.get('binary_sensor', [])): host = ('{}-{}'.format(sensor['sid'], sensor['proto']), int(sensor['short_id']))
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): device.auth() <<<<<<< HEAD
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 _connect(self): import broadlink self._device = broadlink.a1((self.ip_addr, 80), self.mac_addr, None) self._device.timeout = self.timeout
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 }