以下を成功したのでget ?t=21.1&h=45をmock get reqしよう
package main
import (
"machine"
"time"
)
var uart = machine.UART0
var buf = make([]byte, 256)
// --------------------
// コマンド送信
// --------------------
func send(cmd string) {
for i := 0; i < len(cmd); i++ {
uart.WriteByte(cmd[i])
}
uart.WriteByte('\r')
uart.WriteByte('\n')
}
// --------------------
// 応答待ち
// --------------------
func waitFor(expected string, timeout time.Duration) bool {
start := time.Now()
data := ""
for time.Since(start) < timeout {
n, _ := uart.Read(buf)
if n > 0 {
part := string(buf[:n])
print(part)
data += part
if contains(data, expected) {
return true
}
if contains(data, "ERROR") {
return false
}
}
}
return false
}
// --------------------
// 文字列検索
// --------------------
func contains(s, sub string) bool {
for i := 0; i <= len(s)-len(sub); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
func main() {
// ★ ESP-01はまず115200か9600を試す
uart.Configure(machine.UARTConfig{
BaudRate: 115200, // ← 合わなければ115200に変更
TX: machine.GPIO0,
RX: machine.GPIO1,
})
time.Sleep(5 * time.Second)
// --------------------
// AT確認
// --------------------
send("AT")
if !waitFor("OK", 3*time.Second) {
println("AT failed")
return
}
// --------------------
// リセット
// --------------------
send("AT+RST")
time.Sleep(5 * time.Second)
// 再確認
send("AT")
if !waitFor("OK", 3*time.Second) {
println("AT after reset failed")
return
}
// --------------------
// ステーションモード
// --------------------
send("AT+CWMODE=1")
if !waitFor("OK", 3*time.Second) {
println("CWMODE failed")
return
}
// --------------------
// WiFi接続
// --------------------
send(`AT+CWJAP="Buffalo-2G-8340","636nsa535ds3v"`)
// ★ busy p... の後に OK が出れば成功
if !waitFor("OK", 30*time.Second) {
println("WiFi connect failed")
return
}
println("\nWiFi Connected!")
for {
time.Sleep(10 * time.Second)
}
}