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. Such a device will find its application both in home automation and as practical exercises in school computer science.
For reference, by default, the Sonoff Basic program works with a mobile application through a Chinese cloud service, after the proposed alteration, all further interaction with this device will become possible in the browser.

Section I Connecting Sonoff to MGT24 Service

Step 1. Create a control panel

Register on the site mgt24 (if not already registered) and log in with your account.
Login to the systemVisual Programming for Sonoff Basic

To create a control panel for a new device, click on the "+" button.
Panel creation exampleVisual Programming for Sonoff Basic

Once a panel has been created, it will appear in the list of your panels.

In the "Installation" tab of the created panel, find the "Device ID" and "Authorization Key" fields, in the future, this information will be required when setting up the Sonoff device.
Tab ExampleVisual Programming for Sonoff Basic

Step 2. Flashing the device

Using the utility XTCOM_UTIL download firmware Sonoff Basic PLC into the device, for this you need a USB-TTL converter. Here instruction ΠΈ Video instruction.

Step 3. Device setup

Power on the device, after the LED lights up, press the button and hold it down until the LED begins to flash periodically evenly.
At this point, a new wi-fi network called "PLC Sonoff Basic" will appear, connect your computer to this network.
Deciphering the LED indication

LED indication
Device status

intermittent double flashing
no connection to router

continuously shines
established connection with the router

intermittent flashing
hotspot wifi mode

extinguished
No power supply

Open an Internet browser and enter the text "192.168.4.1" into the address bar, go to the device's network settings page.

Fill in the fields as follows:

  • β€œNetwork name” and β€œPassword” (for linking the device to a home wi-fi router).
  • β€œDevice ID” and β€œAuthorization Key” (to authorize the device on the MGT24 service).

Example for configuring the machine's network settingsVisual Programming for Sonoff Basic

Save your settings and reboot your device.
Here Video instruction.

Step 4 Connect sensors (optional)

The current firmware supports up to four ds18b20 temperature sensors. Here Video instruction for sensor installation. Apparently, this step will be the most difficult, as it will require straight arms and a soldering iron from you.

Section II. visual programming

Step 1. Scripting

Used as a programming environment Blockly, the environment is easy to learn, so you don't need to be a programmer to create simple scripts.

I added specialized blocks for writing and reading device parameters. Any parameter is accessed by name. For parameters of remote devices, compound names are used: "parameter@device".
Drop-down list of optionsVisual Programming for Sonoff Basic

An example of a scenario for cycling the load on and off (1Hz):
Visual Programming for Sonoff Basic

An example of a script that synchronizes the operation of two separate devices. Namely, the relay of the target device repeats the operation of the relay of the remote device.
Visual Programming for Sonoff Basic

Scenario for 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 will not describe all this in detail here, there are already quite a lot on the network. learning material about Blockly.

Step 2. Order of execution of scripts

The script runs continuously, and as soon as it reaches its end, it starts again. In this case, there are two blocks that can temporarily suspend the script, "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 seconds (maybe less) delays, and it does not block the execution of other processes in the device.
If the script contains an infinite loop within itself, in the body of which there is no "pause", the interpreter initiates a small pause on its own.
If the allocated memory stack is exhausted, the interpreter will stop the execution of such a voracious script (be careful with recursive functions).

Step 3 Debugging scripts

To debug a script already loaded into the device, you can start tracing the program step by step. This can be extremely useful when the behavior of the script is not what the author intended. 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 debug tool is very simple and consists of three main buttons: "start", "one step forward" and "stop" (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 with the mouse).
To display the current values ​​of parameters (sensors, relays) on the monitor, use the β€œprint” block.
Here overview video about using the debugger.

Section for the curious. And what's under the hood?

In order for the scripts to work on the target device, a bytecode interpreter and an assembler for 38 instructions were developed. A specialized code generator has been built into the blockly source code, which converts visual blocks into assembler instructions. In the future, this assembler program is converted into bytecode and transferred to the device for execution.
The architecture of this virtual machine is quite simple and there is no point in describing it, you will find many articles on the net about designing the simplest virtual machines.
Under the stack of my virtual machine, I usually allocate 1000 bytes, this is enough with a margin. Of course, deep recursions can exhaust any stack, but they are unlikely to be of practical use.

The resulting bytecode is quite compact. As an example, the bytecode for calculating the same factorial is only 49 bytes. This is its visual presentation form:
Visual Programming for Sonoff Basic

And this is his assembler 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 assembler form of presentation does not have any practical value, then the "javascript" tab, on the contrary, gives a more familiar look than visual blocks:

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

window.alert(factorial(10));

As for performance. When running the simplest flasher script, on the oscilloscope screen, I got a 47kHz meander (at a processor clock speed of 80MHz).
Visual Programming for Sonoff BasicVisual Programming for Sonoff Basic
I consider this a good result, at least this speed is almost ten times faster than Moon ΠΈ espruino.

The final part

Summing up, I will say that the use of scripts allows us not only to program the logic of the operation of a single device, but also makes it possible to link several devices into a single mechanism, where one device affects the behavior of others.
I also note that the chosen way of storing scripts (directly in the devices themselves, and not on the server) simplifies switching already working devices to another server, for example, to a home Raspberry, here instruction.

That's all, I'll be glad to hear advice and constructive criticism.

Source: habr.com

Add a comment