Visual programming for Sonoff Basic

Visual programming for Sonoff Basic
An article on how to create a programmable logic controller from a cheap Chinese device. This device can be used for home automation as well as for practical computer science classes in schools.
For reference, by default, the Sonoff Basic program works with a mobile application through a Chinese cloud service, but after the proposed modifications, all further interactions with this device will be possible through a browser.

Section I. Connecting Sonoff to the MGT24 service

Step 1. Creating a control panel

Register on the website mgt24 (if not already registered) and log in to your account.
LoginVisual programming for Sonoff Basic

To create a control panel for the new device, click the ‘+’ button.
Example of panel creationVisual programming for Sonoff Basic

After the panel is created, it will appear in your list of panels.

In the ‘Setup’ tab of the created panel, locate the ‘Device ID’ and ‘Authorization Key’ fields; this information will be needed for setting up the Sonoff device.
Example tabVisual programming for Sonoff Basic

Step 2. Flashing the device

Using the utility XTCOM_UTIL upload the firmware PLC Sonoff Basic to the device; for this, you will need a USB-TTL converter. Here’s the the instruction and video guide.

Step 3. Configuring the device

Power the device, and once the LED lights up, press and hold the button until the LED starts blinking periodically.
At this moment, a new Wi-Fi network named ‘PLC Sonoff Basic’ will appear; connect your computer to this network.
Decoding LED indicators

LED indicators
Device status

periodic double blinking
no connection to the router

steady light
connection to the router established

periodic steady blinking
Wi-Fi access point mode

off
no power

Open a web browser and enter ‘192.168.4.1’ in the address bar to go to the device network settings page.

Fill in the fields as follows:

  • ‘Network Name’ and ‘Password’ (to bind the device to your home Wi-Fi router).
  • ‘Device ID’ and ‘Authorization Key’ (for device authorization on the MGT24 service).

Example of device network settingsVisual programming for Sonoff Basic

Save the settings and reboot the device.
Here video guide.

Step 4. Connecting Sensors (Optional)

The current firmware supports up to four ds18b20 temperature sensors. Here video guide is the installation of the sensors. Apparently, this step will be the most challenging, as it will require skilled hands and a soldering iron.

Section II. Visual Programming

Step 1. Creating Scripts

The programming environment used is Blockly, which is easy to learn, so you don’t need to be a programmer to create simple scripts.

I added specialized blocks for reading and writing device parameters. Access to any parameter is done by name. For parameters of remote devices, composite names are used: ‘parameter@device’.
Parameter Dropdown ListVisual programming for Sonoff Basic

Example of a script for toggling a load on and off (1Hz):
Visual programming for Sonoff Basic

Example of a script that synchronizes the operation of two separate devices. Specifically, the relay of the target device replicates the work of the relay of the remote device.
Visual programming for Sonoff Basic

Script for a thermostat (without hysteresis):
Visual programming for Sonoff Basic

To create more complex scripts, you can use variables, loops, functions (with arguments), and other constructs. I won’t go into detail here, as there is already quite a lot of educational material about Blockly.

Step 2. Execution Order of Scripts

The script runs in continuous mode, and as soon as it reaches its end, it starts again. There are two blocks that can temporarily pause the script’s execution: ‘delay’ and ‘pause’.
The ‘delay’ block is used for millisecond or microsecond delays. This block strictly maintains the time interval, blocking the operation of the entire device.
The ‘pause’ block is used for second (or shorter) delays, and it does not block the execution of other processes in the device.
If a script contains an infinite loop without a ‘pause’, the interpreter will independently initiate a short pause.
In case of exhausting the allocated stack memory, the interpreter will stop the execution of such a resource-intensive script (be cautious with recursive functions).

Step 3. Debugging Scripts

To debug a script that has already been uploaded to the device, you can run a step-by-step tracing of the program. This can be extremely useful when the script's behavior is not as intended by the author. In this case, tracing allows the author to quickly find the source of the problem and fix the error in the script.

Factorial calculation script in debug mode:
Visual programming for Sonoff Basic

The debugging tool is very simple and consists of three main buttons: 'start', 'step forward', and 'stop' (also don't forget about 'enter' and 'exit' debug mode). In addition to step-by-step tracing, you can set a breakpoint on any block (by clicking on the block).
To display the current values of parameters (sensors, relays) on the monitor, use the 'print' block.
Here overview video on using the debugger.

A section for the curious. So, what's under the hood?

To ensure scripts run on the target device, a bytecode interpreter and an assembler with 38 instructions were developed. A specialized code generator was integrated into the blockly source code, which converts visual blocks into assembly instructions. This assembly program is then transformed into bytecode and sent to the device for execution.
The architecture of this virtual machine is quite simple, and there isn't much point in describing it; you will find many articles online about designing simple virtual machines.
I typically allocate 1000 bytes for the stack of my virtual machine, which is more than enough. Of course, deep recursions can exhaust any stack, but they're unlikely to have practical applications.

The resulting bytecode is quite compact. For example, the bytecode for calculating the same factorial is only 49 bytes. Here is its visual representation:
Visual programming for Sonoff Basic

And here is its assembly program:

shift -1
ldi 10
call factorial, 1
print
exit
:factorial
ld_arg 0
ldi 1
gt
je 8
ld_arg 0
ld_arg 0
ldi 1
sub
call factorial, 1
mul
ret
ldi 1
ret

If the assembly representation has no practical value, the 'javascript' tab, on the other hand, provides a more familiar view than visual blocks:

function factorial(num) {
  if (num > 1) {
    return num + factorial(num - 1);
  }
  return 1;
}

window.alert(factorial(10));

In terms of performance, when running the simplest blinking script, I obtained a 47 kHz square wave on the oscilloscope screen (with a processor clock frequency of 80 MHz).
Visual programming for Sonoff BasicVisual programming for Sonoff Basic
I consider this a decent result; at least this speed is almost ten times faster than that of Lua and Espruino.

Final Part

To sum up, I would say that using scripts allows us not only to program the logic of a single device but also to connect multiple devices into a cohesive mechanism, where some devices influence the behavior of others.
I would also note that the chosen method of storing scripts (directly in the devices rather than on a server) simplifies switching already operational devices to another server, such as a home Raspberry Pi, here. the instruction.

That’s all; I would appreciate any advice and constructive criticism.

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster