mirror of
https://github.com/tinygo-org/drivers.git
synced 2026-08-08 17:03:39 +00:00
Add network device driver model, netdev
This commit is contained in:
@@ -1,145 +0,0 @@
|
||||
// This is a console to a ESP8266/ESP32 running on the device UART1.
|
||||
// Allows you to type AT commands from your computer via the microcontroller.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 <--> INTERNET
|
||||
//
|
||||
// More information on the Espressif AT command set at:
|
||||
// https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
)
|
||||
|
||||
// change actAsAP to true to act as an access point instead of connecting to one.
|
||||
const actAsAP = false
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
uart = machine.UART1
|
||||
tx = machine.PA22
|
||||
rx = machine.PA23
|
||||
|
||||
console = machine.Serial
|
||||
|
||||
adaptor *espat.Device
|
||||
)
|
||||
|
||||
func main() {
|
||||
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
|
||||
|
||||
// Init esp8266
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
// first check if connected
|
||||
if connectToESP() {
|
||||
println("Connected to wifi adaptor.")
|
||||
adaptor.Echo(false)
|
||||
|
||||
connectToAP()
|
||||
} else {
|
||||
println("")
|
||||
failMessage("Unable to connect to wifi adaptor.")
|
||||
return
|
||||
}
|
||||
|
||||
println("Type an AT command then press enter:")
|
||||
prompt()
|
||||
|
||||
input := make([]byte, 64)
|
||||
i := 0
|
||||
for {
|
||||
if console.Buffered() > 0 {
|
||||
data, _ := console.ReadByte()
|
||||
|
||||
switch data {
|
||||
case 13:
|
||||
// return key
|
||||
console.Write([]byte("\r\n"))
|
||||
|
||||
// send command to ESP8266
|
||||
input[i] = byte('\r')
|
||||
input[i+1] = byte('\n')
|
||||
adaptor.Write(input[:i+2])
|
||||
|
||||
// display response
|
||||
r, _ := adaptor.Response(500)
|
||||
console.Write(r)
|
||||
|
||||
// prompt
|
||||
prompt()
|
||||
|
||||
i = 0
|
||||
continue
|
||||
default:
|
||||
// just echo the character
|
||||
console.WriteByte(data)
|
||||
input[i] = data
|
||||
i++
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func prompt() {
|
||||
print("ESPAT>")
|
||||
}
|
||||
|
||||
// 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 '" + ssid + "'")
|
||||
|
||||
if err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second); err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
ip, err := adaptor.GetClientIP()
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println(ip)
|
||||
}
|
||||
|
||||
// provide access point
|
||||
func provideAP() {
|
||||
println("Starting wifi network as access point '" + ssid + "'...")
|
||||
adaptor.SetWifiMode(espat.WifiModeAP)
|
||||
adaptor.SetAPConfig(ssid, pass, 7, espat.WifiAPSecurityWPA2_PSK)
|
||||
println("Ready.")
|
||||
ip, _ := adaptor.GetAPIP()
|
||||
println(ip)
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
// This is a sensor hub that uses a ESP8266/ESP32 running on the device UART1.
|
||||
// It creates a UDP "server" you can use to get info to/from your computer via the microcontroller.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 <--> INTERNET
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
"tinygo.org/x/drivers/net"
|
||||
)
|
||||
|
||||
// change actAsAP to true to act as an access point instead of connecting to one.
|
||||
const actAsAP = false
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// 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
|
||||
)
|
||||
|
||||
func main() {
|
||||
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
|
||||
|
||||
// Init esp8266
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
readyled := machine.LED
|
||||
readyled.Configure(machine.PinConfig{Mode: machine.PinOutput})
|
||||
readyled.High()
|
||||
|
||||
// first check if connected
|
||||
if connectToESP() {
|
||||
println("Connected to wifi adaptor.")
|
||||
adaptor.Echo(false)
|
||||
|
||||
connectToAP()
|
||||
} else {
|
||||
println("")
|
||||
failMessage("Unable to connect to wifi adaptor.")
|
||||
return
|
||||
}
|
||||
|
||||
// now make UDP connection
|
||||
laddr := &net.UDPAddr{Port: 2222}
|
||||
println("Loading UDP listener...")
|
||||
conn, _ := net.ListenUDP("UDP", laddr)
|
||||
|
||||
println("Waiting for data...")
|
||||
data := make([]byte, 50)
|
||||
blink := true
|
||||
for {
|
||||
n, _ := conn.Read(data)
|
||||
if n > 0 {
|
||||
println(string(data[:n]))
|
||||
conn.Write([]byte("hello back\r\n"))
|
||||
}
|
||||
blink = !blink
|
||||
if blink {
|
||||
readyled.High()
|
||||
} else {
|
||||
readyled.Low()
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting UDP...")
|
||||
conn.Close()
|
||||
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 '" + ssid + "'")
|
||||
|
||||
if err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second); err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
ip, err := adaptor.GetClientIP()
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println(ip)
|
||||
}
|
||||
|
||||
// provide access point
|
||||
func provideAP() {
|
||||
println("Starting wifi network as access point '" + ssid + "'...")
|
||||
adaptor.SetWifiMode(espat.WifiModeAP)
|
||||
adaptor.SetAPConfig(ssid, pass, 7, espat.WifiAPSecurityWPA2_PSK)
|
||||
println("Ready.")
|
||||
ip, _ := adaptor.GetAPIP()
|
||||
println(ip)
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// This is a sensor station that uses a ESP8266 or ESP32 running on the device UART1.
|
||||
// It creates a UDP connection you can use to get info to/from your computer via the microcontroller.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
"tinygo.org/x/drivers/net"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the listener aka "hub". Replace with your own info.
|
||||
const hubIP = "0.0.0.0"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// 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
|
||||
)
|
||||
|
||||
func main() {
|
||||
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
|
||||
|
||||
// Init esp8266/esp32
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
// first check if connected
|
||||
if connectToESP() {
|
||||
println("Connected to wifi adaptor.")
|
||||
adaptor.Echo(false)
|
||||
|
||||
connectToAP()
|
||||
} else {
|
||||
println("")
|
||||
failMessage("Unable to connect to wifi adaptor.")
|
||||
return
|
||||
}
|
||||
|
||||
// now make UDP connection
|
||||
ip := net.ParseIP(hubIP)
|
||||
raddr := &net.UDPAddr{IP: ip, Port: 2222}
|
||||
laddr := &net.UDPAddr{Port: 2222}
|
||||
|
||||
println("Dialing UDP connection...")
|
||||
conn, _ := net.DialUDP("udp", laddr, raddr)
|
||||
|
||||
for {
|
||||
// send data
|
||||
println("Sending data...")
|
||||
conn.Write([]byte("hello\r\n"))
|
||||
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting UDP...")
|
||||
conn.Close()
|
||||
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 '" + ssid + "'")
|
||||
|
||||
if err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second); err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
ip, err := adaptor.GetClientIP()
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println(ip)
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
// 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/net/mqtt"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the MQTT broker to use. Replace with your own info.
|
||||
const server = "tcp://test.mosquitto.org:1883"
|
||||
|
||||
//const server = "ssl://test.mosquitto.org:8883"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
uart = machine.UART2
|
||||
tx = machine.PA22
|
||||
rx = machine.PA23
|
||||
|
||||
console = machine.Serial
|
||||
|
||||
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())
|
||||
|
||||
// Init esp8266/esp32
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
// first check if connected
|
||||
if connectToESP() {
|
||||
println("Connected to wifi adaptor.")
|
||||
adaptor.Echo(false)
|
||||
|
||||
connectToAP()
|
||||
} else {
|
||||
println("")
|
||||
failMessage("Unable to connect to wifi adaptor.")
|
||||
return
|
||||
}
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
|
||||
|
||||
println("Connecting to MQTT broker at", server)
|
||||
cl := mqtt.NewClient(opts)
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
for {
|
||||
println("Publishing MQTT message...")
|
||||
data := []byte("{\"e\":[{ \"n\":\"hello\", \"v\":101 }]}")
|
||||
token := cl.Publish(topic, 0, false, data)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
println(token.Error().Error())
|
||||
}
|
||||
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
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 '" + ssid + "'")
|
||||
|
||||
if err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second); err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
ip, err := adaptor.GetClientIP()
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println(ip)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
// 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 also install the Paho MQTT package to build this program:
|
||||
//
|
||||
// go get -u github.com/eclipse/paho.mqtt.golang
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"machine"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
"tinygo.org/x/drivers/net/mqtt"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the MQTT broker to use. Replace with your own info.
|
||||
//const server = "tcp://test.mosquitto.org:1883"
|
||||
|
||||
const server = "ssl://test.mosquitto.org:8883"
|
||||
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
// these are defaults for the Arduino Nano33 IoT.
|
||||
uart = machine.UART1
|
||||
tx = machine.PA22
|
||||
rx = machine.PA23
|
||||
|
||||
console = machine.Serial
|
||||
|
||||
adaptor *espat.Device
|
||||
cl mqtt.Client
|
||||
topicTx = "tinygo/tx"
|
||||
topicRx = "tinygo/rx"
|
||||
)
|
||||
|
||||
func subHandler(client mqtt.Client, msg mqtt.Message) {
|
||||
fmt.Printf("[%s] ", msg.Topic())
|
||||
fmt.Printf("%s\r\n", msg.Payload())
|
||||
}
|
||||
|
||||
func main() {
|
||||
time.Sleep(3000 * time.Millisecond)
|
||||
|
||||
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
// Init esp8266/esp32
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
// first check if connected
|
||||
if connectToESP() {
|
||||
println("Connected to wifi adaptor.")
|
||||
adaptor.Echo(false)
|
||||
|
||||
connectToAP()
|
||||
} else {
|
||||
println("")
|
||||
failMessage("Unable to connect to wifi adaptor.")
|
||||
return
|
||||
}
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
|
||||
|
||||
println("Connecting to MQTT broker at", server)
|
||||
cl = mqtt.NewClient(opts)
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
// subscribe
|
||||
token := cl.Subscribe(topicRx, 0, subHandler)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
go publishing()
|
||||
|
||||
select {}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting MQTT...")
|
||||
cl.Disconnect(100)
|
||||
|
||||
println("Done.")
|
||||
}
|
||||
|
||||
func publishing() {
|
||||
for {
|
||||
println("Publishing MQTT message...")
|
||||
data := []byte("{\"e\":[{ \"n\":\"hello\", \"v\":101 }]}")
|
||||
token := cl.Publish(topicTx, 0, false, data)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
println(token.Error().Error())
|
||||
}
|
||||
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 '" + ssid + "'")
|
||||
|
||||
if err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second); err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
ip, err := adaptor.GetClientIP()
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println(ip)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
// This is a sensor station that uses a ESP8266 or ESP32 running on the device UART1.
|
||||
// It creates a UDP connection you can use to get info to/from your computer via the microcontroller.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
"tinygo.org/x/drivers/net"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
const serverIP = "0.0.0.0"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// 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
|
||||
)
|
||||
|
||||
func main() {
|
||||
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
|
||||
|
||||
// Init esp8266/esp32
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
// first check if connected
|
||||
if connectToESP() {
|
||||
println("Connected to wifi adaptor.")
|
||||
adaptor.Echo(false)
|
||||
|
||||
connectToAP()
|
||||
} else {
|
||||
println("")
|
||||
failMessage("Unable to connect to wifi adaptor.")
|
||||
return
|
||||
}
|
||||
|
||||
// now make TCP connection
|
||||
ip := net.ParseIP(serverIP)
|
||||
raddr := &net.TCPAddr{IP: ip, Port: 8080}
|
||||
laddr := &net.TCPAddr{Port: 8080}
|
||||
|
||||
println("Dialing TCP connection...")
|
||||
conn, err := net.DialTCP("tcp", laddr, raddr)
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
for {
|
||||
// send data
|
||||
println("Sending data...")
|
||||
conn.Write([]byte("hello\r\n"))
|
||||
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting TCP...")
|
||||
conn.Close()
|
||||
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 '" + ssid + "'")
|
||||
|
||||
if err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second); err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
ip, err := adaptor.GetClientIP()
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
println(ip)
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// This example gets an URL using http.Get(). URL scheme can be http or https.
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
//
|
||||
// Some targets (Arduino Nano33 IoT) don't have enough SRAM to run http.Get().
|
||||
// Use the following for those targets:
|
||||
//
|
||||
// examples/net/webclient (for HTTP)
|
||||
// examples/net/tlsclient (for HTTPS)
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
name := "John Doe"
|
||||
occupation := "gardener"
|
||||
|
||||
params := "name=" + url.QueryEscape(name) + "&" +
|
||||
"occupation=" + url.QueryEscape(occupation)
|
||||
|
||||
path := fmt.Sprintf("https://httpbin.org/get?%s", params)
|
||||
|
||||
cnt := 0
|
||||
for {
|
||||
fmt.Printf("Getting %s\r\n\r\n", path)
|
||||
resp, err := http.Get(path)
|
||||
if err != nil {
|
||||
fmt.Printf("%s\r\n", err.Error())
|
||||
time.Sleep(10 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
|
||||
for k, v := range resp.Header {
|
||||
fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
|
||||
}
|
||||
fmt.Printf("\r\n")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
println(string(body))
|
||||
resp.Body.Close()
|
||||
|
||||
cnt++
|
||||
fmt.Printf("-------- %d --------\r\n", cnt)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,57 @@
|
||||
// This example gets an URL using http.Head(). URL scheme can be http or https.
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
//
|
||||
// Some targets (Arduino Nano33 IoT) don't have enough SRAM to run http.Head().
|
||||
// Use the following for those targets:
|
||||
//
|
||||
// examples/net/webclient (for HTTP)
|
||||
// examples/net/tlsclient (for HTTPS)
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
url string = "https://httpbin.org"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
resp, err := http.Head(url)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := resp.Write(&buf); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(string(buf.Bytes()))
|
||||
|
||||
netdev.NetDisconnect()
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,61 @@
|
||||
// This example posts an URL using http.Post(). URL scheme can be http or https.
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
//
|
||||
// Some targets (Arduino Nano33 IoT) don't have enough SRAM to run http.Post().
|
||||
// Use the following for those targets:
|
||||
//
|
||||
// examples/net/webclient (for HTTP)
|
||||
// examples/net/tlsclient (for HTTPS)
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
path := "https://httpbin.org/post"
|
||||
data := []byte("{\"name\":\"John Doe\",\"occupation\":\"gardener\"}")
|
||||
|
||||
resp, err := http.Post(path, "application/json", bytes.NewBuffer(data))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println(string(body))
|
||||
|
||||
netdev.NetDisconnect()
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,62 @@
|
||||
// This example posts an URL using http.PostForm(). URL scheme can be http or https.
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
//
|
||||
// Some targets (Arduino Nano33 IoT) don't have enough SRAM to run
|
||||
// http.PostForm(). Use the following for those targets:
|
||||
//
|
||||
// examples/net/webclient (for HTTP)
|
||||
// examples/net/tlsclient (for HTTPS)
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
path := "https://httpbin.org/post"
|
||||
data := url.Values{
|
||||
"name": {"John Doe"},
|
||||
"occupation": {"gardener"},
|
||||
}
|
||||
|
||||
resp, err := http.PostForm(path, data)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println(string(body))
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build challenger_rp2040
|
||||
|
||||
// +build: challenger_rp2040
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
)
|
||||
|
||||
var cfg = espat.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// UART
|
||||
Uart: machine.UART1,
|
||||
Tx: machine.UART1_TX_PIN,
|
||||
Rx: machine.UART1_RX_PIN,
|
||||
}
|
||||
|
||||
var netdev = espat.New(&cfg)
|
||||
@@ -0,0 +1,100 @@
|
||||
// This example is a MQTT client. It sends machine.ReadTemparature() readings
|
||||
// to the broker every second for 10 seconds.
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using
|
||||
// paho.mqtt.golang. Use the -stack-size=4KB command line option.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"machine"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
broker string = "tcp://test.mosquitto.org:1883"
|
||||
)
|
||||
|
||||
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
|
||||
fmt.Printf("Message %s received on topic %s\n", msg.Payload(), msg.Topic())
|
||||
}
|
||||
|
||||
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
|
||||
fmt.Println("Connected")
|
||||
}
|
||||
|
||||
var connectionLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
|
||||
fmt.Printf("Connection Lost: %s\n", err.Error())
|
||||
}
|
||||
|
||||
func main() {
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
clientId := "tinygo-client-" + randomString(10)
|
||||
fmt.Printf("ClientId: %s\n", clientId)
|
||||
|
||||
options := mqtt.NewClientOptions()
|
||||
options.AddBroker(broker)
|
||||
options.SetClientID(clientId)
|
||||
options.SetDefaultPublishHandler(messagePubHandler)
|
||||
options.OnConnect = connectHandler
|
||||
options.OnConnectionLost = connectionLostHandler
|
||||
|
||||
fmt.Printf("Connecting to MQTT broker at %s\n", broker)
|
||||
client := mqtt.NewClient(options)
|
||||
token := client.Connect()
|
||||
if token.Wait() && token.Error() != nil {
|
||||
panic(token.Error())
|
||||
}
|
||||
|
||||
topic := "cpu/freq"
|
||||
token = client.Subscribe(topic, 1, nil)
|
||||
if token.Wait() && token.Error() != nil {
|
||||
panic(token.Error())
|
||||
}
|
||||
fmt.Printf("Subscribed to topic %s\n", topic)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
freq := float32(machine.CPUFrequency()) / 1000000
|
||||
payload := fmt.Sprintf("%.02fMhz", freq)
|
||||
token = client.Publish(topic, 0, false, payload)
|
||||
if token.Wait() && token.Error() != nil {
|
||||
panic(token.Error())
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
client.Disconnect(100)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build challenger_rp2040
|
||||
|
||||
// +build: challenger_rp2040
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
)
|
||||
|
||||
var cfg = espat.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// UART
|
||||
Uart: machine.UART1,
|
||||
Tx: machine.UART1_TX_PIN,
|
||||
Rx: machine.UART1_RX_PIN,
|
||||
}
|
||||
|
||||
var netdev = espat.New(&cfg)
|
||||
@@ -0,0 +1,104 @@
|
||||
// This is an example of an NTP client.
|
||||
//
|
||||
// It creates a UDP connection to request the current time and parse the
|
||||
// response from a NTP server. The system time is set to NTP time.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
ntpHost string = "0.pool.ntp.org:123"
|
||||
)
|
||||
|
||||
const NTP_PACKET_SIZE = 48
|
||||
|
||||
var response = make([]byte, NTP_PACKET_SIZE)
|
||||
|
||||
func main() {
|
||||
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
conn, err := net.Dial("udp", ntpHost)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
println("Requesting NTP time...")
|
||||
|
||||
t, err := getCurrentTime(conn)
|
||||
if err != nil {
|
||||
log.Fatal(fmt.Sprintf("Error getting current time: %v", err))
|
||||
} else {
|
||||
message("NTP time: %v", t)
|
||||
}
|
||||
|
||||
conn.Close()
|
||||
netdev.NetDisconnect()
|
||||
|
||||
runtime.AdjustTimeOffset(-1 * int64(time.Since(t)))
|
||||
|
||||
for {
|
||||
message("Current time: %v", time.Now())
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func getCurrentTime(conn net.Conn) (time.Time, error) {
|
||||
if err := sendNTPpacket(conn); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
n, err := conn.Read(response)
|
||||
if err != nil && err != io.EOF {
|
||||
return time.Time{}, err
|
||||
}
|
||||
if n != NTP_PACKET_SIZE {
|
||||
return time.Time{}, fmt.Errorf("expected NTP packet size of %d: %d", NTP_PACKET_SIZE, n)
|
||||
}
|
||||
|
||||
return parseNTPpacket(response), nil
|
||||
}
|
||||
|
||||
func sendNTPpacket(conn net.Conn) error {
|
||||
var request = [48]byte{
|
||||
0xe3,
|
||||
}
|
||||
|
||||
_, err := conn.Write(request[:])
|
||||
return err
|
||||
}
|
||||
|
||||
func parseNTPpacket(r []byte) time.Time {
|
||||
// the timestamp starts at byte 40 of the received packet and is four bytes,
|
||||
// this is NTP time (seconds since Jan 1 1900):
|
||||
t := uint32(r[40])<<24 | uint32(r[41])<<16 | uint32(r[42])<<8 | uint32(r[43])
|
||||
const seventyYears = 2208988800
|
||||
return time.Unix(int64(t-seventyYears), 0)
|
||||
}
|
||||
|
||||
func message(format string, args ...interface{}) {
|
||||
println(fmt.Sprintf(format, args...), "\r")
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || arduino_nano33 || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal arduino_nano33 nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build challenger_rp2040
|
||||
|
||||
// +build: challenger_rp2040
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
)
|
||||
|
||||
var cfg = espat.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// UART
|
||||
Uart: machine.UART1,
|
||||
Tx: machine.UART1_TX_PIN,
|
||||
Rx: machine.UART1_RX_PIN,
|
||||
}
|
||||
|
||||
var netdev = espat.New(&cfg)
|
||||
@@ -0,0 +1,99 @@
|
||||
// This example opens a TCP connection and sends some data using netdev sockets.
|
||||
//
|
||||
// You can open a server to accept connections from this program using:
|
||||
//
|
||||
// nc -lk 8080
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"machine"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
addr string = "10.0.0.100:8080"
|
||||
)
|
||||
|
||||
var buf = &bytes.Buffer{}
|
||||
|
||||
func main() {
|
||||
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for {
|
||||
sendBatch()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func sendBatch() {
|
||||
|
||||
host, sport, _ := net.SplitHostPort(addr)
|
||||
ip := net.ParseIP(host).To4()
|
||||
port, _ := strconv.Atoi(sport)
|
||||
|
||||
// make TCP connection
|
||||
message("---------------\r\nDialing TCP connection")
|
||||
fd, _ := netdev.Socket(drivers.AF_INET, drivers.SOCK_STREAM, drivers.IPPROTO_TCP)
|
||||
err := netdev.Connect(fd, "", ip, port)
|
||||
for ; err != nil; err = netdev.Connect(fd, "", ip, port) {
|
||||
message(err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
|
||||
n := 0
|
||||
w := 0
|
||||
start := time.Now()
|
||||
|
||||
// send data
|
||||
message("Sending data")
|
||||
|
||||
for i := 0; i < 1000; i++ {
|
||||
buf.Reset()
|
||||
fmt.Fprint(buf,
|
||||
"\r---------------------------- i == ", i, " ----------------------------"+
|
||||
"\r---------------------------- i == ", i, " ----------------------------")
|
||||
if w, err = netdev.Send(fd, buf.Bytes(), 0, time.Time{}); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
break
|
||||
}
|
||||
n += w
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
ms := time.Now().Sub(start).Milliseconds()
|
||||
fmt.Fprint(buf, "\nWrote ", n, " bytes in ", ms, " ms\r\n")
|
||||
message(buf.String())
|
||||
|
||||
if _, err := netdev.Send(fd, buf.Bytes(), 0, time.Time{}); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
}
|
||||
|
||||
println("Disconnecting TCP...")
|
||||
netdev.Close(fd)
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || arduino_nano33 || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal arduino_nano33 nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build challenger_rp2040
|
||||
|
||||
// +build: challenger_rp2040
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"tinygo.org/x/drivers/espat"
|
||||
)
|
||||
|
||||
var cfg = espat.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// UART
|
||||
Uart: machine.UART1,
|
||||
Tx: machine.UART1_TX_PIN,
|
||||
Rx: machine.UART1_RX_PIN,
|
||||
}
|
||||
|
||||
var netdev = espat.New(&cfg)
|
||||
@@ -1,52 +1,49 @@
|
||||
// This example opens a TCP connection and sends some data,
|
||||
// for the purpose of testing speed and connectivity.
|
||||
// This example opens a TCP connection and sends some data, for the purpose of
|
||||
// testing speed and connectivity.
|
||||
//
|
||||
// You can open a server to accept connections from this program using:
|
||||
//
|
||||
// nc -w 5 -lk 8080
|
||||
// nc -lk 8080
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"machine"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
addr string = "10.0.0.100:8080"
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
const serverIP = ""
|
||||
|
||||
var buf = &bytes.Buffer{}
|
||||
|
||||
func main() {
|
||||
initAdaptor()
|
||||
|
||||
connectToAP()
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for {
|
||||
sendBatch()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
println("Done.")
|
||||
}
|
||||
|
||||
func sendBatch() {
|
||||
|
||||
// make TCP connection
|
||||
ip := net.ParseIP(serverIP)
|
||||
raddr := &net.TCPAddr{IP: ip, Port: 8080}
|
||||
laddr := &net.TCPAddr{Port: 8080}
|
||||
|
||||
message("---------------\r\nDialing TCP connection")
|
||||
conn, err := net.DialTCP("tcp", laddr, raddr)
|
||||
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
|
||||
conn, err := net.Dial("tcp", addr)
|
||||
for ; err != nil; conn, err = net.Dial("tcp", addr) {
|
||||
message(err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
@@ -65,7 +62,7 @@ func sendBatch() {
|
||||
"\r---------------------------- i == ", i, " ----------------------------")
|
||||
if w, err = conn.Write(buf.Bytes()); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
continue
|
||||
break
|
||||
}
|
||||
n += w
|
||||
}
|
||||
@@ -79,34 +76,17 @@ func sendBatch() {
|
||||
println("error:", err.Error(), "\r")
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting TCP...")
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
println("Connecting to " + ssid)
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil { // error connecting to AP
|
||||
for {
|
||||
println(err)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
println("Connected.")
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
ip, err := adaptor.GetClientIP()
|
||||
for ; err != nil; ip, err = adaptor.GetClientIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message(ip)
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || arduino_nano33 || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal arduino_nano33 nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,56 @@
|
||||
// This example listens on port :8080 for client connections. Bytes
|
||||
// received from the client are echo'ed back to the client. Multiple
|
||||
// clients can connect as the same time, each consuming a client socket,
|
||||
// and being serviced by it's own go func.
|
||||
//
|
||||
// Example test using nc as client to copy file:
|
||||
//
|
||||
// $ nc 10.0.0.2 8080 <file >copy ; cmp file copy
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
port string = ":8080"
|
||||
)
|
||||
|
||||
var buf [1024]byte
|
||||
|
||||
func echo(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
_, err := io.CopyBuffer(conn, conn, buf[:])
|
||||
if err != nil && err != io.EOF {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
l, err := net.Listen("tcp", port)
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
go echo(conn)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || arduino_nano33 || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal arduino_nano33 nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,95 @@
|
||||
// This example uses TLS to send an HTTPS request to retrieve a webpage
|
||||
//
|
||||
// You shall see "strict-transport-security" header in the response,
|
||||
// this confirms communication is indeed over HTTPS
|
||||
//
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
// HTTPS server address to hit with a GET / request
|
||||
address string = "httpbin.org:443"
|
||||
)
|
||||
|
||||
var conn net.Conn
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func check(err error) {
|
||||
if err != nil {
|
||||
println("Hit an error:", err.Error())
|
||||
panic("BYE")
|
||||
}
|
||||
}
|
||||
|
||||
func readResponse() {
|
||||
r := bufio.NewReader(conn)
|
||||
resp, err := io.ReadAll(r)
|
||||
check(err)
|
||||
println(string(resp))
|
||||
}
|
||||
|
||||
func closeConnection() {
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
func dialConnection() {
|
||||
var err error
|
||||
|
||||
println("\r\n---------------\r\nDialing TLS connection")
|
||||
conn, err = tls.Dial("tcp", address, nil)
|
||||
for ; err != nil; conn, err = tls.Dial("tcp", address, nil) {
|
||||
println("Connection failed:", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
println("Connected!\r")
|
||||
}
|
||||
|
||||
func makeRequest() {
|
||||
print("Sending HTTPS request...")
|
||||
w := bufio.NewWriter(conn)
|
||||
fmt.Fprintln(w, "GET /get HTTP/1.1")
|
||||
fmt.Fprintln(w, "Host:", strings.Split(address, ":")[0])
|
||||
fmt.Fprintln(w, "User-Agent: TinyGo")
|
||||
fmt.Fprintln(w, "Connection: close")
|
||||
fmt.Fprintln(w)
|
||||
check(w.Flush())
|
||||
println("Sent!\r\n\r")
|
||||
}
|
||||
|
||||
func main() {
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for i := 0; ; i++ {
|
||||
dialConnection()
|
||||
makeRequest()
|
||||
readResponse()
|
||||
closeConnection()
|
||||
println("--------", i, "--------\r\n")
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || arduino_nano33 || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal arduino_nano33 nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,141 @@
|
||||
// This example runs on wioterminal. It gets an URL using http.Get() and
|
||||
// displays the output on the wioterminal LCD screen.
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image/color"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers"
|
||||
"tinygo.org/x/drivers/ili9341"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
"tinygo.org/x/tinyfont/proggy"
|
||||
"tinygo.org/x/tinyterm"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
var (
|
||||
netcfg = rtl8720dn.Config{
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
}
|
||||
|
||||
netdev = rtl8720dn.New(&netcfg)
|
||||
|
||||
display = ili9341.NewSPI(
|
||||
machine.SPI3,
|
||||
machine.LCD_DC,
|
||||
machine.LCD_SS_PIN,
|
||||
machine.LCD_RESET,
|
||||
)
|
||||
|
||||
backlight = machine.LCD_BACKLIGHT
|
||||
|
||||
terminal = tinyterm.NewTerminal(display)
|
||||
|
||||
black = color.RGBA{0, 0, 0, 255}
|
||||
white = color.RGBA{255, 255, 255, 255}
|
||||
red = color.RGBA{255, 0, 0, 255}
|
||||
blue = color.RGBA{0, 0, 255, 255}
|
||||
green = color.RGBA{0, 255, 0, 255}
|
||||
|
||||
font = &proggy.TinySZ8pt7b
|
||||
)
|
||||
|
||||
func notify(e drivers.NetlinkEvent) {
|
||||
switch e {
|
||||
case drivers.NetlinkEventNetUp:
|
||||
fmt.Println("Wifi connection UP")
|
||||
fmt.Fprintf(terminal, "Wifi connection UP")
|
||||
case drivers.NetlinkEventNetDown:
|
||||
fmt.Println("Wifi connection DOWN")
|
||||
fmt.Fprintf(terminal, "Wifi connection DOWN")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
machine.SPI3.Configure(machine.SPIConfig{
|
||||
SCK: machine.LCD_SCK_PIN,
|
||||
SDO: machine.LCD_SDO_PIN,
|
||||
SDI: machine.LCD_SDI_PIN,
|
||||
Frequency: 40000000,
|
||||
})
|
||||
|
||||
display.Configure(ili9341.Config{})
|
||||
display.FillScreen(black)
|
||||
|
||||
backlight.Configure(machine.PinConfig{machine.PinOutput})
|
||||
backlight.High()
|
||||
|
||||
terminal.Configure(&tinyterm.Config{
|
||||
Font: font,
|
||||
FontHeight: 10,
|
||||
FontOffset: 6,
|
||||
})
|
||||
|
||||
fmt.Fprintf(terminal, "Connecting to %s...\r\n", ssid)
|
||||
|
||||
netdev.NetNotify(notify)
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
name := "John Doe"
|
||||
occupation := "gardener"
|
||||
|
||||
params := "name=" + url.QueryEscape(name) + "&" +
|
||||
"occupation=" + url.QueryEscape(occupation)
|
||||
|
||||
path := fmt.Sprintf("https://httpbin.org/get?%s", params)
|
||||
|
||||
cnt := 0
|
||||
for {
|
||||
fmt.Fprintf(terminal, "Getting %s\r\n\r\n", path)
|
||||
resp, err := http.Get(path)
|
||||
if err != nil {
|
||||
fmt.Fprintf(terminal, "%s\r\n", err.Error())
|
||||
time.Sleep(10 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Fprintf(terminal, "%s %s\r\n", resp.Proto, resp.Status)
|
||||
for k, v := range resp.Header {
|
||||
fmt.Fprintf(terminal, "%s: %s\r\n", k, strings.Join(v, " "))
|
||||
}
|
||||
fmt.Fprintf(terminal, "\r\n")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
fmt.Fprintf(terminal, string(body))
|
||||
resp.Body.Close()
|
||||
|
||||
cnt++
|
||||
fmt.Fprintf(terminal, "-------- %d --------\r\n", cnt)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// This example uses TCP to send an HTTP request to retrieve a webpage. The
|
||||
// HTTP request is hand-rolled to avoid the overhead of using http.Get() from
|
||||
// the "net/http" package. See example/net/http-get for the full http.Get()
|
||||
// functionality.
|
||||
//
|
||||
// Example HTTP server:
|
||||
// ---------------------------------------------------------------------------
|
||||
// package main
|
||||
//
|
||||
// import "net/http"
|
||||
//
|
||||
// func main() {
|
||||
// http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
// w.Write([]byte("hello"))
|
||||
// })
|
||||
// http.ListenAndServe(":8080", nil)
|
||||
// }
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
// HTTP server address to hit with a GET / request
|
||||
address string = "10.0.0.100:8080"
|
||||
)
|
||||
|
||||
var conn net.Conn
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func dialConnection() {
|
||||
var err error
|
||||
|
||||
println("\r\n---------------\r\nDialing TCP connection")
|
||||
conn, err = net.Dial("tcp", address)
|
||||
for ; err != nil; conn, err = net.Dial("tcp", address) {
|
||||
println("Connection failed:", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
println("Connected!\r")
|
||||
}
|
||||
|
||||
func check(err error) {
|
||||
if err != nil {
|
||||
println("Hit an error:", err.Error())
|
||||
panic("BYE")
|
||||
}
|
||||
}
|
||||
|
||||
func makeRequest() {
|
||||
println("Sending HTTP request...")
|
||||
w := bufio.NewWriter(conn)
|
||||
fmt.Fprintln(w, "GET / HTTP/1.1")
|
||||
fmt.Fprintln(w, "Host:", strings.Split(address, ":")[0])
|
||||
fmt.Fprintln(w, "User-Agent: TinyGo")
|
||||
fmt.Fprintln(w, "Connection: close")
|
||||
fmt.Fprintln(w)
|
||||
check(w.Flush())
|
||||
println("Sent!\r\n\r")
|
||||
}
|
||||
|
||||
func readResponse() {
|
||||
r := bufio.NewReader(conn)
|
||||
resp, err := io.ReadAll(r)
|
||||
check(err)
|
||||
println(string(resp))
|
||||
}
|
||||
|
||||
func closeConnection() {
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
func main() {
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for i := 0; ; i++ {
|
||||
dialConnection()
|
||||
makeRequest()
|
||||
readResponse()
|
||||
closeConnection()
|
||||
println("--------", i, "--------\r\n")
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || arduino_nano33 || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal arduino_nano33 nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -1,30 +1,26 @@
|
||||
// This example listens on port :80 serving a web page. Multiple clients
|
||||
// may connect and be serviced at the same time. IPv4 only. HTTP only.
|
||||
//
|
||||
// $ curl http://10.0.0.2
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
// You can override the settings with the init() in another source code:
|
||||
//
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// }
|
||||
//
|
||||
// Or use -ldflags option on tinygo command to set at compile-time:
|
||||
//
|
||||
// tinygo flash ... -ldflags '-X "main.ssid=xxx" -X "main.pass=xxx"' ...
|
||||
//
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
port string = ":80"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -35,36 +31,15 @@ var (
|
||||
var led = machine.LED
|
||||
|
||||
func main() {
|
||||
|
||||
// wait a bit for serial
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
|
||||
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
|
||||
spi := machine.NINA_SPI
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
http.UseDriver(adaptor)
|
||||
|
||||
http.HandleFunc("/", root)
|
||||
http.HandleFunc("/hello", hello)
|
||||
@@ -73,7 +48,11 @@ func run() error {
|
||||
http.HandleFunc("/off", LED_OFF)
|
||||
http.HandleFunc("/on", LED_ON)
|
||||
|
||||
return http.ListenAndServe(":80", nil)
|
||||
err := http.ListenAndServe(port, nil)
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func root(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -148,7 +127,7 @@ func root(w http.ResponseWriter, r *http.Request) {
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
`, access)
|
||||
`, access)
|
||||
}
|
||||
|
||||
func sixlines(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,54 @@
|
||||
// This example is a websocket client. It connects to a websocket server
|
||||
// which echos messages back to the client. For server, see
|
||||
//
|
||||
// https://pkg.go.dev/golang.org/x/net/websocket#example-Handler
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using
|
||||
// "golang.org/x/net/websocket". Use the -stack-size=4KB command line option.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
url string = "ws://10.0.0.100:8080/echo"
|
||||
)
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
origin := "http://localhost/"
|
||||
ws, err := websocket.Dial(url, "", origin)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var msg = make([]byte, 512)
|
||||
var n int
|
||||
if n, err = ws.Read(msg); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("Received: %s", msg[:n])
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -0,0 +1,52 @@
|
||||
// This example is a websocket server. It listens for websocket clients
|
||||
// to connect and echos messages back to the client. For client, see
|
||||
//
|
||||
// https://pkg.go.dev/golang.org/x/net/websocket#example-Dial
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using
|
||||
// "golang.org/x/net/websocket". Use the -stack-size=4KB command line option.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"machine"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
port string = ":8080"
|
||||
)
|
||||
|
||||
// Echo the data received on the WebSocket.
|
||||
func EchoServer(ws *websocket.Conn) {
|
||||
io.Copy(ws, ws)
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// This example demonstrates a trivial echo server.
|
||||
func main() {
|
||||
waitSerial()
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
http.Handle("/echo", websocket.Handler(EchoServer))
|
||||
err := http.ListenAndServe(port, nil)
|
||||
if err != nil {
|
||||
panic("ListenAndServe: " + err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 30 KiB |
@@ -0,0 +1,28 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>TinyGo - A Go Compiler For Small Places</title>
|
||||
<style>
|
||||
body {
|
||||
background-color: rgb(4, 111, 143);
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
img {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
width: 299px;
|
||||
height: 255px;
|
||||
}
|
||||
h1 {
|
||||
color: white;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TinyGo - A Go Compiler For Small Places</h1>
|
||||
<img src="images/tinygo-logo.png">
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
// This example is an HTTP server serving up a static file system
|
||||
//
|
||||
// Note: It may be necessary to increase the stack size when using "net/http".
|
||||
// Use the -stack-size=4KB command line option.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
port string = ":80"
|
||||
)
|
||||
|
||||
//go:embed index.html main.go images
|
||||
var fs embed.FS
|
||||
|
||||
func main() {
|
||||
// wait a bit for console
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
if err := netdev.NetConnect(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
hfs := http.FileServer(http.FS(fs))
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
hfs.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
log.Fatal(http.ListenAndServe(port, nil))
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build wioterminal
|
||||
|
||||
// +build: wioterminal
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var cfg = rtl8720dn.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Device
|
||||
En: machine.RTL8720D_CHIP_PU,
|
||||
// UART
|
||||
Uart: machine.UART3,
|
||||
Tx: machine.PB24,
|
||||
Rx: machine.PC24,
|
||||
Baudrate: 614400,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = rtl8720dn.New(&cfg)
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build pyportal || nano_rp2040 || metro_m4_airlift || arduino_mkrwifi1010 || matrixportal_m4
|
||||
|
||||
// +build: pyportal nano_rp2040 metro_m4_airlift arduino_mkrwifi1010 matrixportal_m4
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var cfg = wifinina.Config{
|
||||
// WiFi AP credentials
|
||||
Ssid: ssid,
|
||||
Passphrase: pass,
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
Spi: machine.NINA_SPI,
|
||||
Freq: 8 * 1e6,
|
||||
Sdo: machine.NINA_SDO,
|
||||
Sdi: machine.NINA_SDI,
|
||||
Sck: machine.NINA_SCK,
|
||||
// Device pins
|
||||
Cs: machine.NINA_CS,
|
||||
Ack: machine.NINA_ACK,
|
||||
Gpio0: machine.NINA_GPIO0,
|
||||
Resetn: machine.NINA_RESETN,
|
||||
// Watchdog (set to 0 to disable)
|
||||
WatchdogTimeo: time.Duration(20 * time.Second),
|
||||
}
|
||||
|
||||
var netdev = wifinina.New(&cfg)
|
||||
@@ -1,131 +0,0 @@
|
||||
// This is a sensor station that uses a RTL8720DN running on the device UART2.
|
||||
// It creates an MQTT connection that publishes a message every second
|
||||
// to an MQTT broker.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> USB-CDC <--> MCU <--> UART2 <--> RTL8720DN <--> Internet <--> MQTT broker.
|
||||
//
|
||||
// You must install the Paho MQTT package to build this program:
|
||||
//
|
||||
// go get -u github.com/eclipse/paho.mqtt.golang
|
||||
//
|
||||
// You can check that mqttpub is running successfully with the following command.
|
||||
//
|
||||
// mosquitto_sub -h test.mosquitto.org -t tinygo
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/net/mqtt"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// debug = true
|
||||
// server = "tinygo.org"
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
server string = "tcp://test.mosquitto.org:1883"
|
||||
debug = false
|
||||
)
|
||||
|
||||
var buf [0x400]byte
|
||||
|
||||
var lastRequestTime time.Time
|
||||
var conn net.Conn
|
||||
var adaptor *rtl8720dn.Driver
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
topic = "tinygo"
|
||||
)
|
||||
|
||||
func run() error {
|
||||
// change the UART and pins as needed for platforms other than the WioTerminal.
|
||||
adaptor = rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
|
||||
|
||||
println("Connectng to MQTT...")
|
||||
cl := mqtt.NewClient(opts)
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
for i := 0; ; i++ {
|
||||
println("Publishing MQTT message...")
|
||||
data := []byte(fmt.Sprintf(`{"e":[{"n":"hello %d","v":101}]}`, i))
|
||||
token := cl.Publish(topic, 0, false, data)
|
||||
token.Wait()
|
||||
if err := token.Error(); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting MQTT...")
|
||||
cl.Disconnect(100)
|
||||
|
||||
println("Done.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
// This is a sensor station that uses a RTL8720DN running on the device UART2.
|
||||
// It creates an MQTT connection that publishes a message every second
|
||||
// to an MQTT broker.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> USB-CDC <--> MCU <--> UART2 <--> RTL8720DN <--> Internet <--> MQTT broker.
|
||||
//
|
||||
// You must also install the Paho MQTT package to build this program:
|
||||
//
|
||||
// go get -u github.com/eclipse/paho.mqtt.golang
|
||||
//
|
||||
// You can check that mqttpub/mqttsub is running successfully with the following command.
|
||||
//
|
||||
// mosquitto_sub -h test.mosquitto.org -t tinygo/tx
|
||||
// mosquitto_pub -h test.mosquitto.org -t tinygo/rx -m "hello world"
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/net/mqtt"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// debug = true
|
||||
// server = "tinygo.org"
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
server string = "tcp://test.mosquitto.org:1883"
|
||||
debug = false
|
||||
)
|
||||
|
||||
var buf [0x400]byte
|
||||
|
||||
var lastRequestTime time.Time
|
||||
var conn net.Conn
|
||||
var adaptor *rtl8720dn.Driver
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
cl mqtt.Client
|
||||
topicTx = "tinygo/tx"
|
||||
topicRx = "tinygo/rx"
|
||||
)
|
||||
|
||||
func subHandler(client mqtt.Client, msg mqtt.Message) {
|
||||
fmt.Printf("[%s] ", msg.Topic())
|
||||
fmt.Printf("%s\r\n", msg.Payload())
|
||||
}
|
||||
|
||||
func run() error {
|
||||
// change the UART and pins as needed for platforms other than the WioTerminal.
|
||||
adaptor = rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
|
||||
|
||||
println("Connecting to MQTT broker at", server)
|
||||
cl = mqtt.NewClient(opts)
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
// subscribe
|
||||
token := cl.Subscribe(topicRx, 0, subHandler)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
go publishing()
|
||||
|
||||
select {}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting MQTT...")
|
||||
cl.Disconnect(100)
|
||||
|
||||
println("Done.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func publishing() {
|
||||
for i := 0; ; i++ {
|
||||
println("Publishing MQTT message...")
|
||||
data := []byte(fmt.Sprintf(`{"e":[{"n":"hello %d","v":101}]}`, i))
|
||||
token := cl.Publish(topicTx, 0, false, data)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
println(token.Error().Error())
|
||||
}
|
||||
|
||||
time.Sleep(20 * 100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
// This is an example of using the rtl8720dn driver to implement a NTP client.
|
||||
// It creates a UDP connection to request the current time and parse the
|
||||
// response from a NTP server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// ntpHost = "129.6.15.29"
|
||||
// debug = true
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
ntpHost = "129.6.15.29"
|
||||
debug = false
|
||||
)
|
||||
|
||||
const NTP_PACKET_SIZE = 48
|
||||
|
||||
var b = make([]byte, NTP_PACKET_SIZE)
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
// now make UDP connection
|
||||
hip := net.ParseIP(ntpHost)
|
||||
raddr := &net.UDPAddr{IP: hip, Port: 123}
|
||||
laddr := &net.UDPAddr{Port: 2390}
|
||||
conn, err := net.DialUDP("udp", laddr, raddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
// send data
|
||||
println("Requesting NTP time...")
|
||||
t, err := getCurrentTime(conn)
|
||||
if err != nil {
|
||||
message("Error getting current time: %v", err)
|
||||
} else {
|
||||
message("NTP time: %v", t)
|
||||
}
|
||||
runtime.AdjustTimeOffset(-1 * int64(time.Since(t)))
|
||||
for i := 0; i < 10; i++ {
|
||||
message("Current time: %v", time.Now())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func getCurrentTime(conn *net.UDPSerialConn) (time.Time, error) {
|
||||
if err := sendNTPpacket(conn); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
clearBuffer()
|
||||
for now := time.Now(); time.Since(now) < time.Second; {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
if n, err := conn.Read(b); err != nil {
|
||||
return time.Time{}, fmt.Errorf("error reading UDP packet: %w", err)
|
||||
} else if n == 0 {
|
||||
continue // no packet received yet
|
||||
} else if n != NTP_PACKET_SIZE {
|
||||
return time.Time{}, fmt.Errorf("expected NTP packet size of %d: %d", NTP_PACKET_SIZE, n)
|
||||
}
|
||||
return parseNTPpacket(), nil
|
||||
}
|
||||
return time.Time{}, errors.New("no packet received after 1 second")
|
||||
}
|
||||
|
||||
func sendNTPpacket(conn *net.UDPSerialConn) error {
|
||||
clearBuffer()
|
||||
b[0] = 0b11100011 // LI, Version, Mode
|
||||
b[1] = 0 // Stratum, or type of clock
|
||||
b[2] = 6 // Polling Interval
|
||||
b[3] = 0xEC // Peer Clock Precision
|
||||
// 8 bytes of zero for Root Delay & Root Dispersion
|
||||
b[12] = 49
|
||||
b[13] = 0x4E
|
||||
b[14] = 49
|
||||
b[15] = 52
|
||||
if _, err := conn.Write(b); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseNTPpacket() time.Time {
|
||||
// the timestamp starts at byte 40 of the received packet and is four bytes,
|
||||
// this is NTP time (seconds since Jan 1 1900):
|
||||
t := uint32(b[40])<<24 | uint32(b[41])<<16 | uint32(b[42])<<8 | uint32(b[43])
|
||||
const seventyYears = 2208988800
|
||||
return time.Unix(int64(t-seventyYears), 0)
|
||||
}
|
||||
|
||||
func clearBuffer() {
|
||||
for i := range b {
|
||||
b[i] = 0
|
||||
}
|
||||
}
|
||||
|
||||
func message(format string, args ...interface{}) {
|
||||
println(fmt.Sprintf(format, args...), "\r")
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
// This example opens a TCP connection using a device with RTL8720DN firmware
|
||||
// and sends some data, for the purpose of testing speed and connectivity.
|
||||
//
|
||||
// You can open a server to accept connections from this program using:
|
||||
//
|
||||
// nc -w 5 -lk 8080
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"bytes"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// serverIP = "192.168.1.119"
|
||||
// debug = true
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
serverIP = ""
|
||||
debug = false
|
||||
)
|
||||
|
||||
var buf = &bytes.Buffer{}
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
for {
|
||||
sendBatch()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
println("Done.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendBatch() {
|
||||
|
||||
// make TCP connection
|
||||
ip := net.ParseIP(serverIP)
|
||||
raddr := &net.TCPAddr{IP: ip, Port: 8080}
|
||||
laddr := &net.TCPAddr{Port: 8080}
|
||||
|
||||
message("---------------\r\nDialing TCP connection")
|
||||
conn, err := net.DialTCP("tcp", laddr, raddr)
|
||||
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
|
||||
message(err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
|
||||
n := 0
|
||||
w := 0
|
||||
start := time.Now()
|
||||
|
||||
// send data
|
||||
message("Sending data")
|
||||
|
||||
for i := 0; i < 1000; i++ {
|
||||
buf.Reset()
|
||||
fmt.Fprint(buf,
|
||||
"\r---------------------------- i == ", i, " ----------------------------"+
|
||||
"\r---------------------------- i == ", i, " ----------------------------")
|
||||
if w, err = conn.Write(buf.Bytes()); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
continue
|
||||
}
|
||||
n += w
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
ms := time.Now().Sub(start).Milliseconds()
|
||||
fmt.Fprint(buf, "\nWrote ", n, " bytes in ", ms, " ms\r\n")
|
||||
message(buf.String())
|
||||
|
||||
if _, err := conn.Write(buf.Bytes()); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting TCP...")
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"bufio"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// debug = true
|
||||
// url = "https://www.example.com"
|
||||
// test_root_ca = "..."
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
url string = "https://www.example.com"
|
||||
debug = false
|
||||
)
|
||||
|
||||
// Set the test_root_ca created by the following command
|
||||
// $ openssl s_client -showcerts -verify 5 -connect www.example.com:443 < /dev/null
|
||||
var test_root_ca = `-----BEGIN CERTIFICATE-----
|
||||
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
|
||||
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
|
||||
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
|
||||
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
|
||||
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
|
||||
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
|
||||
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
|
||||
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
|
||||
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
|
||||
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
|
||||
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
|
||||
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
|
||||
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
|
||||
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
|
||||
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
|
||||
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
|
||||
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
|
||||
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
|
||||
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
|
||||
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
var buf [0x1000]byte
|
||||
|
||||
var lastRequestTime time.Time
|
||||
var conn net.Conn
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
adaptor.SetRootCA(&test_root_ca)
|
||||
http.SetBuf(buf[:])
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
// You can send and receive cookies in the following way
|
||||
// import "tinygo.org/x/drivers/net/http/cookiejar"
|
||||
// jar, err := cookiejar.New(nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// client := &http.Client{Jar: jar}
|
||||
// http.DefaultClient = client
|
||||
|
||||
cnt := 0
|
||||
for {
|
||||
// Various examples are as follows
|
||||
//
|
||||
// -- Get
|
||||
// resp, err := http.Get(url)
|
||||
//
|
||||
// -- Post
|
||||
// body := `cnt=12`
|
||||
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
|
||||
//
|
||||
// -- Post with JSON
|
||||
// body := `{"msg": "hello"}`
|
||||
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
|
||||
for k, v := range resp.Header {
|
||||
fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
|
||||
}
|
||||
fmt.Printf("\r\n")
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
fmt.Printf("%s\r\n", scanner.Text())
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
cnt++
|
||||
fmt.Printf("-------- %d --------\r\n", cnt)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// hubIP = "192.168.1.118"
|
||||
// debug = true
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
hubIP = ""
|
||||
debug = false
|
||||
)
|
||||
|
||||
var buf [0x400]byte
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
http.SetBuf(buf[:])
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
// now make UDP connection
|
||||
hip := net.ParseIP(hubIP)
|
||||
raddr := &net.UDPAddr{IP: hip, Port: 2222}
|
||||
laddr := &net.UDPAddr{Port: 2222}
|
||||
|
||||
println("Dialing UDP connection...")
|
||||
conn, err := net.DialUDP("udp", laddr, raddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
// send data
|
||||
println("Sending data...")
|
||||
for i := 0; i < 25; i++ {
|
||||
conn.Write([]byte("hello " + strconv.Itoa(i) + "\r\n"))
|
||||
}
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting UDP...")
|
||||
conn.Close()
|
||||
println("Done.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var (
|
||||
debug = false
|
||||
)
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
ver, err := adaptor.Version()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
for {
|
||||
fmt.Printf("RTL8270DN Firmware Version: %s\r\n", ver)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"bufio"
|
||||
"fmt"
|
||||
"image/color"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/ili9341"
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
|
||||
"tinygo.org/x/tinyfont/proggy"
|
||||
"tinygo.org/x/tinyterm"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// If debug is enabled, a serial connection is required.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// debug = false // true
|
||||
// server = "tinygo.org"
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
url = "http://tinygo.org/"
|
||||
debug = false
|
||||
)
|
||||
|
||||
var (
|
||||
display = ili9341.NewSPI(
|
||||
machine.SPI3,
|
||||
machine.LCD_DC,
|
||||
machine.LCD_SS_PIN,
|
||||
machine.LCD_RESET,
|
||||
)
|
||||
|
||||
backlight = machine.LCD_BACKLIGHT
|
||||
|
||||
terminal = tinyterm.NewTerminal(display)
|
||||
|
||||
black = color.RGBA{0, 0, 0, 255}
|
||||
white = color.RGBA{255, 255, 255, 255}
|
||||
red = color.RGBA{255, 0, 0, 255}
|
||||
blue = color.RGBA{0, 0, 255, 255}
|
||||
green = color.RGBA{0, 255, 0, 255}
|
||||
|
||||
font = &proggy.TinySZ8pt7b
|
||||
)
|
||||
|
||||
var buf [0x400]byte
|
||||
|
||||
func main() {
|
||||
display.FillScreen(black)
|
||||
backlight.High()
|
||||
|
||||
terminal.Configure(&tinyterm.Config{
|
||||
Font: font,
|
||||
FontHeight: 10,
|
||||
FontOffset: 6,
|
||||
})
|
||||
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Fprintf(terminal, "error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
fmt.Fprintf(terminal, "setupRTL8720DN()\r\n")
|
||||
if debug {
|
||||
fmt.Fprintf(terminal, "Running in debug mode.\r\n")
|
||||
fmt.Fprintf(terminal, "A serial connection is required to continue execution.\r\n")
|
||||
}
|
||||
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
http.UseDriver(adaptor)
|
||||
http.SetBuf(buf[:])
|
||||
|
||||
fmt.Fprintf(terminal, "ConnectToAP()\r\n")
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(terminal, "connected\r\n\r\n")
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(terminal, "IP Address : %s\r\n", ip)
|
||||
fmt.Fprintf(terminal, "Mask : %s\r\n", subnet)
|
||||
fmt.Fprintf(terminal, "Gateway : %s\r\n", gateway)
|
||||
|
||||
// You can send and receive cookies in the following way
|
||||
// import "tinygo.org/x/drivers/net/http/cookiejar"
|
||||
// jar, err := cookiejar.New(nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// client := &http.Client{Jar: jar}
|
||||
// http.DefaultClient = client
|
||||
|
||||
cnt := 0
|
||||
for {
|
||||
// Various examples are as follows
|
||||
//
|
||||
// -- Get
|
||||
// resp, err := http.Get(url)
|
||||
//
|
||||
// -- Post
|
||||
// body := `cnt=12`
|
||||
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
|
||||
//
|
||||
// -- Post with JSON
|
||||
// body := `{"msg": "hello"}`
|
||||
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Fprintf(terminal, "%s %s\r\n", resp.Proto, resp.Status)
|
||||
for k, v := range resp.Header {
|
||||
fmt.Fprintf(terminal, "%s: %s\r\n", k, strings.Join(v, " "))
|
||||
}
|
||||
fmt.Printf("\r\n")
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
fmt.Fprintf(terminal, "%s\r\n", scanner.Text())
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
cnt++
|
||||
fmt.Fprintf(terminal, "-------- %d --------\r\n", cnt)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
machine.SPI3.Configure(machine.SPIConfig{
|
||||
SCK: machine.LCD_SCK_PIN,
|
||||
SDO: machine.LCD_SDO_PIN,
|
||||
SDI: machine.LCD_SDI_PIN,
|
||||
Frequency: 40000000,
|
||||
})
|
||||
display.Configure(ili9341.Config{})
|
||||
|
||||
backlight.Configure(machine.PinConfig{machine.PinOutput})
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
|
||||
"bufio"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// url = "http://tinygo.org/"
|
||||
// debug = true
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
url = "http://tinygo.org/"
|
||||
debug = false
|
||||
)
|
||||
|
||||
var buf [0x400]byte
|
||||
|
||||
func main() {
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
http.UseDriver(adaptor)
|
||||
http.SetBuf(buf[:])
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
// You can send and receive cookies in the following way
|
||||
// import "tinygo.org/x/drivers/net/http/cookiejar"
|
||||
// jar, err := cookiejar.New(nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// client := &http.Client{Jar: jar}
|
||||
// http.DefaultClient = client
|
||||
|
||||
cnt := 0
|
||||
for {
|
||||
// Various examples are as follows
|
||||
//
|
||||
// -- Get
|
||||
// resp, err := http.Get(url)
|
||||
//
|
||||
// -- Post
|
||||
// body := `cnt=12`
|
||||
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
|
||||
//
|
||||
// -- Post with JSON
|
||||
// body := `{"msg": "hello"}`
|
||||
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
|
||||
for k, v := range resp.Header {
|
||||
fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
|
||||
}
|
||||
fmt.Printf("\r\n")
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
fmt.Printf("%s\r\n", scanner.Text())
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
cnt++
|
||||
fmt.Printf("-------- %d --------\r\n", cnt)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"machine"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
// You can override the setting with the init() in another source code.
|
||||
// func init() {
|
||||
// ssid = "your-ssid"
|
||||
// pass = "your-password"
|
||||
// debug = true
|
||||
// }
|
||||
|
||||
var (
|
||||
ssid string
|
||||
pass string
|
||||
debug = false
|
||||
)
|
||||
|
||||
var led = machine.LED
|
||||
var backlight = machine.LCD_BACKLIGHT
|
||||
|
||||
func main() {
|
||||
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
|
||||
backlight.Configure(machine.PinConfig{Mode: machine.PinOutput})
|
||||
|
||||
err := run()
|
||||
for err != nil {
|
||||
fmt.Printf("error: %s\r\n", err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU)
|
||||
adaptor.Debug(debug)
|
||||
adaptor.Configure()
|
||||
|
||||
http.UseDriver(adaptor)
|
||||
|
||||
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("IP Address : %s\r\n", ip)
|
||||
fmt.Printf("Mask : %s\r\n", subnet)
|
||||
fmt.Printf("Gateway : %s\r\n", gateway)
|
||||
|
||||
http.HandleFunc("/", root)
|
||||
http.HandleFunc("/hello", hello)
|
||||
http.HandleFunc("/cnt", cnt)
|
||||
http.HandleFunc("/6", sixlines)
|
||||
http.HandleFunc("/off", LED_OFF)
|
||||
http.HandleFunc("/on", LED_ON)
|
||||
if err := http.ListenAndServe(":80", nil); err != nil {
|
||||
message(err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func root(w http.ResponseWriter, r *http.Request) {
|
||||
access := 1
|
||||
|
||||
cookie, err := r.Cookie("access")
|
||||
if err != nil {
|
||||
if err == http.ErrNoCookie {
|
||||
cookie = &http.Cookie{
|
||||
Name: "access",
|
||||
Value: "1",
|
||||
}
|
||||
} else {
|
||||
http.Error(w, fmt.Sprintf("%s", err.Error()), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
v, err := strconv.ParseInt(cookie.Value, 10, 0)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("invalid cookie.Value : %s", cookie.Value), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
cookie.Value = fmt.Sprintf("%d", v+1)
|
||||
access = int(v) + 1
|
||||
}
|
||||
http.SetCookie(w, cookie)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
fmt.Fprintf(w, `
|
||||
<html>
|
||||
<head>
|
||||
<title>TinyGo HTTP Server</title>
|
||||
<script language="javascript" type="text/javascript">
|
||||
var counter = 0
|
||||
function ledOn() { fetch("/on").then(response => response.text()).then(text => { led.innerHTML = "<p>on</p>"; }); }
|
||||
function ledOff() { fetch("/off").then(response => response.text()).then(text => { led.innerHTML = "<p>off</p>"; }); }
|
||||
function fetchCnt() { fetch("/cnt").then(response => response.json()).then(json => { counter = json.cnt; cnt.innerHTML = counter; }); }
|
||||
function incrCnt() { counter = counter + 1; fetch("/cnt?cnt=" + counter, { method: 'POST' }).then(response => response.json()).then(json => { counter = json.cnt; cnt.innerHTML = counter; }); }
|
||||
function setCnt() { fetch("/cnt", {
|
||||
method: "POST",
|
||||
body: "cnt=" + document.getElementsByName("cnt")[0].value,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
}).then(response => response.json()).then(json => { counter = json.cnt; cnt.innerHTML = counter; }); return false; }
|
||||
function onLoad() { fetchCnt(); }
|
||||
</script>
|
||||
</head>
|
||||
<body onLoad="onLoad()">
|
||||
<h5>TinyGo HTTP Server</h5>
|
||||
|
||||
<p>
|
||||
access: %d
|
||||
</p>
|
||||
|
||||
<a href="/hello">/hello</a><br>
|
||||
<a href="/6">/6</a><br>
|
||||
|
||||
<p>
|
||||
LED<br>
|
||||
<a href="javascript:ledOn();">/on</a><br>
|
||||
<a href="javascript:ledOff();">/off</a><br>
|
||||
</p>
|
||||
|
||||
|
||||
<p>
|
||||
<a href="/cnt">/cnt</a><br>
|
||||
cnt: <span id="cnt"></span><br>
|
||||
<a href="javascript:incrCnt()">incrCnt()</a><br>
|
||||
<form id="form1" style="display: inline" onSubmit="return setCnt()">
|
||||
<input type="text" name="cnt">
|
||||
<input type="button" value="set cnt", onClick="setCnt()">
|
||||
</form>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
`, access)
|
||||
}
|
||||
|
||||
func sixlines(w http.ResponseWriter, r *http.Request) {
|
||||
// https://fukuno.jig.jp/3267
|
||||
fmt.Fprint(w, `<body onload='onkeydown=e=>K=parseInt(e.key[5]||6,28)/3-8;Z=X=[B=A=12];Y=_=>`+
|
||||
`{for(C=[q=c=i=4];f=i--*K;c-=!Z[h+(K+6?p+K:C[i]=p*A-(p/9|0)*145)])p=B[i];for(c?0:K+6?h+=K:B=C;`+
|
||||
`i=K=q--;f+=Z[A+p])X[p=h+B[q]]=1;h+=A;if(f|B)for(Z=X,X=[l=228],B=[[-7,-20,6,h=17,-9,3,3][t=++t%7]-4,0,1,t-6?-A:2];l--;)`+
|
||||
`for(l%A?l-=l%A*!Z[l]:(P++,c=l+=A);--c>A;)Z[c]=Z[c-A];for(S="";i<240;S+=X[i]|(X[i]=Z[i]|=++i%A<2|i>228)?i%A?"■":"■<br>":" ");`+
|
||||
`D.innerHTML=S+P;setTimeout(Y,i-P)};Y(h=K=t=P=0)'id=D>`)
|
||||
}
|
||||
|
||||
func LED_ON(w http.ResponseWriter, r *http.Request) {
|
||||
led.High()
|
||||
backlight.High()
|
||||
w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`)
|
||||
fmt.Fprintf(w, "led.High()")
|
||||
}
|
||||
|
||||
func LED_OFF(w http.ResponseWriter, r *http.Request) {
|
||||
led.Low()
|
||||
backlight.Low()
|
||||
w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`)
|
||||
fmt.Fprintf(w, "led.Low()")
|
||||
}
|
||||
|
||||
func hello(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`)
|
||||
fmt.Fprintf(w, "hello")
|
||||
}
|
||||
|
||||
var counter int
|
||||
|
||||
func cnt(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
if r.Method == "POST" {
|
||||
c := r.Form.Get("cnt")
|
||||
if c != "" {
|
||||
i64, _ := strconv.ParseInt(c, 0, 0)
|
||||
counter = int(i64)
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set(`Content-Type`, `application/json`)
|
||||
fmt.Fprintf(w, `{"cnt": %d}`, counter)
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
//go:build espat
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"tinygo.org/x/drivers/espat"
|
||||
)
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// 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
|
||||
)
|
||||
|
||||
func initAdaptor() *espat.Device {
|
||||
uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
|
||||
|
||||
adaptor = espat.New(uart)
|
||||
adaptor.Configure()
|
||||
|
||||
return adaptor
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
//go:build rtl8720dn
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"device/sam"
|
||||
"machine"
|
||||
"runtime/interrupt"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/rtl8720dn"
|
||||
)
|
||||
|
||||
var (
|
||||
adaptor *rtl8720dn.RTL8720DN
|
||||
|
||||
uart UARTx
|
||||
)
|
||||
|
||||
func initAdaptor() *rtl8720dn.RTL8720DN {
|
||||
adaptor, err := setupRTL8720DN()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
net.UseDriver(adaptor)
|
||||
|
||||
return adaptor
|
||||
}
|
||||
|
||||
func handleInterrupt(interrupt.Interrupt) {
|
||||
// should reset IRQ
|
||||
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
|
||||
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
|
||||
}
|
||||
|
||||
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
|
||||
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
|
||||
machine.RTL8720D_CHIP_PU.Low()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
machine.RTL8720D_CHIP_PU.High()
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
uart = UARTx{
|
||||
UART: &machine.UART{
|
||||
Buffer: machine.NewRingBuffer(),
|
||||
Bus: sam.SERCOM0_USART_INT,
|
||||
SERCOM: 0,
|
||||
},
|
||||
}
|
||||
|
||||
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
|
||||
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
|
||||
|
||||
rtl := rtl8720dn.New(uart)
|
||||
//rtl.Debug(debug)
|
||||
|
||||
_, err := rtl.Rpc_tcpip_adapter_init()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return rtl, nil
|
||||
}
|
||||
|
||||
type UARTx struct {
|
||||
*machine.UART
|
||||
}
|
||||
|
||||
func (u UARTx) Read(p []byte) (n int, err error) {
|
||||
if u.Buffered() == 0 {
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
return 0, nil
|
||||
}
|
||||
return u.UART.Read(p)
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
//go:build wifinina
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// default interface for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// ESP32/ESP8266 chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
func initAdaptor() *wifinina.Device {
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
|
||||
return adaptor
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
// This example connects to Access Point and prints some info
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
func setup() {
|
||||
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
setup()
|
||||
|
||||
waitSerial()
|
||||
|
||||
connectToAP()
|
||||
|
||||
for {
|
||||
println("----------------------------------------")
|
||||
printSSID()
|
||||
printRSSI()
|
||||
printMac()
|
||||
printIPs()
|
||||
printTime()
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func printSSID() {
|
||||
print("SSID: ")
|
||||
ssid, err := adaptor.GetCurrentSSID()
|
||||
if err != nil {
|
||||
println("Unknown (error: ", err.Error(), ")")
|
||||
return
|
||||
}
|
||||
println(ssid)
|
||||
}
|
||||
|
||||
func printRSSI() {
|
||||
print("RSSI: ")
|
||||
rssi, err := adaptor.GetCurrentRSSI()
|
||||
if err != nil {
|
||||
println("Unknown (error: ", err.Error(), ")")
|
||||
return
|
||||
}
|
||||
println(strconv.Itoa(int(rssi)))
|
||||
}
|
||||
|
||||
func printIPs() {
|
||||
ip, subnet, gateway, err := adaptor.GetIP()
|
||||
if err != nil {
|
||||
println("IP: Unknown (error: ", err.Error(), ")")
|
||||
return
|
||||
}
|
||||
println("IP: ", ip.String())
|
||||
println("Subnet: ", subnet.String())
|
||||
println("Gateway: ", gateway.String())
|
||||
}
|
||||
|
||||
func printTime() {
|
||||
print("Time: ")
|
||||
t, err := adaptor.GetTime()
|
||||
for {
|
||||
if err != nil {
|
||||
println("Unknown (error: ", err.Error(), ")")
|
||||
return
|
||||
}
|
||||
if t != 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
t, err = adaptor.GetTime()
|
||||
}
|
||||
println(time.Unix(int64(t), 0).String())
|
||||
}
|
||||
|
||||
func printMac() {
|
||||
print("MAC: ")
|
||||
mac, err := adaptor.GetMACAddress()
|
||||
if err != nil {
|
||||
println("Unknown (", err.Error(), ")")
|
||||
}
|
||||
println(mac.String())
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
// This example opens a TCP connection using a device with WiFiNINA firmware
|
||||
// and sends a HTTP request to retrieve a webpage, based on the following
|
||||
// Arduino example:
|
||||
//
|
||||
// https://github.com/arduino-libraries/WiFiNINA/blob/master/examples/WiFiWebClientRepeating/
|
||||
//
|
||||
// This example will not work with samd21 or other systems with less than 32KB
|
||||
// of RAM. Use the following if you want to run wifinina on samd21, etc.
|
||||
//
|
||||
// examples/wifinina/webclient
|
||||
// examples/wifinina/tlsclient
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"machine"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/net/http"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
// Can specify a URL starting with http or https
|
||||
const url = "http://tinygo.org/"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
var buf [0x400]byte
|
||||
|
||||
var lastRequestTime time.Time
|
||||
var conn net.Conn
|
||||
|
||||
func setup() {
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
setup()
|
||||
http.SetBuf(buf[:])
|
||||
|
||||
waitSerial()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
// You can send and receive cookies in the following way
|
||||
// import "tinygo.org/x/drivers/net/http/cookiejar"
|
||||
// jar, err := cookiejar.New(nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// client := &http.Client{Jar: jar}
|
||||
// http.DefaultClient = client
|
||||
|
||||
cnt := 0
|
||||
for {
|
||||
// Various examples are as follows
|
||||
//
|
||||
// -- Get
|
||||
// resp, err := http.Get(url)
|
||||
//
|
||||
// -- Post
|
||||
// body := `cnt=12`
|
||||
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
|
||||
//
|
||||
// -- Post with JSON
|
||||
// body := `{"msg": "hello"}`
|
||||
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
fmt.Printf("%s\r\n", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
|
||||
for k, v := range resp.Header {
|
||||
fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
|
||||
}
|
||||
fmt.Printf("\r\n")
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
fmt.Printf("%s\r\n", scanner.Text())
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
cnt++
|
||||
fmt.Printf("-------- %d --------\r\n", cnt)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
// 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 (
|
||||
"fmt"
|
||||
"machine"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net/mqtt"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the MQTT broker to use. Replace with your own info.
|
||||
const server = "tcp://test.mosquitto.org:1883"
|
||||
|
||||
//const server = "ssl://test.mosquitto.org:8883"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
topic = "tinygo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
time.Sleep(3000 * time.Millisecond)
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
// Init esp8266/esp32
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
|
||||
|
||||
println("Connectng to MQTT...")
|
||||
cl := mqtt.NewClient(opts)
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
for i := 0; ; i++ {
|
||||
println("Publishing MQTT message...")
|
||||
data := []byte(fmt.Sprintf(`{"e":[{"n":"hello %d","v":101}]}`, i))
|
||||
token := cl.Publish(topic, 0, false, data)
|
||||
token.Wait()
|
||||
if err := token.Error(); err != nil {
|
||||
switch t := err.(type) {
|
||||
case wifinina.Error:
|
||||
println(t.Error(), "attempting to reconnect")
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
default:
|
||||
println(err.Error())
|
||||
}
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting MQTT...")
|
||||
cl.Disconnect(100)
|
||||
|
||||
println("Done.")
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
println(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
println("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
// 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 also install the Paho MQTT package to build this program:
|
||||
//
|
||||
// go get -u github.com/eclipse/paho.mqtt.golang
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"machine"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net/mqtt"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the MQTT broker to use. Replace with your own info.
|
||||
const server = "tcp://test.mosquitto.org:1883"
|
||||
|
||||
//const server = "ssl://test.mosquitto.org:8883"
|
||||
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
|
||||
cl mqtt.Client
|
||||
topicTx = "tinygo/tx"
|
||||
topicRx = "tinygo/rx"
|
||||
)
|
||||
|
||||
func subHandler(client mqtt.Client, msg mqtt.Message) {
|
||||
fmt.Printf("[%s] ", msg.Topic())
|
||||
fmt.Printf("%s\r\n", msg.Payload())
|
||||
}
|
||||
|
||||
func main() {
|
||||
time.Sleep(3000 * time.Millisecond)
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
// Init esp8266/esp32
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
|
||||
|
||||
println("Connecting to MQTT broker at", server)
|
||||
cl = mqtt.NewClient(opts)
|
||||
if token := cl.Connect(); token.Wait() && token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
// subscribe
|
||||
token := cl.Subscribe(topicRx, 0, subHandler)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
failMessage(token.Error().Error())
|
||||
}
|
||||
|
||||
go publishing()
|
||||
|
||||
select {}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting MQTT...")
|
||||
cl.Disconnect(100)
|
||||
|
||||
println("Done.")
|
||||
}
|
||||
|
||||
func publishing() {
|
||||
for i := 0; ; i++ {
|
||||
println("Publishing MQTT message...")
|
||||
data := []byte(fmt.Sprintf(`{"e":[{"n":"hello %d","v":101}]}`, i))
|
||||
token := cl.Publish(topicRx, 0, false, data)
|
||||
token.Wait()
|
||||
if token.Error() != nil {
|
||||
println(token.Error().Error())
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
println(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
println("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
// This is an example of using the wifinina driver to implement a NTP client.
|
||||
// It creates a UDP connection to request the current time and parse the
|
||||
// response from a NTP server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"machine"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
const ntpHost = "129.6.15.29"
|
||||
|
||||
const NTP_PACKET_SIZE = 48
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
b = make([]byte, NTP_PACKET_SIZE)
|
||||
)
|
||||
|
||||
func setup() {
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
setup()
|
||||
|
||||
waitSerial()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
// now make UDP connection
|
||||
ip := net.ParseIP(ntpHost)
|
||||
raddr := &net.UDPAddr{IP: ip, Port: 123}
|
||||
laddr := &net.UDPAddr{Port: 2390}
|
||||
conn, err := net.DialUDP("udp", laddr, raddr)
|
||||
if err != nil {
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
println(err)
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
// send data
|
||||
println("Requesting NTP time...")
|
||||
t, err := getCurrentTime(conn)
|
||||
if err != nil {
|
||||
message("Error getting current time: %v", err)
|
||||
} else {
|
||||
message("NTP time: %v", t)
|
||||
}
|
||||
runtime.AdjustTimeOffset(-1 * int64(time.Since(t)))
|
||||
for i := 0; i < 10; i++ {
|
||||
message("Current time: %v", time.Now())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func getCurrentTime(conn *net.UDPSerialConn) (time.Time, error) {
|
||||
if err := sendNTPpacket(conn); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
clearBuffer()
|
||||
for now := time.Now(); time.Since(now) < time.Second; {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
if n, err := conn.Read(b); err != nil {
|
||||
return time.Time{}, fmt.Errorf("error reading UDP packet: %w", err)
|
||||
} else if n == 0 {
|
||||
continue // no packet received yet
|
||||
} else if n != NTP_PACKET_SIZE {
|
||||
return time.Time{}, fmt.Errorf("expected NTP packet size of %d: %d", NTP_PACKET_SIZE, n)
|
||||
}
|
||||
return parseNTPpacket(), nil
|
||||
}
|
||||
return time.Time{}, errors.New("no packet received after 1 second")
|
||||
}
|
||||
|
||||
func sendNTPpacket(conn *net.UDPSerialConn) error {
|
||||
clearBuffer()
|
||||
b[0] = 0b11100011 // LI, Version, Mode
|
||||
b[1] = 0 // Stratum, or type of clock
|
||||
b[2] = 6 // Polling Interval
|
||||
b[3] = 0xEC // Peer Clock Precision
|
||||
// 8 bytes of zero for Root Delay & Root Dispersion
|
||||
b[12] = 49
|
||||
b[13] = 0x4E
|
||||
b[14] = 49
|
||||
b[15] = 52
|
||||
if _, err := conn.Write(b); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseNTPpacket() time.Time {
|
||||
// the timestamp starts at byte 40 of the received packet and is four bytes,
|
||||
// this is NTP time (seconds since Jan 1 1900):
|
||||
t := uint32(b[40])<<24 | uint32(b[41])<<16 | uint32(b[42])<<8 | uint32(b[43])
|
||||
const seventyYears = 2208988800
|
||||
return time.Unix(int64(t-seventyYears), 0)
|
||||
}
|
||||
|
||||
func clearBuffer() {
|
||||
for i := range b {
|
||||
b[i] = 0
|
||||
}
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
func message(format string, args ...interface{}) {
|
||||
println(fmt.Sprintf(format, args...), "\r")
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//go:build nano_rp2040
|
||||
|
||||
// This examples shows how to control RGB LED connected to
|
||||
// NINA-W102 chip on Arduino Nano RP2040 Connect board
|
||||
// Built-in LED code added for API comparison
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
const (
|
||||
LED = machine.LED
|
||||
|
||||
// Arduino Nano RP2040 Connect board RGB LED pins
|
||||
// See https://docs.arduino.cc/static/3525d638b5c76a2d19588d6b41cd02a0/ABX00053-full-pinout.pdf
|
||||
LED_R wifinina.Pin = 27
|
||||
LED_G wifinina.Pin = 25
|
||||
LED_B wifinina.Pin = 26
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano-RP2040 Connect
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
device *wifinina.Device
|
||||
)
|
||||
|
||||
func setup() {
|
||||
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
device = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
device.Configure()
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
LED.Configure(machine.PinConfig{Mode: machine.PinOutput})
|
||||
LED_R.Configure(wifinina.PinConfig{Mode: wifinina.PinOutput})
|
||||
LED_G.Configure(wifinina.PinConfig{Mode: wifinina.PinOutput})
|
||||
LED_B.Configure(wifinina.PinConfig{Mode: wifinina.PinOutput})
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
setup()
|
||||
|
||||
LED.Low() // OFF
|
||||
LED_R.High() // OFF
|
||||
LED_G.High() // OFF
|
||||
LED_B.High() // OFF
|
||||
|
||||
go func() {
|
||||
for {
|
||||
LED.Low()
|
||||
time.Sleep(time.Second)
|
||||
LED.High()
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
LED_R.Low() // ON
|
||||
time.Sleep(time.Second)
|
||||
LED_R.High() // OFF
|
||||
LED_G.Low() // ON
|
||||
time.Sleep(time.Second)
|
||||
LED_G.High() // OFF
|
||||
LED_B.Low() // ON
|
||||
time.Sleep(time.Second)
|
||||
LED_B.High() // OFF
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
// This example opens a TCP connection using a device with WiFiNINA firmware
|
||||
// and sends some data, for the purpose of testing speed and connectivity.
|
||||
//
|
||||
// You can open a server to accept connections from this program using:
|
||||
//
|
||||
// nc -w 5 -lk 8080
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
const serverIP = ""
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
var buf = &bytes.Buffer{}
|
||||
|
||||
func main() {
|
||||
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
for {
|
||||
sendBatch()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
println("Done.")
|
||||
}
|
||||
|
||||
func sendBatch() {
|
||||
|
||||
// make TCP connection
|
||||
ip := net.ParseIP(serverIP)
|
||||
raddr := &net.TCPAddr{IP: ip, Port: 8080}
|
||||
laddr := &net.TCPAddr{Port: 8080}
|
||||
|
||||
message("---------------\r\nDialing TCP connection")
|
||||
conn, err := net.DialTCP("tcp", laddr, raddr)
|
||||
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
|
||||
message(err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
|
||||
n := 0
|
||||
w := 0
|
||||
start := time.Now()
|
||||
|
||||
// send data
|
||||
message("Sending data")
|
||||
|
||||
for i := 0; i < 1000; i++ {
|
||||
buf.Reset()
|
||||
fmt.Fprint(buf,
|
||||
"\r---------------------------- i == ", i, " ----------------------------"+
|
||||
"\r---------------------------- i == ", i, " ----------------------------")
|
||||
if w, err = conn.Write(buf.Bytes()); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
continue
|
||||
}
|
||||
n += w
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
ms := time.Now().Sub(start).Milliseconds()
|
||||
fmt.Fprint(buf, "\nWrote ", n, " bytes in ", ms, " ms\r\n")
|
||||
message(buf.String())
|
||||
|
||||
if _, err := conn.Write(buf.Bytes()); err != nil {
|
||||
println("error:", err.Error(), "\r")
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting TCP...")
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
// This example opens a TCP connection using a device with WiFiNINA firmware
|
||||
// and sends a HTTPS request to retrieve a webpage
|
||||
//
|
||||
// You shall see "strict-transport-security" header in the response,
|
||||
// this confirms communication is indeed over HTTPS
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"machine"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/net/tls"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
const server = "tinygo.org"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
var buf [256]byte
|
||||
|
||||
var lastRequestTime time.Time
|
||||
var conn net.Conn
|
||||
|
||||
func setup() {
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
setup()
|
||||
|
||||
waitSerial()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
for {
|
||||
readConnection()
|
||||
if time.Now().Sub(lastRequestTime).Milliseconds() >= 10000 {
|
||||
makeHTTPSRequest()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func readConnection() {
|
||||
if conn != nil {
|
||||
for n, err := conn.Read(buf[:]); n > 0; n, err = conn.Read(buf[:]) {
|
||||
if err != nil {
|
||||
println("Read error: " + err.Error())
|
||||
} else {
|
||||
print(string(buf[0:n]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeHTTPSRequest() {
|
||||
|
||||
var err error
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
message("\r\n---------------\r\nDialing TCP connection")
|
||||
conn, err = tls.Dial("tcp", server, nil)
|
||||
for ; err != nil; conn, err = tls.Dial("tcp", server, nil) {
|
||||
message("Connection failed: " + err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
println("Connected!\r")
|
||||
|
||||
print("Sending HTTPS request...")
|
||||
fmt.Fprintln(conn, "GET / HTTP/1.1")
|
||||
fmt.Fprintln(conn, "Host:", strings.Split(server, ":")[0])
|
||||
fmt.Fprintln(conn, "User-Agent: TinyGo")
|
||||
fmt.Fprintln(conn, "Connection: close")
|
||||
fmt.Fprintln(conn)
|
||||
println("Sent!\r\n\r")
|
||||
|
||||
lastRequestTime = time.Now()
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
// This is a sensor station that uses a ESP32 running nina-fw over SPI.
|
||||
// It creates a UDP connection you can use to get info to/from your computer via the microcontroller.
|
||||
//
|
||||
// In other words:
|
||||
// Your computer <--> UART0 <--> MCU <--> SPI <--> ESP32
|
||||
package main
|
||||
|
||||
import (
|
||||
"machine"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the server aka "hub". Replace with your own info.
|
||||
const hubIP = ""
|
||||
|
||||
var (
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
// Init esp8266/esp32
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
machine.NINA_SPI.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
adaptor = wifinina.New(machine.NINA_SPI,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
|
||||
// connect to access point
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
// now make UDP connection
|
||||
ip := net.ParseIP(hubIP)
|
||||
raddr := &net.UDPAddr{IP: ip, Port: 2222}
|
||||
laddr := &net.UDPAddr{Port: 2222}
|
||||
|
||||
println("Dialing UDP connection...")
|
||||
conn, err := net.DialUDP("udp", laddr, raddr)
|
||||
if err != nil {
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
for {
|
||||
// send data
|
||||
println("Sending data...")
|
||||
for i := 0; i < 25; i++ {
|
||||
conn.Write([]byte("hello " + strconv.Itoa(i) + "\r\n"))
|
||||
}
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Right now this code is never reached. Need a way to trigger it...
|
||||
println("Disconnecting UDP...")
|
||||
conn.Close()
|
||||
println("Done.")
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
// This example opens a TCP connection using a device with WiFiNINA firmware
|
||||
// and sends a HTTP request to retrieve a webpage, based on the following
|
||||
// Arduino example:
|
||||
//
|
||||
// https://github.com/arduino-libraries/WiFiNINA/blob/master/examples/WiFiWebClientRepeating/
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"machine"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers/net"
|
||||
"tinygo.org/x/drivers/wifinina"
|
||||
)
|
||||
|
||||
var (
|
||||
// access point info
|
||||
ssid string
|
||||
pass string
|
||||
)
|
||||
|
||||
// IP address of the "example.com" server. Replace with your own info.
|
||||
const server = "93.184.216.34"
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
// change these to connect to a different UART or pins for the ESP8266/ESP32
|
||||
var (
|
||||
|
||||
// these are the default pins for the Arduino Nano33 IoT.
|
||||
spi = machine.NINA_SPI
|
||||
|
||||
// this is the ESP chip that has the WIFININA firmware flashed on it
|
||||
adaptor *wifinina.Device
|
||||
)
|
||||
|
||||
var buf [256]byte
|
||||
|
||||
var lastRequestTime time.Time
|
||||
var conn net.Conn
|
||||
|
||||
func setup() {
|
||||
// Configure SPI for 8Mhz, Mode 0, MSB First
|
||||
spi.Configure(machine.SPIConfig{
|
||||
Frequency: 8 * 1e6,
|
||||
SDO: machine.NINA_SDO,
|
||||
SDI: machine.NINA_SDI,
|
||||
SCK: machine.NINA_SCK,
|
||||
})
|
||||
|
||||
adaptor = wifinina.New(spi,
|
||||
machine.NINA_CS,
|
||||
machine.NINA_ACK,
|
||||
machine.NINA_GPIO0,
|
||||
machine.NINA_RESETN)
|
||||
adaptor.Configure()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
setup()
|
||||
|
||||
waitSerial()
|
||||
|
||||
connectToAP()
|
||||
displayIP()
|
||||
|
||||
for {
|
||||
readConnection()
|
||||
if time.Now().Sub(lastRequestTime).Milliseconds() >= 10000 {
|
||||
makeHTTPRequest()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Wait for user to open serial console
|
||||
func waitSerial() {
|
||||
for !machine.Serial.DTR() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func readConnection() {
|
||||
if conn != nil {
|
||||
for n, err := conn.Read(buf[:]); n > 0; n, err = conn.Read(buf[:]) {
|
||||
if err != nil {
|
||||
println("Read error: " + err.Error())
|
||||
} else {
|
||||
print(string(buf[0:n]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeHTTPRequest() {
|
||||
|
||||
var err error
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
// make TCP connection
|
||||
ip := net.ParseIP(server)
|
||||
raddr := &net.TCPAddr{IP: ip, Port: 80}
|
||||
laddr := &net.TCPAddr{Port: 8080}
|
||||
|
||||
message("\r\n---------------\r\nDialing TCP connection")
|
||||
conn, err = net.DialTCP("tcp", laddr, raddr)
|
||||
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
|
||||
message("Connection failed: " + err.Error())
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
println("Connected!\r")
|
||||
|
||||
print("Sending HTTP request...")
|
||||
fmt.Fprintln(conn, "GET / HTTP/1.1")
|
||||
fmt.Fprintln(conn, "Host:", server)
|
||||
fmt.Fprintln(conn, "User-Agent: TinyGo")
|
||||
fmt.Fprintln(conn, "Connection: close")
|
||||
fmt.Fprintln(conn)
|
||||
println("Sent!\r\n\r")
|
||||
|
||||
lastRequestTime = time.Now()
|
||||
}
|
||||
|
||||
const retriesBeforeFailure = 3
|
||||
|
||||
// connect to access point
|
||||
func connectToAP() {
|
||||
time.Sleep(2 * time.Second)
|
||||
var err error
|
||||
for i := 0; i < retriesBeforeFailure; i++ {
|
||||
println("Connecting to " + ssid)
|
||||
err = adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
|
||||
if err == nil {
|
||||
println("Connected.")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// error connecting to AP
|
||||
failMessage(err.Error())
|
||||
}
|
||||
|
||||
func displayIP() {
|
||||
ip, _, _, err := adaptor.GetIP()
|
||||
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
|
||||
message(err.Error())
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
message("IP address: " + ip.String())
|
||||
}
|
||||
|
||||
func message(msg string) {
|
||||
println(msg, "\r")
|
||||
}
|
||||
|
||||
func failMessage(msg string) {
|
||||
for {
|
||||
println(msg)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user