From Tuya Cloud to Berry on OpenBeken
I bought a Tuya smart socket because I wanted a smart socket.
Before long, I was extracting encryption keys, opening plastic cases, soldering UART wires, debugging unfamiliar Wi-Fi chips and adding a programming language to alternative firmware.
The socket itself was only the beginning.
Local, with permission
My first attempt at controlling the socket was through Tuya’s supported path. I created a cloud project, obtained API credentials and used TinyTuya to discover the device’s local key. With the device ID, address and key, a Python program on my network could switch the outlet without sending every command through the cloud:
import tinytuya
d = tinytuya.OutletDevice(dev_id=DEVICE_ID, address=ADDRESS, local_key=LOCAL_KEY, version=3.4)
d.turn_off()
This worked, but there was an awkward dependency hiding in the word “local”. The socket accepted local commands, but obtaining the key required Tuya’s API. My API access was a trial subscription which expired. I could ask for an extension, but that merely changed the expiry date.
The first note on my Tuya project page became:
DUMP THE LOCAL KEYS AS SOON AS POSSIBLE
I had local control of hardware I owned, for as long as I retained a secret which somebody else’s service had temporarily agreed to reveal. That was better than mandatory cloud control, but it was not the arrangement I wanted.
The monitors from hell
The socket had a job waiting for it.
My NVIDIA system had three monitors, including a Samsung Odyssey G7. Sometimes waking them from deep sleep hung the graphics stack or the whole machine. This was not an entirely novel failure: reports about Odyssey G7, G8 and G9 displays failing to wake, showing a black screen or freezing NVIDIA systems were easy to find.
I tried the civilized fixes first. I looked at driver versions, turned off Adaptive Sync and G-SYNC, and went through refresh-rate combinations. The problem remained intermittent, which made every attempted fix particularly convincing right until it failed again.
The uncivilized fix was to remove AC power from the monitors when the screen blanked, and restore it when the session woke. That was the socket’s job. In Tuya’s app I had named it “Monitory”, which is Polish for monitors.
So a cheap socket was about to become part of my computer’s reliability, and its key came from a trial subscription.
Replacing the firmware
In September 2024 I started looking for alternative firmware. Before opening the socket, I also tried to understand what its stock firmware was saying on the network.
I found EspTuya, an Arduino sketch which implemented enough of Tuya’s local protocol to parse and decrypt messages.
It was messy, but I was glad it existed.
I ran it against the socket and captured a 204-byte UDP broadcast beginning with Tuya’s 0x000055aa header.
The parser identified protocol command 0x23, decrypted the AES-128 payload and recovered the device’s JSON announcement, including its address, gateway ID, product key and protocol version 3.4.
That was a useful look below TinyTuya’s interface. The supposedly simple local switch was speaking a framed, encrypted protocol with version-specific behavior, CRCs and discovery messages. I thought about cleaning EspTuya up into a proper project, but never did.
The socket contained a Tuya T34 module, which is a BK7231N, and OpenBeken supported it. OpenBeken is open-source firmware for a broad collection of Wi-Fi and Bluetooth microcontrollers found in inexpensive smart devices. It provides local HTTP and MQTT control and a substantial amount of compatibility with Tasmota’s interfaces.
The attractive route was an over-the-air conversion.
I tried tuya-convert, but newer Tuya firmware had closed that route with a different PSK identity mechanism.
So, in February 2025, I opened the socket.
Next to the Wi-Fi module the board had a BL0942 chip for power measurement and an AMS1117 regulator.
I soldered wires to the serial pins and to the regulator, so that I could run the board from 12 V on the bench instead of from the mains.
Then I used hid_download_py to talk to the bootloader.
It did not work cleanly at first. Reads came back with CRC errors, and some devices only cooperated at a lower baud rate. In the end I dumped the stock firmware, wrote OpenBeken and ignored the CRC complaints.
A later device taught me more about failures like that. It had an LN882H chip, and nothing I tried could talk to it. I suspected the tools, and then the 3.3 V supply. Finally I pulled out a logic analyzer and found that my FTDI adapter wasn’t sending anything on its transmit line. A CH340G adapter worked right away. The strange part is that I had flashed six BK7231 chips with that same FTDI adapter.
That is now one of my standard debugging steps. When a serial protocol makes no sense, check whether there is actually a serial waveform before developing a theory about the protocol.
With OpenBeken on the socket, I configured the relay, LED, button and power meter. It no longer needed a Tuya account, an API trial or a preserved local key.
Now the monitors could get their uncivilized fix. I wrote a watchdog which listened to XScreenSaver:
BLANK
UNBLANK
It delayed and coalesced those events, called the socket’s HTTP API, and dealt with the consequences of displays physically disappearing from X11. On power-on it moved an i3 workspace back to the right output. It also stopped and restarted Plasma and picom around the transition, because they otherwise consumed CPU or became confused by the changing display topology.
The setup was absurdly specific to my computer, but it worked. The monitors no longer got an opportunity to negotiate their unreliable wake-up path. They woke because a relay restored mains power.
One socket becomes a collection
After the first conversion, I started opening the other devices.
The collection grew to include sockets for the monitors, television and 3D printer, as well as scene buttons, a USB adapter, smart switches, an IR remote, sensors and lights. OpenBeken’s Tasmota-compatible HTTP interface let the OctoPrint-Tasmota plugin control the printer outlet. Simple rules gave one of the sockets a timed shutoff. The sockets that measure power had to be calibrated again, which I did with a multimeter and a 40 W incandescent bulb.
Not every device used the same chip. I encountered BK7231 variants, LN882H, BL602 and ECR6600 modules, each with different tools and different ways to fail.
I documented that work as niterian on Elektroda.
For the LN882H device I unpacked Tuya’s own flashing tool, which turned out to be a Python program packed with PyInstaller, and compared its protocol with the open-source loader.
The dead UART adapter is written up there too, and so is a crash in OpenBeken’s GPIO Doctor on pin P13.
For a BL602 switch I desoldered the module because its serial pins were hard to reach, flashed it with BouffaloLab’s tool, and posted the log and the configuration that worked.
This was my route into the OpenBeken community. I had begun as a user trying to make some sockets independent. Soon I was filing bug reports from real devices and testing the fixes.
The limits of a command language
OpenBeken already had useful scripting. Commands, aliases, change handlers and scheduled events could express a surprising amount of automation. My devices were proof of that.
They also exposed rough edges.
I reported that SendGet could not authenticate when one password-protected OpenBeken device needed to control another.
I found that an IR event registered with addEventHandler3 ignored its third argument, the one that tells a held button from a fresh press.
That one came up while turning on an Xbox.
And a power-threshold handler never fired below 20 watts.
I misread the code while looking for the reason.
Another contributor, xjikka, found it: those events were only processed when MQTT was enabled, and I had it disabled.
For larger scripts I wanted ordinary language features: functions, closures, modules, callbacks and a persistent interpreter. I also liked OpenBeken’s goal of Tasmota compatibility. Tasmota already had an answer to this problem: Berry.
Berry is a small dynamically typed language designed for embedded systems. Tasmota uses it as a higher-level scripting environment over firmware APIs. On 23 February 2025 I compiled Berry from its repository and started putting it into OpenBeken.
Can it turn off a socket?
The first goal was deliberately small.
I added a berry console command which evaluates its argument as Berry code, and bound one OpenBeken function to it:
berry channelSet(1, 0)
It turned off my smart plug.
The same day I opened PR #1544, “[POC] Run berry-lang”. The description was candid about the state of it. The proof of concept created a new VM for each evaluation, many Berry features were disabled, the build integration was messy, and I did not know what it would cost in binary size, RAM and stack on OpenBeken’s many targets. OpenBeken also already had a scripting language, so “here is another language” was not self-evidently an improvement.
The longer-term case was stronger:
- Berry APIs compatible with Tasmota’s;
- an
autoexec.bethat runs at startup; - reusable modules stored on the device’s filesystem and shared between users.
The maintainer answered the same evening:
Very nice and promising […] I really like the idea. I’ve been thinking about doing similar but I considered lua, didn’t check out berry yet but it seems good.
He built it too. The firmware for the BK7231N grew from 486 KB to 531 KB.
He also wanted it in OpenBeken’s Windows simulator, which is where the project’s self-tests run.
Getting it there found a bug in Berry itself.
Built with Microsoft’s compiler, Berry’s ffs function was off by one, and the interpreter corrupted its own memory as soon as it started.
I reported it with a fix.
One of Berry’s maintainers replied: “Oh this is bad. I never compiled under MSVC so I never saw the problem.”
The fix was merged the next day, and two more small ones followed.
The tiny relay test grew. I worked on closures, callbacks, timers, file imports and the lifetime of the interpreter. I studied how Tasmota kept one interpreter alive and connected its timers to the host firmware.
By 10 March this made my plug toggle every second:
state = 1
var tick
def tick()
state = 1 - state
channelSet(1, state)
delayMs(1000, tick)
end
tick()
Two days later the firmware could import an autoexec.be module, and I had ported a countdown timer to it.
It watched a relay, counted a channel down once per second, let the duration be changed from the web interface, and switched the load off at zero.
It was a port of a timer script I already ran on one of the sockets.
That evening I wrote that the pull request had “achieved its proof-of-concept goals and reached its threshold of usefulness”. Within hours another contributor, NonPIayerCharacter, had an AHT10 temperature sensor talking over I2C from a Berry script. The maintainer’s verdict was “certainly worth merging as-is”, as long as it was disabled by default.
The PR was merged on 30 March 2025.
A real device finds a real limit
I eventually used Berry in a two-button page-turning remote for KOReader on a Kindle. That project has its own longer story, but one part belongs here because it found a firmware problem.
The Berry module handled the two buttons, the requests to KOReader, an inactivity timer and deep sleep.
Importing the module from the console worked.
Importing it from an addRepeatingEvent timer crashed the BK7231N.
The same Berry code was running in two different RTOS tasks: the HTTP handler had enough stack, and the timer task did not.
I measured each task’s free stack, raised the timer task’s stack size, and the import worked.
The diagnosis is in issue #1663.
On the remote I worked around it by having the timer only schedule the import.
The language passed its tests on a desktop and ran correctly through one entry point, then fell over because another entry point ran it on a smaller stack.
Berry finds bugs below Berry
Some crashes that looked like Berry problems were defects lower in the platform.
While debugging the proof of concept in March, I noticed that realloc on my BK7231T device sometimes returned memory whose old contents had been overwritten.
It was a known problem.
I extended OpenBeken’s allocator test so that it resizes allocations over and over and checks that their contents survive (PR #1563).
In May the same test failed on a BK7231N, and I added a workaround on the Berry side (PR #1649).
I suspect it was behind the crashes I had been getting when importing big modules.
I fixed the Berry tests on Linux, where they were segfaulting because pointers were being cast to int, and made closure calls accept any number of arguments (PR #1640).
Then I made it possible to run the Linux tests under AddressSanitizer (PR #1651).
The sanitizer immediately justified its presence.
It found an out-of-bounds read where a TuyaMCU channel mapping of -999 was used to index the channel-type array (PR #1652).
The same day I fixed a memory leak in the HTTP functions (PR #1653).
UndefinedBehaviorSanitizer followed (PR #1664).
What it reports are shifts into the sign bit in the code that handles flags.
A socket automation motivated an embedded-language experiment. The language exercised memory allocation and task stacks in new ways. Making those failures reproducible improved the host project’s tests. The improved tests found unrelated bugs.
Local means maintainable
My original problem was not that the Tuya socket failed to work. It worked exactly as sold. I could even control it locally after using the cloud API to obtain its key.
The problem was the ownership model around that success. API access expired. Local control depended on retaining cloud-issued secrets. The socket was meant to become part of my computer’s reliability, and I did not want its future tied to a trial subscription.
Flashing OpenBeken solved that immediate problem. It also changed my relationship with the devices. A sealed product became a board I could inspect, back up, reflash, debug and improve. That experience later made alternative-firmware support a buying criterion for a Tapo C210 camera. When something did not work, I could trace it from a physical UART waveform through an RTOS task and into a Linux sanitizer run. When the fix was generally useful, I could send it upstream.
The journey ended much further from Tuya’s API than I expected. The monitors had a dependable power switch. The Kindle had a two-button remote. OpenBeken had Berry, stronger allocator tests, sanitizer builds and several fixes those tests exposed.
All I had wanted was to turn a socket on and off.