[SOLVED] Channel select with broadlink and mqtt

First things first, please use the code fences when publishing code, thanks

There are several solutions to your problem.

  • Solution 1: Use timers (Recommended)
var topic = "" //AT THE TOP OF THE RULES FILE!!

rule “Tvswitcher”
when
    Item Channel_select changed
then
    if (Channel_select.state == “NULL”) return; // If NULL do nothing
    topic = “broadlink/tvswicher/select/tv” + Channel_select.state.toString.substring(0, 1)
    publish(“mosquitto”, topic, “play-0d43b4e42518”)
    createTimer(now.plusSeconds(1), [ |
        topic = “broadlink/tvswicher/select/tv” + Channel_select.state.toString.substring(1, 2)
        publish(“mosquitto”, topic, “play-0d43b4e42518”)
    |]
    createTimer(now.plusSeconds(2), [ |
        topic = “broadlink/tvswicher/select/tv” + Channel_select.state.toString.substring(2)
        publish(“mosquitto”, topic, “play-0d43b4e42518”)
    |]
end

If the string was longer we would use a loop through the string an increment the substring indexes when looping but as you only have 3 characters this should be enough and writing the loop will not save lines of code

When the rule executes it will send the find message straight away and create 2 timers to be executed 1 seconds after and 2 seconds after with the respective topics. Because the timers are execute outside the rule, we need to move the declaration of the topic variable to the top of the rules file and that it’s scope becomes global and can be accessed by the timers.

  • Solution 2: Use Thread::sleep (Not recommended)
rule “Tvswitcher”
when
    Item Channel_select changed
then
    if (Channel_select.state == “NULL”) return; // If NULL do nothing
    var topic = “broadlink/tvswicher/select/tv” + Channel_select.state.toString.substring(0, 1)
    publish(“mosquitto”, topic, “play-0d43b4e42518”)
    Thread::sleep(1)
    topic = “broadlink/tvswicher/select/tv” + Channel_select.state.toString.substring(1, 2)
    publish(“mosquitto”, topic, “play-0d43b4e42518”)
    Thread::sleep(1)
    topic = “broadlink/tvswicher/select/tv” + Channel_select.state.toString.substring(2)
    publish(“mosquitto”, topic, “play-0d43b4e42518”)
end
2 Likes