Looking for help/mentor to make a tcp listener platform

I want to make a tcp listener for hass. I’m very noobish at python. I took a basic class to get up and running but I’m not CS major or anything.

I do have a working tcp listener I made that runs commands based on whats typed in. Ie. Telnet to port x and type in “run a” and whatever is defined in the python program for “run a” runs. I have that much.

I started reading the documentation and looking at the examples but I’m not clear on where in the code to start the listener and how to pass back to hass.

I was thinking if someone could help me with sudo-code for it then I can probably fill in the rest. What I think the first step might be to listen, and take the text and fill it in as a state for the sensor or an attribute to the sensor.

Anyway, thats all for now.

For a component it could look like the following:

@asyncio.coroutine
def async_start(hass, discovery_topic, hass_config):
    """Initialize of TCP Listener."""

    @asyncio.coroutine
    def async_tcp_message_received():
        """Process the received payload."""
        # Do something with your payload

    yield from async_tcp_message_received()

    return True

Keep in mind that there are already TCP platforms (eg. https://home-assistant.io/components/sensor.tcp/) available.

@fabaff Thanks. I do know about tcp.sensor but that isn’t a listener. I looked at it again and it doesn’t have anything about asyncio. Do I need that? It seems like another level of complexity that is going to make this a lot harder.

I spent some more time fumbling around. I’m thinking your saying to use asyncio becuase currently I don’t see a way to listen for a connection using the example framework. Am I correct or totally lost?

https://pastebin.com/raw/9Zg7jbYV

I tried putting the tcp listener under update and it appears to only run every so often which makes sense.

This is the sample code for a usual sensor.

That’s because you need the listener async_tcp_message_received() or tcp_message_received() in setup_platform(), async_setup_platform(), or async_start() depends on what you want to use.

Most MQTT platforms and history/export components are implementing listeners.

Thanks for the help @fabaff.
I ended up not figuring it out. This is what I ended up with. Note that I didn’t write the socket handler from scratch. I copied a template and modified it.
Script: https://pastebin.com/raw/mTB7stVi

If you have any recommendations on how to improve my python so I don’t have these janky scripts running as separate daemons I’d like to try.

The total solution I came up with: