Skip to content

Instantly share code, notes, and snippets.

@deadprogram
Created August 13, 2019 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deadprogram/33a6f38af709dbbb588b492b453b3ea3 to your computer and use it in GitHub Desktop.
Save deadprogram/33a6f38af709dbbb588b492b453b3ea3 to your computer and use it in GitHub Desktop.
// This is a sensor station that uses a ESP8266 or ESP32 running on the device UART1.
// It creates an MQTT connection that publishes a message every second
// to an MQTT broker.
//
// In other words:
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 <--> Internet <--> MQTT broker.
//
// You must install the Paho MQTT package to build this program:
//
// go get -u github.com/eclipse/paho.mqtt.golang
//
package main
import (
"machine"
"math/rand"
"time"
"tinygo.org/x/drivers/espat"
"tinygo.org/x/drivers/espat/mqtt"
)
// access point info.. change to match yours
const ssid = "thing1"
const pass = "thing2"
// IP address of the MQTT broker to use. Replace with your own info.
const server = "tcp://test.mosquitto.org:1883"
// const server = "tcp://10.42.0.1:1883"
// const server = "ssl://test.mosquitto.org:8883"
// change these to connect to a different UART or pins for the ESP8266/ESP32
var (
uart = machine.UART1
tx = machine.PA22
rx = machine.PA23
adaptor *espat.Device
topic = "tinygo"
)
func main() {
time.Sleep(3000 * time.Millisecond)
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
rand.Seed(time.Now().UnixNano())
button := machine.D11
button.Configure(machine.PinConfig{Mode: machine.PinInput})
readyLED := machine.LED
readyLED.Configure(machine.PinConfig{Mode: machine.PinOutput})
readyLED.Low()
sendLED := machine.D12
sendLED.Configure(machine.PinConfig{Mode: machine.PinOutput})
// Init esp8266/esp32
adaptor = espat.New(uart)
adaptor.Configure()
// first check if connected
if connectToESP() {
readyLED.High()
println("Connected to wifi adaptor.")
adaptor.Echo(false)
readyLED.Low()
connectToAP()
readyLED.High()
} else {
println("")
failMessage("Unable to connect to wifi adaptor.")
return
}
opts := mqtt.NewClientOptions(adaptor)
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
readyLED.Low()
println("Connectng to MQTT...")
cl := mqtt.NewClient(opts)
if token := cl.Connect(); token.Wait() && token.Error() != nil {
failMessage(token.Error().Error())
}
readyLED.High()
for {
if button.Get() {
sendLED.High()
println("Publishing MQTT message...")
data := []byte("{\"e\":[{ \"n\":\"hello\", \"sv\":\"world\" }]}")
token := cl.Publish(topic, 0, false, data)
token.Wait()
if token.Error() != nil {
println(token.Error().Error())
break
}
sendLED.Low()
time.Sleep(500 * time.Millisecond)
}
}
// Right now this code is only reached when there is an error. Need a way to trigger clean exit.
println("Disconnecting MQTT...")
cl.Disconnect(100)
println("Done.")
}
// connect to ESP8266/ESP32
func connectToESP() bool {
for i := 0; i < 5; i++ {
println("Connecting to wifi adaptor...")
if adaptor.Connected() {
return true
}
time.Sleep(1 * time.Second)
}
return false
}
// connect to access point
func connectToAP() {
println("Connecting to wifi network...")
adaptor.SetWifiMode(espat.WifiModeClient)
adaptor.ConnectToAP(ssid, pass, 10)
println("Connected.")
println(adaptor.GetClientIP())
}
// Returns an int >= min, < max
func randomInt(min, max int) int {
return min + rand.Intn(max-min)
}
// Generate a random string of A-Z chars with len = l
func randomString(len int) string {
bytes := make([]byte, len)
for i := 0; i < len; i++ {
bytes[i] = byte(randomInt(65, 90))
}
return string(bytes)
}
func failMessage(msg string) {
for {
println(msg)
time.Sleep(1 * time.Second)
}
}
@cyantarek
Copy link

Where can I find the "machine" library? It looks like built-in library but in my system, I can not find it to use. Please help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment