logo elektroda
logo elektroda
X
logo elektroda

Scripting the behaviour of TuyaMCU relay OpenBeken - custom buttons, timers, events, countdown

p.kaczmarek2 3858 0

TL;DR

  • Scripts for a TuyaMCU BK7231N thermostat relay running OpenBeken add custom buttons, timers, a countdown display, and relay-state mapping.
  • The setup maps TuyaMCU dpIDs to OBK channels, then uses a looped script with addChangeHandler and HTTP buttons for predefined time spans.
  • The relay uses TuyaMCU baud rate 115200, maps dpID 1 to channel 1 and dpID 24 to channel 2, and refreshes state every 10 seconds.
  • The countdown works on the OBK page and in Home Assistant, but automatic temperature control and other MCU dpIDs are left for another part.
Generated by the language model.
ADVERTISEMENT
📢 Listen (AI):
  • Electrical socket with a connected temperature sensor and wire, placed on a power strip.
    Here I will show you how you can script the behaviour of TuyaMCU BK7231N relay flashed with OpenBeken firmware. In this topic I will cover a creation of scripts, mapping TuyaMCU variables to OpenBeken channels, displaying them, creation of custom HTTP buttons and setup of a custom OBK script timer.
    This topic will not cover the automatic temperature/heating control itself, because I am planning to show it in the separate part.

    Requirements
    This topic assumes that you already have device flashed with OpenBeken:
    https://github.com/openshwprojects/OpenBK7231T_App
    You can find more about flashing such devices on our Youtube channel:
    https://www.youtube.com/@elektrodacom
    Or on our Elektroda teardowns list:
    https://openbekeniot.github.io/webapp/devicesList.html

    Futhermore, I already assume that you know the dpIDs used by your device. You can use our TuyaMCUAnalyzer for that:
    https://github.com/openshwprojects/TuyaMCUAnalyzer
    See related topic:
    https://www.elektroda.com/rtvforum/topic3970199.html#20528459

    Used device
    For this topic I used a TuyaMCU BK7231N thermostat (relay+external temperature probe) device, but in this case I will focus mostly on the relay control:
    TuyaMCU socket adapter on a wooden table Smart electric socket with an external temperature probe. Smart plug connected to a power strip White electric plug adapter on a wooden surface.

    Basic TuyaMCU setup
    The setup of TuyaMCU itself is not the main point of this topic, as we have already covered it in the other threads, for example:
    https://www.elektroda.com/rtvforum/topic3898502.html
    but I will still write a few words about it here.
    TuyaMCU is using (already mentioned) dpIDs, which are the identifactors of the variables. Those variables also have their types, like integer, enum, or a boolean. In order to use TuyaMCU, you need to guess the meanings of the dpIDs.
    I am usually doing the UART capture of TuyaMCU communication between the MCU and the WiFI module with Tuya firmware. I am just changing the things in Tuya App and observing what kind of data is sent.
    For this device, we basically need two dpIDs:
    - relay control (boolean, 1 or 0), which can be send from MCU to WiFI module when user presses a button on case, or which can be send from WiFi module to the MCU when you want to toggle relay from the app
    - the temperature measurement, which is always send from MCU to WiFI module
    So, let's setup this in OBK. Create autoexec.bat in LittleFS:
    
    // start TuyaMCU driver
    startDriver TuyaMCU
    // set TuyaMCU baud rate
    tuyaMcu_setBaudRate 115200
    // set TuyaMCU default wifi state 0x04, which means "paired",
    // because some TuyaMCU MCUs will not report all data
    // unless they think they are connected to cloud
    tuyaMcu_defWiFiState 4
    // set channel 1 to display toggle
    setChannelType 1 Toggle
    // Map given dpID to channel 1, dpID type bool
    // linkTuyaMCUOutputToChannel [dpId][varType][channelID]
    linkTuyaMCUOutputToChannel 1 bool 1
    // channel 2 will be temperature
    setChannelType 2 temperature
    // Map given dpID to channel 2, dpID type value
    linkTuyaMCUOutputToChannel 24 val 2
    

    Save and reboot, you will get the following controls:
    OpenBeken control interface screen with temperature information.
    But that's just the beginning...
    For convencience, we can also start NTP (time from web) and SSDP (make device discoverable on local network) drivers:
    
    startDriver NTP
    startDriver SSDP 
    


    One important thing to note - this TuyaMCU has more dpIDs which are not covered in this topic. It is possible to use those dpIDs to setup a thermostat behaviour on the MCU itself (without OpenBK scripting), but I will cover it another time.

    Extending the script
    Let's say that we want to have ability to enable the relay for a given amount of time. After that time passes, the relay goes back to the previous (open) state.
    We can do that entirely in script. We basically need to:
    - choose arbitrary obk channel as a time variable
    - create a timer (we'll do that in a loop) that will turn off relay after given time
    - create http buttons for predefined time spans
    - create a field where user can enter a time of his choice
    - display the remaining time on http page
    - do some miscellaneous stuff like resetting timer when user forces the relay to be off

    Here is the full code - see comments for details.
    
    
    // setup cosmetics for channel 10, channel labels can have HTML codes
    setChannelLabel 10  "<b><span style='color:orange'\>Time left</span></b>"
    // set channel 10 to display formatted time
    setChannelType 10 TimerSeconds
    
    // create command aliases for enable + setup delay (in channel 10) sequences
    alias enable_30min backlog POWER ON; setChannel 10 30*60
    alias enable_30sec backlog POWER ON; setChannel 10 30
    
    // set channel 11 label, channel 11 will allow to enter hours value of new timespan
    setChannelLabel 11  "<b><span style='color:orange'\>Custom time setting [hours]</span></b>"
    setChannelType 11 TextField
    
    // start driver handling extra buttons on http page
    startDriver httpButtons
    // button 0 - set enable to 1
    setButtonEnabled 0 1
    // set button 0 label
    setButtonLabel 0 "Enable for 30 minutes"
    // set button 0 command (see alias created above)
    setButtonCommand 0 "enable_30min"
    // set button 0 color (CSS color code)
    setButtonColor 0 "green"
    
    // when anything sets relay to off, also clear timer
    addChangeHandler Channel1 == 0 setChannel 10 0
    // if user manually sets channel 1 with no timer, then set default time - you can change 1234 to any value in seconds
    addChangeHandler Channel1 == 1  if $CH10==0 then "setChannel 10 1234"
    
    // just like for button 0, also setup button 1
    setButtonEnabled 1 1
    setButtonLabel 1"Enable for 60 minutes"
    setButtonCommand 1 "enable_60min"
    setButtonColor 1 "green"
    
    // just like for button 0, also setup button 2
    startDriver httpButtons
    setButtonEnabled 2 1
    setButtonLabel 2 "Enable for 30 sec"
    setButtonCommand 2 "enable_30sec"
    setButtonColor 2 "green"
    
    
    // every 10 seconds, request update from TuyaMCU
    addRepeatingEvent 10 -1 tuyaMcu_sendQueryState
    
    // now this part runs in a loop
    again:
    // wait one secnd
    delay_s 1
    // if channel sued for timer has reached 0, time off
    if $CH10<=0 then POWER OFF
    
    // subtract one from time, clamp at 0 and 99999
    addChannel 10 -1 0 999999
    
    // continue the loop forever
    goto again
    

    Here is how it looks on OBK page:
    OpenBeken interface screen with TuyaMCU settings and timer
    OpenBK7231N interface page with relay enabled for 30 minutes.
    Each button is fully functional. The timer is automatically refreshed and formatted. The custom delay also works, it can be set either via OBK page or via Home Assistant. The countdown timer can be also accessed in Home Assistant if you write custom yaml to listen to countdown variable channel.

    Linking device with HA
    The basic functionality of this device can be added to HA via Home Assistant Discovery in OBK:
    https://www.youtube.com/watch?v=pkcspey25V4&ab_channel=Elektrodacom
    The custom functions can be exposed via custom yaml. See our MQTT commands/channel access docs:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/mqttTopics.md

    Linking device with HTTP
    You can also report data directly to HTTP server via GET or POST. Everything was covered in the linked topic:
    https://www.elektroda.com/rtvforum/topic4007790.html

    Linking the behaviour of the relay to the temperature
    I am planning to release a separate guide on this topic, but basically, in OpenBeken you can either:
    - check the temperature in the loop and act according to that, possibly with a delay
    - use change handler to detect when a temperature changes over a certain threshold and then change the relay state:
    
    addChangeHandler Channel0 < 50 echo value is low
    

    I am also planning to make a C driver for a thermostat, but that's a plan for the future.

    Linking the behaviour of the relay to the current time
    It is also possible to relate relay behaviour to the current time we've got from NTP. There are two ways to do that:
    - use addClockEvent:
    Section of documentation about the addClockEvent function in OpenBeken.
    This can be used to run any script at given time of given day of week.
    - use $hour or $minute variable and check its value with if conditional expression

    See more:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/commands.md
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/README.md
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/constants.md

    You can also see more autoexec.bat examples at:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/autoexecExamples.md

    Summary
    So now you have learned how to configure a TuyaMCU relay in OpenBeken. The same logic can apply to a normal relay, where you just need to set the channel of relay pin to the same channel you have in the script. Everything else will work the same.
    Keep in mind that the same could be done in Home Assistant, but with OBK scripting, no Home Assistant is needed. This might give you an advantage when, for example, you don't want to setup HA for a single automation.
    That's all for now, thank you for reading. In the next part I will show how to setup a thermostat. Stay tuned.

    Cool? Ranking DIY
    Helpful post? Buy me a coffee.
    About Author
    p.kaczmarek2
    Moderator Smart Home
    Offline 
    p.kaczmarek2 wrote 14589 posts with rating 12611, helped 654 times. Been with us since 2014 year.
  • ADVERTISEMENT
📢 Listen (AI):

FAQ

TL;DR: With 2 mapped dpIDs and a 1-second loop, you can script an OpenBeken TuyaMCU relay to run timed actions; as the guide says, "that's just the beginning." This FAQ is for BK7231N users who want custom buttons, countdown timers, and event-based relay control without needing Home Assistant. [#20777858]

Why it matters: It shows how to move relay timing, display logic, and scheduled actions onto the device itself, reducing dependence on external automation.

Option Where logic runs What the thread says Best fit
TuyaMCU-side thermostat behavior MCU firmware Possible through additional dpIDs, but not covered here Use when you want built-in thermostat behavior
OpenBeken scripting OBK script engine Handles timers, buttons, events, NTP scheduling, and relay logic Use when you want custom local automation
Home Assistant automation External controller Can do similar tasks, but OBK scripting avoids needing HA Use when you already run HA

Key insight: OpenBeken treats TuyaMCU data as channels, so once you map dpIDs correctly, you can build relay timers, HTTP controls, temperature triggers, and clock-based schedules with one script. [#20777858]

Quick Facts

  • The basic example maps dpID 1 as a bool to channel 1 for relay control and dpID 24 as a value to channel 2 for temperature reporting. [#20777858]
  • The timer example uses channel 10 as TimerSeconds for the countdown display and channel 11 as TextField for a custom time entry in hours. [#20777858]
  • The script refreshes TuyaMCU state every 10 seconds with addRepeatingEvent 10 -1 tuyaMcu_sendQueryState and decrements the countdown every 1 second in a loop. [#20777858]
  • Preset actions shown in the thread include 30 seconds, 30 minutes, and 60 minutes, all triggered by custom HTTP buttons. [#20777858]
  • Startup commands shown for this device include startDriver TuyaMCU, tuyaMcu_setBaudRate 115200, tuyaMcu_defWiFiState 4, plus optional startDriver NTP and startDriver SSDP. [#20777858]

How do I script a TuyaMCU BK7231N relay in OpenBeken so it turns on for a set time and then switches off automatically?

Use an OpenBeken script that turns the relay on, stores a countdown in a channel, and decrements that value every 1 second until it reaches 0. The thread uses POWER ON, setChannel 10 30*60 for 30 minutes, then checks if $CH10<=0 then POWER OFF. 1. Map the relay dpID to a control channel. 2. Set channel 10 as TimerSeconds. 3. Run a loop with delay_s 1 and addChannel 10 -1 0 999999. [#20777858]

What is TuyaMCU in the context of OpenBeken devices, and how do dpIDs work?

"TuyaMCU" is a device-side microcontroller interface that exchanges typed data points with the Wi-Fi module, using numbered dpIDs as variable identifiers. In this thread, dpIDs carry values such as relay state and temperature, and each dpID has a type like bool, val, or enum. OpenBeken works only after you identify what each dpID means for your specific device. [#20777858]

How can I map TuyaMCU dpIDs to OpenBeken channels for relay control and temperature reporting?

Map each TuyaMCU dpID to an OpenBeken channel with linkTuyaMCUOutputToChannel. The thread sets setChannelType 1 Toggle and maps relay control with linkTuyaMCUOutputToChannel 1 bool 1. It then sets setChannelType 2 temperature and maps temperature with linkTuyaMCUOutputToChannel 24 val 2. After saving autoexec.bat and rebooting, both controls appear on the OBK page. [#20777858]

Why do I need to set tuyaMcu_defWiFiState 4 in OpenBeken, and what does the paired state change on some TuyaMCU devices?

You set tuyaMcu_defWiFiState 4 so some TuyaMCU devices behave as if they are paired and report full data. The thread states that value 0x04 means "paired" and notes that some MCUs will not report all data unless they think they are connected to the cloud. If your flashed BK7231N device shows incomplete data, this setting is a key fix. [#20777858]

What is autoexec.bat in OpenBeken, and what kinds of startup commands should go into it for a TuyaMCU relay?

autoexec.bat is the OpenBeken startup script stored in LittleFS, and it should contain driver starts, baud rate setup, Wi-Fi state, channel types, and dpID mappings. The thread puts startDriver TuyaMCU, tuyaMcu_setBaudRate 115200, tuyaMcu_defWiFiState 4, and two linkTuyaMCUOutputToChannel commands in it. It also recommends optional startDriver NTP and startDriver SSDP for time sync and local discovery. [#20777858]

How can I create custom HTTP buttons in OpenBeken for preset relay countdown times like 30 seconds or 30 minutes?

Create aliases for each preset time, start the httpButtons driver, then bind each button to an alias. The thread uses alias enable_30min backlog POWER ON; setChannel 10 30*60 and alias enable_30sec backlog POWER ON; setChannel 10 30. It then enables buttons, sets labels like "Enable for 30 minutes," assigns commands, and colors them green with setButtonColor. [#20777858]

What is the best way to display and update a countdown timer on the OpenBeken web interface using TimerSeconds and custom channels?

Use a dedicated channel with TimerSeconds, then reduce that channel once per second in the main script loop. The thread sets setChannelLabel 10 to a styled HTML label, then setChannelType 10 TimerSeconds so the web UI formats the remaining time automatically. It updates the value with addChannel 10 -1 0 999999, which also clamps the range. [#20777858]

How do addChangeHandler and addRepeatingEvent work in OpenBeken scripts for relay timers and event-driven automation?

addChangeHandler reacts when a channel changes, while addRepeatingEvent runs a command at fixed intervals. The thread uses addChangeHandler Channel1 == 0 setChannel 10 0 to clear the timer when the relay turns off. It also uses addRepeatingEvent 10 -1 tuyaMcu_sendQueryState to query TuyaMCU state every 10 seconds for ongoing synchronization. [#20777858]

What causes a TuyaMCU relay timer script to reset or stop unexpectedly when the relay is turned off manually?

A manual relay-off action resets the timer if you explicitly attach a change handler for that case. The thread adds addChangeHandler Channel1 == 0 setChannel 10 0, so any action that sets channel 1 to 0 also clears channel 10. That behavior is intentional, not a fault, and it prevents a stale countdown from continuing after the relay is already off. [#20777858]

How can I expose custom OpenBeken channels such as a countdown timer to Home Assistant using MQTT and custom YAML?

Expose the basic device through OpenBeken Home Assistant Discovery, then publish custom channels through MQTT and define them in custom YAML. The thread says the countdown variable channel can be accessed in Home Assistant if you write custom YAML to listen to that channel. It also points to the OpenBeken MQTT commands and channel-access documentation for the exact topic structure. [#20777858]

What is the difference between handling thermostat logic on the TuyaMCU itself and doing it in OpenBeken scripting?

TuyaMCU-side logic uses extra thermostat dpIDs on the MCU, while OpenBeken scripting builds the behavior in the OBK layer with loops, events, and channel rules. The thread says this device has more dpIDs that can set thermostat behavior on the MCU itself, but the shown example keeps control in OpenBeken. That approach works even without Home Assistant and can be adapted to a normal relay. [#20777858]

How do I use NTP time in OpenBeken to control a relay by schedule with addClockEvent, $hour, or $minute?

Start the NTP driver, then trigger actions either with addClockEvent or by checking $hour and $minute in script conditions. The thread gives two methods: scheduled script execution at a given time and day of week, or direct checks against clock variables. 1. Add startDriver NTP. 2. Use addClockEvent for fixed schedules. 3. Use if with $hour or $minute for custom time logic. [#20777858]

Which tools are used to identify TuyaMCU dpIDs before writing an OpenBeken script, and how does TuyaMCUAnalyzer fit into the process?

The thread uses UART capture and TuyaMCUAnalyzer to identify dpIDs before scripting. The author watches communication between the MCU and the Wi-Fi module while changing settings in the Tuya app, then interprets which dpIDs represent functions like relay control or temperature. TuyaMCUAnalyzer helps decode that traffic so you can map the right dpIDs in OpenBeken. [#20777858]

How can I link relay behavior to temperature changes in OpenBeken using loops or addChangeHandler thresholds?

You can poll the temperature in a loop or trigger actions when a channel crosses a threshold. The thread gives a direct example: addChangeHandler Channel0 < 50 echo value is low. That means you can switch the relay when a measured value rises above or falls below a target, and you can add delays if you prefer loop-based control. [#20777858]

What troubleshooting steps help when a flashed BK7231N thermostat with OpenBeken is not showing all TuyaMCU data or controls correctly?

Check the dpIDs first, then verify the TuyaMCU startup settings and channel mappings. The thread recommends identifying dpIDs with UART capture or TuyaMCUAnalyzer, starting the TuyaMCU driver, setting the baud rate to 115200, and forcing tuyaMcu_defWiFiState 4 because some devices hide data unless they believe they are cloud-paired. Reboot after saving autoexec.bat, then confirm channel types and mappings for relay and temperature. [#20777858]
Generated by the language model.
ADVERTISEMENT