Websocket using Toit.io

import net
import http
import web_socket
import bytes
import gpio
IS_CONNECTED := false
SWITCH ::= gpio.Pin 16 --output
HOST ::= "your-endpoint"
PORT ::= 80
main:
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

programmer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Advice to my junior developer self

How to make Laravel Ajax Real Time CRUD —  Continue

Meaningful Availability: User-Uptime

Quickly Test and Deploy Vector Search Solutions with the Milvus 2.0 Bootcamp

How to use Serializer with Your Ruby on Rails API — Step by Step Guide

Creating an Excel+VBA Formula to Extract a Single JSON Value from a SaaS Endpoint’s JSON Payload

Announcement: Raffle for NFT holders

Meshswap Pre-launch MATIC Airdrop Event

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
hc

hc

programmer

More from Medium

Speech Recognition + VoiceCmd + IOT

Sharing Project: Two-Factor Authentication in Keycloak with TokenChannel.io

Securing APIs with APIkey

OSD600 — Release 0.3 External Contribution