Ejemplo n.º 1
0
async def info ():
    """Connect to an ESPHome device and get details."""
    loop = asyncio.get_running_loop()

    # Establish connection
    api = aioesphomeapi.APIClient(loop,host, 6053, password)
    await api.connect(login=True)

    # Get API version of the device's firmware
    #print("api.api_version:"+str(api.api_version))

    # Show device details
    device_info = await api.device_info()
    #print("device_info:"+str(device_info))

    # List all entities of the device
    entities = await api.list_entities_services()
    #print("entities:"+str(entities))

    ###
    sInfo = entities[0]
    #rint (len(sInfo))
    d = {}
    for i in range(len(sInfo)):
        lInfo = sInfo[i]
        print( str(lInfo.key) +';'+ str(lInfo.name))
Ejemplo n.º 2
0
    async def relay_set_real(self, relay_index, switch_command):
        hostname = self.devices[relay_index]['hostname']
        password = self.devices[relay_index]['password']
        key = self.devices[relay_index]['key']

        cli = aioesphomeapi.APIClient(
            eventloop = self.asyncio_loop,
            address = hostname,
            port = 6053,
            password = password,
            keepalive = 0
        )
        await asyncio.wait_for(cli.connect(login=True), timeout=10)

        sensors, services = await asyncio.wait_for(cli.list_entities_services(), timeout=10)

        # Get the integer key for the given key (which is actually an ID)
        key_int = None
        for this_sensor in sensors:
            if this_sensor.object_id == key:
                self.logger.debug("Device %s has matching object: %s" % (hostname, this_sensor.object_id))
                key_int = this_sensor.key
            else:
                self.logger.debug("Device %s has object: %s" % (hostname, this_sensor.object_id))


        if not key_int:
            self.logger.print("Could not get integer key for device %s object %s" % (hostname, key))
            return

        await asyncio.wait_for(cli.switch_command(key_int, switch_command), timeout=10)
        await asyncio.wait_for(cli.disconnect(), timeout=10)

        self.logger.debug("Device %s key %s (%d) was set to: %s" % (hostname, key, key_int, switch_command))
Ejemplo n.º 3
0
async def main():
    """Connect to an ESPHome device and get details."""
    loop = asyncio.get_running_loop()

    # Establish connection
    api = aioesphomeapi.APIClient(loop, "astroscale.local", 6053,
                                  "1WkzndV8oAZ5sqbe47rc")
    await api.connect(login=True)

    # Get API version of the device's firmware
    print(api.api_version)

    def change_callback(state):
        global weight
        global weight_date
        """Print the state changes of the device.."""
        print(
            f"state: {state}, isWeight:{state.key == weight_key}, state isnan: {math.isnan(state.state)}"
        )
        if state is not None and not math.isnan(
                state.state) and state.key == weight_key:
            print("Setting weigth to ", state.state)
            weight_date = get_now()
            weight = state.state

    # Subscribe to the state changes
    await api.subscribe_states(change_callback)
Ejemplo n.º 4
0
    async def start(self):
        """."""
        success = False
        config = self._config
        try:
            url = config.circuitsetup.url
            port = config.circuitsetup.get('port', ESPHomeApi._DEFAULT_ESPHOME_API_PORT)
            password = config.circuitsetup.get('password', ESPHomeApi._DEFAULT_ESPHOME_API_PASSWORD)
            self._client = aioesphomeapi.APIClient(address=url, port=port, password=password)
            await self._client.connect(login=True)
            success = True
        except SocketAPIError as e:
            _LOGGER.error(f"{e}")
        except InvalidAuthAPIError as e:
            _LOGGER.error(f"ESPHome login failed: {e}")
        except Exception as e:
            _LOGGER.error(f"Unexpected exception connecting to ESPHome: {e}")
        finally:
            if not success:
                self._client = None
                return False

        try:
            api_version = self._client.api_version
            _LOGGER.info(f"ESPHome API version {api_version.major}.{api_version.minor}")

            device_info = await self._client.device_info()
            self._name = device_info.name
            _LOGGER.info(f"Name: '{device_info.name}', model is {device_info.model}, version {device_info.esphome_version} built on {device_info.compilation_time}")
        except Exception as e:
            _LOGGER.error(f"Unexpected exception accessing version and/or device_info: {e}")
            return False

        try:
            entities, services = await self._client.list_entities_services()
            sample_period = None
            extra = ''
            for sensor in entities:
                if sensor.name == 'cs24_sampling':
                    sample_period = sensor.accuracy_decimals
                    extra = f', ESPHome reports sampling sensors every {sample_period} seconds'
                    break
            _LOGGER.info(f"CS/ESPHome core started{extra}")

        except Exception as e:
            _LOGGER.error(f"Unexpected exception accessing '{self._name}' list_entities_services(): {e}")
            return False

        self._sensors_by_name, self._sensors_by_key = sensors.parse_sensors(yaml=config.sensors, entities=entities)
        self._sensors_by_location = sensors.parse_by_location(self._sensors_by_name)
        self._sensors_by_integration = sensors.parse_by_integration(self._sensors_by_name)
        return True
Ejemplo n.º 5
0
async def main(s3):
    loop = asyncio.get_running_loop()
    cli = aioesphomeapi.APIClient(loop, hostname, port, password, keepalive=1)

    await cli.connect(login=True)

    def cb(state):
        time = datetime.now().strftime('%s')
        print(f"[{time}] Capturing to {bucket}/{time}.png")
        object = s3.Object(bucket, f"{time}.png")
        object.put(Body=state.image)

    await cli.subscribe_states(cb)
Ejemplo n.º 6
0
async def main():
    """Connect to an ESPHome device and wait for state changes."""
    loop = asyncio.get_running_loop()
    cli = aioesphomeapi.APIClient(loop, host, 6053, password)

    await cli.connect(login=True)

    def change_callback(state):
        today = datetime.datetime.today()
        if state.state != 0.0:
            print(_log(state.key, state.state, state.missing_state))
            #register.send(_log(state.key,state.state,state.missing_state),2)

    # Subscribe to the state changes
    await cli.subscribe_states(change_callback)
Ejemplo n.º 7
0
async def process_esphome(name, port, password, info_queue, data_queue):
    """Connect to an ESPHome device and wait for state changes."""
    loop = asyncio.get_running_loop()
    client = aioesphomeapi.APIClient(loop, name, port, password)

    await client.connect(login=True)

    # Get the info from the device
    info = await get_info(client)

    # Send the info the database writing queue
    await info_queue.put(info)

    def change_callback(state):
        data_queue.put_nowait(state)

    # Subscribe to the state changes
    await client.subscribe_states(change_callback)
Ejemplo n.º 8
0
async def main():
    loop = asyncio.get_event_loop()

    for i in ['/', '-', '\\', '|'] * 4:
        await asyncio.sleep(0.1)
        print(f"{i} GateHacker 1.2.44.2 engaging {i}", end="\r")
    print(flush=True)

    print("Identifying target...")
    rsv = resolver.Resolver()
    rsv.nameservers = ["10.98.0.1"]
    target = rsv.resolve("sebaschan.lan")
    host = target.rrset[0].address

    await asyncio.sleep(0.2)

    print("Spooling up connections...")
    client = aioesphomeapi.APIClient(loop, host, 6053, password)
    await client.connect(login=True)
    await asyncio.sleep(0.2)

    print("Hacking the gate...")
    await asyncio.sleep(0.2)

    switch: aioesphomeapi.BinarySensorInfo = filter(
        lambda s: s.object_id == 'open_ring_one_door',
        (await client.list_entities_services())[0]).__next__()

    await client.switch_command(switch.key, 1)

    msg = "! GATE 0 HACK3D !"
    trg = list(" " * len(msg))
    src = list(enumerate(msg))
    random.shuffle(src)
    for i, k in src:
        trg[i] = k
        print(f"\r {''.join(trg)} ", end="", flush=True)
        await asyncio.sleep(0.04)
    await asyncio.sleep(0.2)

    print()
    input("Press enter to close the door...")
    await client.switch_command(switch.key, 0)
Ejemplo n.º 9
0
async def main(conf):
    main_loop = asyncio.get_running_loop()
    clis = list()

    for device in conf["lights"]:
        cli = aioesphomeapi.APIClient(main_loop, device["hostname"], 6053,
                                      device["password"])

        reconnection_closure = await generate_reconnection_closure(
            main_loop, cli, device["hostname"])
        try:
            await cli.connect(login=True, on_stop=reconnection_closure)
        except aioesphomeapi.APIConnectionError:
            continue

        print("Connected to {}".format(device["hostname"]))
        list_services = await cli.list_entities_services()
        pprint.pprint(list_services)
        clis.append(cli)

    await asyncio.gather(do_stuff(clis, conf["stepmania_sextet_file"]))

    print("All done")