brainelectronics / micropython-modbus

MicroPython Modbus RTU Slave/Master and TCP Server/Slave library
GNU General Public License v3.0
115 stars 48 forks source link

Question on setting a value before accessing a register (on_get_cb callback) #97

Closed Omid888 closed 2 days ago

Omid888 commented 3 months ago

Description

I need to read a temperature sensor value and assign it to it's register only when the register is requested from master. I understand that this must be done by on_get_cb callback for that register.

def my_coil_get_cb(reg_type, address, val):
    sensor_value = read_from_sensors()
    register_definitions["HREG"]["temp"]["val"] = sensor_value
    client.setup_registers(registers=register_definitions)

register_definitions = {
    "HREG": {
        "temp": {
            "register": 123,
            "len": 1,
            "val": 0,
            "on_get_cb": my_coil_get_cb,
        }
    }
}

client.setup_registers(registers=register_definitions)

while True:
    try:
        result = client.process()
    except KeyboardInterrupt:
        print('KeyboardInterrupt, stopping TCP client...')
        break
    except Exception as e:
        print('Exception during execution: {}'.format(e))

This works. But I think it's a very poor way to do such thing. Is there a better way? ‌ ‌ Informations:

umodbus version: 2.3.7
device: Raspberrypi pico W
(sysname='rp2', nodename='rp2', release='1.23.0', version='v1.23.0 on 2024-06-02 (GNU 13.2.0 MinSizeRel)', machine='Raspberry Pi Pico W with RP2040')
Omid888 commented 3 months ago

My questions are: 1) Is it the right way? 2) why on_get_cb does not have the "register name" parameter, instead of the address parameter? This way the callback would be much useful. This is a very bad way to iterate through ALL registers to find the correct "register name" and then do the operation (e.g assign the desired value).

Omid888 commented 3 months ago
  1. And why at the end of every on_get_cb() function, should be a client.setup_registers(registers=register_definitions) function? shouldn't that be done automatically?