#async socket

1 messages · Page 1 of 1 (latest)

blazing plaza
#

I think asyncio.DatagramProtocol is what you are looking for

#

This is kind of where the "batteries included" in Python leaves you with dead batteries 🤣

#

Do you need multicast?

sharp pike
#

where you could use asyncio.get_running_loop() to get the event loop that runs HA

hybrid wraith
#

I thought about streams, but my grill doesn't really stream, it waits for a command, responds and thats it

#

as far as I can tell it doesnt send info on any set interval unless you ask it for information

hybrid wraith
#

it works perfect with my sync code, but I want to make it perfect for home assistant

sharp pike
#

A stream will just keep the connection open, and you can use dispatcher or eventbus to notifiy when new data has arrived

hybrid wraith
#

it almost seems wasteful to keep a connection alive if you don't intend to talk

sharp pike
#

The point of async is that it supends your task if it is just waiting for data, so it doesn't really block any other processes

#

data = await reader.read(1024) will wait for data to come in for example.
If you wrap your coroutine in a task like so : asyncio.create_task(tcp_client)

#
import asyncio

async def tcp_client:
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    data = await reader.read(100)
    # notify entities that data is received

asyncio.create_task(tcp_client()) # when running this in HA
asyncio.run(tcp_client())  # when running standalone

Taken from the link i've sent earlier

hybrid wraith
#

ok, I'll read up on it after my next appointment, thanks a lot for the info

sharp pike
#

you could use dispatcher from homeassistant/helpers/dispatcher to notify about data updates within your integration

blazing plaza
#

This is all tcp, do streams work with UDP too?

sharp pike
#

Good one, it doesn't mention in the docs

blazing plaza
#

It could fit nicely

sharp pike
hybrid wraith
#

I think the data is being sent back here:transport, protocol = await loop.create_datagram_endpoint(lambda: EchoClientProtocol(message, on_con_lost),remote_addr=('127.0.0.1', 9999)) I'm just not sure how to access it

sharp pike
#

the data isn't getting returned, you'll need to set up a listener

hybrid wraith
#

ugh, async asucks

sharp pike
#

though what you should probably do to update the data is append your data model as extra parameter to EchoClientProtocol

hybrid wraith
#

self.data = datagram_received?