Script for incrementing a value sent on a mqtt topic

hello,
I still need a little help. and it’s not easy to explain.
It is a modified position control by entering the value on a keyboard then validation by “enter” key

I’m looking for a script that allows you to send the MQTT command on the keyboard of 4 + 2 characters (enter) on a topic that only accepts one digit at a time (like keyboard).
I have to send for example 0123 (position value) then 13 (enter key) on this topic
today i do it this way

  touche_0:
    alias: "0"
    sequence:
      service: mqtt.publish
      data:
        topic: "/Cmd/Keyboard"
        payload: "0"
        

then the 1
then the 2
then the 3
and finally command 13 (enter).

In addition, I need to increment this sequence from 1 to 1 until I reach a threshold. 0001 to 1600.

Today, it is not automated and I would like to do it by creating a loop which sends these commands from 1 to 1600 until I receive information on another topic which informs me that I have reached the good threshold.

Does anyone already have an automation like this and how can I please?

We’re working on a repeat loop for scripting that will make this a cinch. Hopefully it will be available in the 0.113 release.

1 Like

Currently, scripts are not well suited for looping (it can be done but it’s a bit clumsy). I think your best strategy would be to do this in python, using the python_script integration, instead of a script.

This is just a sample of what you will need to do. It publishes '0', waits a half-second, publishes '1', waits a half-second, etc up to publishing '3' and then exists the for-loop to publish '13'.

    for i in range(4):
      service_data = {'topic':'/Cmd/Keyboard', 'payload':'{}'.format(i), 'qos':0, 'retain':'false'}
      hass.services.call('mqtt', 'publish', service_data, False)
      time.sleep(0.5)

    service_data = {'topic':'/Cmd/Keyboard', 'payload':'13', 'qos':0, 'retain':'false'}
    hass.services.call('mqtt', 'publish', service_data, False)

EDIT
While composing the python_script, pnbruckner has let the cat out of the bag. :slight_smile: So you may wish to wait for when his script enhancements are released and then it will be very easy to perform looping with a script.

1 Like

Thank you for this track.
It is true that I am no longer in home automation but more on industrial automation. But HA is a great tool for doing a whole bunch of things, even in the industry.