Modbus integration not connecting

I’m trying to create an integration that is using modbus.
So far I have this code in my init.py

"""test modbus Integration."""

from __future__ import annotations

import logging
import asyncio
from pymodbus.client import ModbusTcpClient
from homeassistant.helpers.typing import ConfigType
from homeassistant.core import HomeAssistant

_LOGGER = logging.getLogger(__name__)

DOMAIN = 'test_modbus'

async def async_setup(hass, config):
    """Set up the modbus component."""
    hass.states.async_set('test_modbus.test', 'Works!')
    return True


async def myconnect():
    client = ModbusTcpClient('192.168.22.210', 502)

    response = client.read_holding_registers(508, 1, slave=1)
    result = response.registers
    
    hass.async_create_task(myconnect())
    return True

The test_modbus.test entity is created en can be seen in the developer’s tools.
Only the myconnect function is not working.

The same code outside HA works, the following give back results.

#!/usr/bin/env python

import time
from pymodbus.client import ModbusTcpClient

def connect():
    client = ModbusTcpClient('192.168.22.210', 502)
    
    response = client.read_holding_registers(499, 40, slave=1)
    result = response.registers

    client.close()

    print (result)


connect()

I have read the developer docs, I am probably doing something wrong.
Have been trying for a few days now, but can;t figure out what is missing.
There are no errors, nothing in the log.

When HA loads your integration it calls async_setup. So, this is fine and your setup is running and then returning True to tell HA the setup was successful.

However, nothing is calling your connect function. You would need to add something in async setup to call that. Ie

async def async_setup(hass, config):
    """Set up the Itho Amber modbus component."""
    hass.states.async_set('test_modbus.test', 'Works!')
    await connect()
    return True

As an additional note, you need to remove

hass.async_create_task(myconnect())

from your connect function. It will be in an infinite loop firing tasks on the event loop to call itself. That may freeze HA.

Thanks,

I assumed that I needed to register the function by adding it to task list.
It makes sense now.

1 Like