Switch function . modbus write

I need to make a simple switch. But I don’t know the best way to do this.

It’s a switch that have two functions. An on function and an off function.

When switch is on, it should make a modbus write to a register. When off, it should make another modbus write and stop the on write.

I’m thinking a switch with some automation That looks for switch on / off, and call service modbus.write based on switch state.

But maybe there’s a smarter way to do so. ?