Websocket using Toit.io
Using toit.io, we can manage ESP32 microcontrollers through the cloud using their services. The interesting thing about toit.io is there’s actually a VM running in the ESP32.
I came across toit.io probably in 2020 and it was still very early in development. There were a lot of features not available but recently I had a project which required an ESP32 to be controlled over the internet.
Hence I thought why not give toit.io a shot. The benefits out of the box is once you flash the ESP32 with Toit firmware, WiFi connection is automatic. Handling of reconnection is also done. What’s even more convenient is the online logs. If I remember correctly, in the past they used to charge a fee based on the amount of logs uploaded. But now, it seems like the pricing has updated to per device.
That’s a very good pricing model and they even allow linking of 10 devices for free.
There seems to be some issues with using TLS (I’m thinking it’s a limitation on the memory which causes the encryption and decryption of data to fail). So in my use-case I’m just using ws
instead of wss
for this project.
The documentation is a not that straight forward to follow. Not everything includes examples and hence I’m documenting this down to help anyone who are doing the same thing.
You can read up more regarding their WebSocket implementation here https://libs.toit.io/web_socket/library-summary.
Basically below contains the source code. I’ve a server running a websocket server at the endpoint ws://your-endpoint/ws
. The server will just broadcast a simple string “ON” or “OFF” and the ESP32 will toggle the GPIO pin 16 to which controls a relay on my board.
The codes also includes auto reconnecting to the websocket server incase it disconnect or the server is inaccessible.
import net
import http
import web_socket
import bytes
import gpioIS_CONNECTED := false
SWITCH ::= gpio.Pin 16 --output
HOST ::= "your-endpoint"
PORT ::= 80main:
print "Device Online"
s := connect_server
while true:
if IS_CONNECTED == false:
s = connect_server
if s != null:
IS_CONNECTED = true
else:
IS_CONNECTED = false
sleep --ms=5000
else if IS_CONNECTED == true:
try:
print "Waiting data"
dc := catch:
payload := s.read
if payload == "ON":
SWITCH.set 1
else if payload == "OFF":
SWITCH.set 0
print "$payload"
if dc:
IS_CONNECTED = false
SWITCH.set 0
finally:
connect_server:
network_interface := net.open
socket := network_interface.tcp_connect HOST PORT
http_connection := http.Connection socket HOST
err := catch:
request := http_connection.new_request "GET" "/ws"
client := web_socket.WebSocketClient http_connection request
return client
if err:
print "Server down, retry in 5s"
return null
https://gist.github.com/seeya/ac7e9dcd6945a4b881e1a41290a559ca#file-ws_service-toit