-
Notifications
You must be signed in to change notification settings - Fork 43
Running punyforth on a power outlet
The Sonoff "smart socket" is a commercial product that uses an esp8266 chip internally. This happens to be the same chip on which Punyforth is able to run. The product is advertised as a WiFi capable smart socket that can be controlled by smartphones. I haven't tried the original firmware but I suspect it uses a remote server like most other IoT devices. I don't like this concept at all (remember "the S in IoT stands for security").
We're going to replace the factory software in this tutorial with a Forth REPL.
Others have already covered how to flash the esp8266 of the sonoff socket. Basically you have to solder a 4 pin header onto the board, connect an FTDI cabel (RX to TX and TX to RX) and use the standard esptool.py to flash a firmware (and obviously don't do this while the device is plugged in to AC otherwise you will end up dead).
Let's choose the modules to install. We'll need gpio to control the relay and the tcp-repl to try out things interactively.
modules.py --app init.forth core gpio tcp-repl
The init.forth contains the wifi settings and the code that starts the TCP REPL automatically.
str: '<password>' str: '<ssid>' wifi-connect
repl-start
You'll need to hold the red button while flashing the device.
flash com3
The sonoff socket has a relay that can be controlled by gpio pin 12.
12 constant: RELAY
RELAY GPIO_OUT gpio-mode
Turning on and off the power is extremely simple. Just write GPIO_HIGH or GPIO_LOW the 12th pin.
: on ( -- ) RELAY GPIO_HIGH gpio-write ;
: off ( -- ) RELAY GPIO_LOW gpio-write ;
The socket also has a bright green led light that can be used for general purpose notifications.
13 constant: LED
LED GPIO_OUT gpio-mode
This time writing GPIO_LOW to the 13th pin switches the lights on and GPIO_HIGH switches it off.
: led-on ( -- ) LED GPIO_LOW gpio-write ;
: led-off ( -- ) LED GPIO_HIGH gpio-write ;
We can define a word that flashes the light the given number of times.
: flash ( n -- ) LED swap times-blink led-off ;
: alert ( -- ) 10 flash ;
By using the REPL we can try this out interactively.
If you plug in a device, for example a desk lamp you'll be able to turn it on and off by using the on and off words.
I plugged in an ultrasonic humidifier into the sonoff socket. Here you can see how can I control it using the REPL from a tablet.
The next step will be to integrate this to my DHT22 based humidity and temperature data logger to ensure a consistent air humidity level.
Attila Magyar
2016
Attila Magyar