def do_GET(self):
        #logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        #logging.info("GET request Path: %s\n", str(self.path))
        self._set_response()
        #self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
        if self.path == "/":
            self.wfile.write(
                "Commands available to send to {} / {} / type: 0x{}: <br /><br />"
                .format(broadlinkconfig.host, broadlinkconfig.mac,
                        format(broadlinkconfig.type, '02x')).encode('utf-8'))
            for command in irconfig.commands:
                self.wfile.write("<a href=/{}>{}</a><br />".format(
                    command, command).encode('utf-8'))
        else:
            #self.wfile.write("command:".encode('utf-8'))
            command = self.path.replace('/', '')
            #type = 0x2737
            #host = "192.168.1.1"
            #mac = bytearray.fromhex("abcdef")
            dev = broadlink.gendevice(broadlinkconfig.type,
                                      (broadlinkconfig.host, 80),
                                      bytearray.fromhex(broadlinkconfig.mac))
            dev.auth()
            payload = get_command_data(command, 1)
            dev.send_data(payload)
            self.wfile.write(
                "command <b>{}</b> send<br />".format(command).encode('utf-8'))
            self.wfile.write(
                "<br /><a href=/>Return to index</a>".encode('utf-8'))

        self.wfile.write("<br /><br />end of document".encode('utf-8'))
Ejemplo n.º 2
0
 def _learn_new_IR_command(self, values, type_id, did):
     """ Devices.xml Callback Method to learn a new command. """
     dev = indigo.devices[did]
     # If an address was provided, use it, otherwise, get it from the props.
     addr = values.get("address",
                       dev.pluginProps.get("address", "127.0.0.1"))
     model = values.get("model", dev.pluginProps.get("model", "0x2712"))
     cat = values.get("category", dev.pluginProps.get("category", "IR"))
     values['rawCommand'] = "- learn failed -"
     try:
         # Magic.
         bl_device = broadlink.gendevice(int(model, 0), (addr, 80),
                                         "000000000000")
         bl_device.auth()
         bl_device.enter_learning()
     except Exception as err:
         indigo.server.log(
             u"{0}, Error connecting to {1} ({2}): {3}".format(
                 MODELS[cat][model], dev.name, addr, err),
             isError=True)
         return values
     timeout = int(indigo.activePlugin.pluginPrefs.get("timeout", 8))
     data = None
     while data is None and timeout > 0:
         time.sleep(1)
         timeout -= 1
         data = bl_device.check_data()
     if data:
         values['rawCommand'] = ''.join(
             format(x, '02x') for x in bytearray(data))
     return values
Ejemplo n.º 3
0
 def update_device_states(self, dev):
     """ Used to update a single device's state(s).
         Currently only captures on/off power state.
     """
     addr = dev.pluginProps.get("address", "")
     model = dev.pluginProps.get("model", "0x2712")
     cat = dev.pluginProps.get("category", "SP")
     try:
         # This device is not supported in the python-broadlink library, so spoof it as another device.
         # TODO: Remove this when https://github.com/mjg59/python-broadlink/issues/142 has a solution.
         rmodel = model
         model = "0x2711" if model == "0x7547" else model
         # Magic.
         bl_device = broadlink.gendevice(int(model, 0), (addr, 80),
                                         "000000000000")
         bl_device.timeout = indigo.activePlugin.pluginPrefs.get(
             "timeout", 8)
         bl_device.auth()
         state = bl_device.check_power()
     except Exception as err:
         dev.setErrorStateOnServer(u"Comm Error: {}".format(err))
         indigo.server.log(
             u"{0}, Error connecting to {1} ({2}): {3}".format(
                 MODELS[cat][rmodel], dev.name, addr, err),
             isError=True)
     else:
         if dev.pluginProps.get("logActions", True):
             indigo.server.log(u"Updated \"{0}\" on:{1} -> on:{2}".format(
                 dev.name, dev.states["onOffState"], state))
         dev.updateStateOnServer("onOffState", state)
Ejemplo n.º 4
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """装载实体."""
    host = config['host']
    mac = bytearray.fromhex(config['mac'])
    dev = broadlink.gendevice(type, (host, 80), mac)
    o = Rmmin3(hass, dev)
    add_devices([o])
 def gen_device(self, dev_data):
     dev_type, host, mac = dev_data["type"], dev_data["host"], bytearray.fromhex(
         dev_data["mac"])
     dev = broadlink.gendevice(int(dev_type, 0), (host, 80), mac)
     if not dev.auth():
         raise falcon.HTTPBadRequest("device auth failed.")
     return dev
Ejemplo n.º 6
0
 def __init__(self, device_name: str, devtype: int, host: str, mac: str):
     self.name = device_name
     self.device = broadlink.gendevice(devtype, (host, 80), mac)
     self.device.auth()
     log.debug(
         f'Created device \'{device_name}\' with details 0x{devtype:02x} {host} {mac}'
     )
Ejemplo n.º 7
0
def main():
    """ Send a command. """
    device = broadlink.gendevice(int(DEVICE_ID, 0), (DEVICE_IP, 80),
                                 "000000000000")
    print("Sending command to {}".format(DEVICE_IP))
    device.auth()
    data = bytearray.fromhex(''.join(IR_COMMAND))
    device.send_data(data)
Ejemplo n.º 8
0
def initDevice(dtype, host, mac):
    dtypeTmp = dtype
    if dtypeTmp == '0x6539':
	    dtypeTmp = '0x610F'
    _dtype = int(dtypeTmp, 0)
    _host = host
    _mac = bytearray.fromhex(mac)
    return broadlink.gendevice(_dtype, (_host, 80), _mac)
Ejemplo n.º 9
0
    def __init__(self, args):
        if not broadlink:
            raise Exception("broadlink module not available")
        devtype, host, mac = args.split(":")
        devtype = int(devtype, 0)
        mac = bytearray.fromhex(mac)

        self.dev = broadlink.gendevice(devtype, (host, 80), mac)
        self.dev.auth()
def main():
    """ Send a command. """
    rm_pro_dev = broadlink.gendevice(int(RM_PRO_PLUS_DEV, 0), (DEVICE_IP, 80),
                                     "000000000000")
    print "sending command to " + DEVICE_IP
    rm_pro_dev.auth()

    data = bytearray.fromhex(''.join(IR_COMMAND))
    rm_pro_dev.send_data(data)
Ejemplo n.º 11
0
def br_init():
  global BROADLINK
  DEVICE = y[config]["device"]
  HOST = y[config]["RMhost"]
  MACR = y[config]["macreverse"]
  mac = bytearray.fromhex(MACR)
  BROADLINK = broadlink.gendevice(DEVICE, (HOST, 80), mac)
  BROADLINK.auth()
  return
Ejemplo n.º 12
0
def select_device(ip, mac, port='80', type_='10039'):

    host = (ip, int(port))
    type_ = hex(int(type_))
    type_ = int(type_, 16)
    if not isinstance(mac, bytearray):
        mac = bytearray.fromhex(mac)

    device = broadlink.gendevice(type_, host, mac)
    return device
Ejemplo n.º 13
0
    async def async_setup(self):
        """Set up the device and related entities."""
        config = self.config

        api = blk.gendevice(
            config.data[CONF_TYPE],
            (config.data[CONF_HOST], DEFAULT_PORT),
            bytes.fromhex(config.data[CONF_MAC]),
            name=config.title,
        )
        api.timeout = config.data[CONF_TIMEOUT]
        self.api = api

        try:
            await self.hass.async_add_executor_job(api.auth)

        except AuthenticationError:
            await self._async_handle_auth_error()
            return False

        except (NetworkTimeoutError, OSError) as err:
            raise ConfigEntryNotReady from err

        except BroadlinkException as err:
            _LOGGER.error(
                "Failed to authenticate to the device at %s: %s", api.host[0], err
            )
            return False

        self.authorized = True

        update_manager = get_update_manager(self)
        coordinator = update_manager.coordinator
        await coordinator.async_refresh()
        if not coordinator.last_update_success:
            raise ConfigEntryNotReady()

        self.update_manager = update_manager
        self.hass.data[DOMAIN].devices[config.entry_id] = self
        self.reset_jobs.append(config.add_update_listener(self.async_update))

        try:
            self.fw_version = await self.hass.async_add_executor_job(api.get_fwversion)
        except (BroadlinkException, OSError):
            pass

        # Forward entry setup to related domains.
        tasks = (
            self.hass.config_entries.async_forward_entry_setup(config, domain)
            for domain in get_domains(self.api.type)
        )
        for entry_setup in tasks:
            self.hass.async_create_task(entry_setup)

        return True
Ejemplo n.º 14
0
 async def async_step_reauth(self, data):
     """Reauthenticate to the device."""
     device = blk.gendevice(
         data[CONF_TYPE],
         (data[CONF_HOST], DEFAULT_PORT),
         bytes.fromhex(data[CONF_MAC]),
         name=data[CONF_NAME],
     )
     device.timeout = data[CONF_TIMEOUT]
     await self.async_set_device(device)
     return await self.async_step_reset()
Ejemplo n.º 15
0
 def get_devices(self):
     if len(self.config['devices']) == 0:
         return broadlink.discover(timeout=self.get('lookup_timeout', 5))
     ds = []
     for d in self.config['devices']:
         mac = bytearray.fromhex(d['mac'].replace(':', ' '))
         dev = broadlink.gendevice(host=(d['host'], 80),
                                   mac=mac,
                                   devtype=0x4EAD)
         ds.append(dev)
     return ds
Ejemplo n.º 16
0
def get_rmmini_info(rmmini_id):
    # DBのデータからホスト情報を作成
    rmmini_info = db.session.query(Rmmini).filter(
        Rmmini.id == rmmini_id).first()
    device = broadlink.gendevice(rmmini_info.devtype, (rmmini_info.host, 80),
                                 bytearray.fromhex(rmmini_info.mac_address))
    db.session.close()
    if device.auth():
        return device
    else:
        return False
Ejemplo n.º 17
0
def Connect_Broadlink():

    host = request.args.get('host')
    type = int(request.args.get('type'), 16)
    mac = bytearray.fromhex(request.args.get('mac'))
    print("host, type, mac:", host, type, mac)
    dev = broadlink.gendevice(type, (host, 80), mac)
    print("We have a device")
    dev.auth()
    print('dev=', dev)
    return dev
Ejemplo n.º 18
0
 async def async_step_reauth(self, entry_data: Mapping[str,
                                                       Any]) -> FlowResult:
     """Reauthenticate to the device."""
     device = blk.gendevice(
         entry_data[CONF_TYPE],
         (entry_data[CONF_HOST], DEFAULT_PORT),
         bytes.fromhex(entry_data[CONF_MAC]),
         name=entry_data[CONF_NAME],
     )
     device.timeout = entry_data[CONF_TIMEOUT]
     await self.async_set_device(device)
     return await self.async_step_reset()
def command():
    dtype = int(request.args.get('type'), 0)
    host = request.args.get('host')
    mac = bytearray.fromhex(request.args.get('mac'))
    dev = broadlink.gendevice(dtype, (host, 80), mac)
    command = request.args.get('command')
    dev.auth()
    try:
        dev.send_data(bytearray.fromhex(''.join(command)))
        return jsonify('{"data":"","success":1,"message":"Command sent successfully"}')
    except:
        return jsonify('{"data":"","success":0,"message":"Error occurred while Sending command!"}')
def sweep():
    global _continu_to_sweep
    global _rf_sweep_message
    global _rf_sweep_status
    _continu_to_sweep=False
    _rf_sweep_message=''
    _rf_sweep_status=False
    dtype = int(request.args.get('type'), 0)
    host = request.args.get('host')
    mac = bytearray.fromhex(request.args.get('mac'))
    dev = broadlink.gendevice(dtype, (host, 80), mac)
    dev.auth()
    dev.sweep_frequency()
    _rf_sweep_message = "Learning RF Frequency, press and hold the button to learn..."
    start = time.time()
    while time.time() - start < TIMEOUT:
        time.sleep(1)
        if dev.check_frequency():
            break
    else:
      _rf_sweep_message = "RF Frequency not found!"
      dev.cancel_sweep_frequency()
      return jsonify('{"data":"RF Frequency not found!","success":0}')
    
    _rf_sweep_message = "Found RF Frequency - 1 of 2!"
    time.sleep(1)
    _rf_sweep_message = "You can now let go of the button"
    _rf_sweep_status=True
    while _continu_to_sweep == False:
      _rf_sweep_message = "Click The Continue button"
    
    _rf_sweep_message = "To complete learning, single press the button you want to learn"
    _rf_sweep_status=False
    dev.find_rf_packet()
    start = time.time()
    while time.time() - start < TIMEOUT:
      time.sleep(1)
      try:
        data = dev.check_data()
      except (ReadError, StorageError):
        continue
      else:
        break
    else:
        _rf_sweep_message = "No Data Found"
        return jsonify('{"data":"No Data Found"}')

    _rf_sweep_message = "Found RF Frequency - 2 of 2!"
    learned = ''.join(format(x, '02x') for x in bytearray(data))
    _rf_sweep_message = "RF Scan Completed Successfully"
    time.sleep(1)
    return jsonify('{"data":"' + learned + '"}')
Ejemplo n.º 21
0
    def actionControlDevice(self, action, dev):
        """ Callback Method to Control a SP Device. """
        if action.deviceAction in [
                indigo.kUniversalAction.RequestStatus,
                indigo.kUniversalAction.EnergyUpdate
        ]:
            self.update_device_states(dev)
        addr = dev.pluginProps.get("address", "")
        model = dev.pluginProps.get("model", "0x2711")
        cat = dev.pluginProps.get("category", "SP")
        try:
            # This device is not supported in the python-broadlink library, so spoof it as another device.
            # TODO: Remove this when https://github.com/mjg59/python-broadlink/issues/142 has a solution.
            rmodel = model
            model = "0x2711" if model == "0x7547" else model
            # Magic.
            bl_device = broadlink.gendevice(int(model, 0), (addr, 80),
                                            "000000000000")
            bl_device.auth()
        except Exception as err:
            indigo.server.log(
                u"{0}, Error connecting to {1} ({2}): {3}".format(
                    MODELS[cat][rmodel], dev.name, addr, err),
                isError=True)
            return
        control_device = False
        if action.deviceAction == indigo.kDeviceAction.TurnOn:
            power_state, reply, control_device = True, "On", True
        elif action.deviceAction == indigo.kDeviceAction.TurnOff:
            power_state, reply, control_device = False, "Off", True
        elif action.deviceAction == indigo.kDeviceAction.Toggle:
            # Get current state from device before toggling.
            power_state = not bl_device.check_power()
            reply = "On" if power_state else "Off"
            control_device = True
        elif action.deviceAction == indigo.kDeviceAction.AllLightsOff:
            if dev.pluginProps.get("supportsAllLights", False):
                power_state, reply, control_device = False, "Off", True
        elif action.deviceAction == indigo.kDeviceAction.AllLightsOn:
            if dev.pluginProps.get("supportsAllLights", False):
                power_state, reply, control_device = True, "On", True
        elif action.deviceAction == indigo.kDeviceAction.AllOff:
            if dev.pluginProps.get("supportsAllOff", False):
                power_state, reply, control_device = False, "Off", True

        if control_device:
            bl_device.set_power(power_state)
            dev.updateStateOnServer("onOffState", power_state)
            if dev.pluginProps.get("logActions", True):
                indigo.server.log(u"Sent \"{0}\" {1}".format(dev.name, reply))
Ejemplo n.º 22
0
 def update_relays_devices(self, addrs, devs):
     """ Updates Indigo with current SP and SC devices' states.  Called from set_all_device_states() """
     for (addr, model, cat) in addrs:
         # This device is not supported in the python-broadlink library, so spoof it as another device.
         # TODO: Remove this when https://github.com/mjg59/python-broadlink/issues/142 has a solution.
         rmodel = model
         model = "0x2711" if model == "0x7547" else model
         bl_device = broadlink.gendevice(int(model, 0), (addr, 80),
                                         "000000000000")
         bl_device.timeout = indigo.activePlugin.pluginPrefs.get(
             "timeout", 8)
         energy = 0.0
         try:
             # Magic.
             bl_device.auth()
             state = bl_device.check_power()
             try:
                 energy = bl_device.get_energy()
             except AttributeError:
                 energy = 0.0
         except Exception as err:
             for dev in devs:
                 # Update all the sub devices that failed to get queried.
                 if (dev.pluginProps["address"],
                         dev.pluginProps["model"]) == (addr, model):
                     dev.setErrorStateOnServer(
                         u"Comm Error: {} -> {}".format(addr, err))
                     if indigo.activePlugin.pluginPrefs.get(
                             "logUpdateErrors", True):
                         indigo.server.log(
                             u"{0}, Error communicating with {1} ({2}): {3}"
                             .format(MODELS[cat][rmodel], dev.name, addr,
                                     err),
                             isError=True)
         else:
             # Match this address back to the device(s) and update the state(s).
             for dev in devs:
                 if (dev.pluginProps["address"],
                         dev.pluginProps["model"]) == (addr, model):
                     dev.updateStateOnServer("onOffState", state)
                     if "curEnergyLevel" in dev.states:
                         dev.updateStateOnServer("curEnergyLevel", energy)
                     if (dev.states["onOffState"] != state
                             and dev.pluginProps.get("logChanges", True)):
                         reply = "On" if state else "Off"
                         indigo.server.log(
                             u"Device \"{}\" turned {}".format(
                                 dev.name, reply))
Ejemplo n.º 23
0
    def sendIrCode(self, hermes, intent_message, code, subappliance=None):
        house_rooms = self.extractHouseRooms(intent_message)
        appliances = self.extractAppliances(intent_message)

        global allAppliances
        global allRooms

        if len(house_rooms) == 0:
            house_rooms.append(self.defaultRoom)

        if len(appliances) == 0:
            appliances.append(self.defaultAppliance)

        for appliance in appliances:
            for room in house_rooms:

                if appliance not in allAppliances:
                    hermes.publish_start_session_notification(
                        intent_message.site_id, "Cet appareil nexiste pas", "")
                    return False

                print "[Room]: " + room
                print "[Appliance]: " + appliance

                cmd = "./remotes/" + room + "/" + appliance + "/"

                if subappliance != None:
                    cmd = cmd + subappliance + "/"

                cmd = cmd + code

                if not os.path.isfile(cmd):
                    hermes.publish_start_session_notification(
                        intent_message.site_id, "Cet appareil nexiste pas", "")
                    return False

                contents = Path(cmd).read_text()
                data = bytearray.fromhex(''.join(contents))

                dev = broadlink.gendevice(0x2737, (allRooms[room]["ip"], 80),
                                          allRooms[room]["mac"])
                dev.auth()
                dev.send_data(data)

        return True
Ejemplo n.º 24
0
    async def async_setup(self):
        """Set up the device and related entities."""
        config = self.config

        api = blk.gendevice(
            config.data[CONF_TYPE],
            (config.data[CONF_HOST], DEFAULT_PORT),
            bytes.fromhex(config.data[CONF_MAC]),
            name=config.title,
        )
        api.timeout = config.data[CONF_TIMEOUT]
        self.api = api

        try:
            self.fw_version = await self.opp.async_add_executor_job(
                self._auth_fetch_firmware)

        except AuthenticationError:
            await self._async_handle_auth_error()
            return False

        except (NetworkTimeoutError, OSError) as err:
            raise ConfigEntryNotReady from err

        except BroadlinkException as err:
            _LOGGER.error("Failed to authenticate to the device at %s: %s",
                          api.host[0], err)
            return False

        self.authorized = True

        update_manager = get_update_manager(self)
        coordinator = update_manager.coordinator
        await coordinator.async_config_entry_first_refresh()

        self.update_manager = update_manager
        self.opp.data[DOMAIN].devices[config.entry_id] = self
        self.reset_jobs.append(config.add_update_listener(self.async_update))

        # Forward entry setup to related domains.
        self.opp.config_entries.async_setup_platforms(
            config, get_domains(self.api.type))

        return True
Ejemplo n.º 25
0
def main():
    """ Read a command. """
    rm_pro_dev = broadlink.gendevice(int(RM_PRO_PLUS_DEV, 0), (DEVICE_IP, 80),
                                     "000000000000")
    print "reading command from " + DEVICE_IP
    rm_pro_dev.auth()

    rm_pro_dev.enter_learning()
    data = None
    print "Learning..."
    timeout = 30

    while (data is None) and (timeout > 0):
        time.sleep(1)
        timeout -= 1
        data = rm_pro_dev.check_data()

    if data:
        print ''.join(format(x, '02x') for x in bytearray(data))
def learnir():
    dtype = int(request.args.get('type'), 0)
    host = request.args.get('host')
    mac = bytearray.fromhex(request.args.get('mac'))
    dev = broadlink.gendevice(dtype, (host, 80), mac)
    dev.auth()
    dev.enter_learning()
    start = time.time()
    while time.time() - start < TIMEOUT:
        time.sleep(1)
        try:
            data = dev.check_data()
        except (ReadError, StorageError):
            continue
        else:
            break
    else:
        return jsonify('{"data":"","success":0,"message":"No Data Recived"}')
    learned = ''.join(format(x, '02x') for x in bytearray(data))
    return jsonify('{"data":"' + learned + '","success":1,"message":"IR Data Recived"}')
Ejemplo n.º 27
0
def main():
    """ Read a command from an RM/RM2/RM3/RMmini. """
    device = broadlink.gendevice(int(DEVICE_ID, 0), (DEVICE_IP, 80),
                                 "000000000000")
    print("reading command from {}".format(DEVICE_IP))
    device.auth()

    device.enter_learning()
    data = None
    print("Learning... (push a button)")
    timeout = 30

    while (data is None) and (timeout > 0):
        time.sleep(1)
        timeout -= 1
        data = device.check_data()

    if data:
        print("Captured command!")
        print("".join(format(x, "02x") for x in bytearray(data)))
Ejemplo n.º 28
0
def on_message(client, userdata, msg):
    now = datetime.datetime.now()
    logging.info(" {} {} {}".format(now.strftime("%Y-%m-%d %H:%M:%S.%f"),
                                    msg.topic, msg.payload))
    if msg.topic == TOPIC_POWER:
        if msg.payload in (b"true", "true"):
            print("ON")
            daikin_message.power = Power.ON
        else:
            print("OFF")
            daikin_message.power = Power.OFF
    if msg.topic == TOPIC_TEMPERATURE:
        daikin_message.temperature = int(msg.payload)

    daikin_message.recreate_blocks()
    logging.info("mensaje <{}>".format(daikin_message))
    client = Daikin()
    durations = client.message_to_durations(daikin_message)
    bl = utils.durations_to_broadlink(durations)
    dev = broadlink.gendevice(BROADLINK_DEVICE_TYPE, (BROADLINK_HOST, 80),
                              BROADLINK_MAC)
    dev.auth()
    dev.send_data(bl)
Ejemplo n.º 29
0
    def connect_broadlink(self):
        """
        Connect to the known Broadlink device and Authenticate.
        device = gendevice(devtype, host, mac, name=name, cloud=cloud)
        devtype = 0x27a9 = (rm, "RM pro+", "Broadlink") <-- from broadlink.__init__.py 
        host = 192.168.2.15 (DHCP reservation), port 80
        mac = 78:0f:77:63:5a:25 Convert to bytes = b'x\x0fwcZ%'
        """
        d = broadlink.gendevice(0x27a9, ('192.168.2.16', 80),
                                b'x\x0fwcZ%',
                                name='Apt',
                                cloud=False)

        try:
            result = d.auth()
            self.setDriver('GV0', 1)
            LOGGER.info(
                'Successful Connection and Authentication to Broadlink @ 192.168.2.16.'
            )
        except:
            self.setDriver('GV0', 0)
            LOGGER.info('Unable to connect to Broadlink @ 192.168.2.16.')
        return d if result else None
Ejemplo n.º 30
0
def main():
    """ Read Device State. """
    device = broadlink.gendevice(int(DEVICE_ID, 0), (DEVICE_IP, 80),
                                 "000000000000")
    print("Checking State: {}".format(DEVICE_IP))
    # Not sure why this fails on python 3.7
    device.auth()

    state = device.check_power()
    print("Current State: {}".format(state))
    try:
        energy = device.get_energy()
        print("Energy State: {}".format(energy))
    except ValueError:
        # May not support energy metering.
        pass

    print("Turning device off.")
    device.set_power(False)
    print("Sleeping 5 seconds.")
    time.sleep(5)
    print("Turning device on.")
    device.set_power(True)