rtl8720dn: add support for rtl8720dn

This commit is contained in:
sago35
2021-06-27 14:28:54 +09:00
committed by Ron Evans
parent b53a8a17e7
commit 0bc3702dd0
19 changed files with 10731 additions and 2 deletions
+3 -1
View File
@@ -197,12 +197,14 @@ endif
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m4 ./examples/sdcard/tinyfs/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=wioterminal ./examples/rtl8720dn/webclient/
@md5sum ./build/test.hex
DRIVERS = $(wildcard */)
NOTESTS = build examples flash semihosting pcd8544 shiftregister st7789 microphone mcp3008 gps microbitmatrix \
hcsr04 ssd1331 ws2812 thermistor apa102 easystepper ssd1351 ili9341 wifinina shifter hub75 \
hd44780 buzzer ssd1306 espat l9110x st7735 bmi160 l293x dht keypad4x4 max72xx p1am tone tm1637 \
pcf8563 mcp2515 servo sdcard
pcf8563 mcp2515 servo sdcard rtl8720dn
TESTS = $(filter-out $(addsuffix /%,$(NOTESTS)),$(DRIVERS))
unit-test:
+2 -1
View File
@@ -52,7 +52,7 @@ func main() {
## Currently supported devices
The following 66 devices are supported.
The following 67 devices are supported.
| Device Name | Interface Type |
|----------|-------------|
@@ -100,6 +100,7 @@ The following 66 devices are supported.
| [PCD8544 display](http://eia.udg.edu/~forest/PCD8544_1.pdf) | SPI |
| [PCF8563 real time clock](https://www.nxp.com/docs/en/data-sheet/PCF8563.pdf) | I2C |
| [Resistive Touchscreen (4-wire)](http://ww1.microchip.com/downloads/en/Appnotes/doc8091.pdf) | GPIO |
| [RTL8720DN 2.4G/5G Dual Bands Wireless and BLE5.0](https://www.seeedstudio.com/Realtek8720DN-2-4G-5G-Dual-Bands-Wireless-and-BLE5-0-Combo-Module-p-4442.html) | UART |
| [Semihosting](https://wiki.segger.com/Semihosting) | Debug |
| [Servo](https://learn.sparkfun.com/tutorials/hobby-servo-tutorial/all) | PWM |
| [Shift register (PISO)](https://en.wikipedia.org/wiki/Shift_register#Parallel-in_serial-out_\(PISO\)) | GPIO |
+141
View File
@@ -0,0 +1,141 @@
package main
import (
"fmt"
"strings"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/tls"
"tinygo.org/x/drivers/rtl8720dn"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = true
// server = "tinygo.org"
// test_root_ca = "..."
// }
var (
ssid string
password string
server string = "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 [0x400]byte
var lastRequestTime time.Time
var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
rtl.SetRootCA(&test_root_ca)
net.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.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)
cnt := 0
for {
readConnection()
if time.Now().Sub(lastRequestTime).Milliseconds() >= 10000 {
makeHTTPSRequest()
cnt++
fmt.Printf("-------- %d --------\r\n", cnt)
}
}
}
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()
}
func message(msg string) {
println(msg, "\r")
}
@@ -0,0 +1,71 @@
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
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)
waitSerial()
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
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
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)
}
@@ -0,0 +1,143 @@
package main
import (
"fmt"
"image/color"
"time"
"tinygo.org/x/drivers/net"
"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.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = true
// server = "tinygo.org"
// }
var (
ssid string
password string
server string = "tinygo.org"
debug = false
)
var (
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
var lastRequestTime time.Time
var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
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")
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
fmt.Fprintf(terminal, "ConnectToAP()\r\n")
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
fmt.Fprintf(terminal, "connected\r\n\r\n")
ip, subnet, gateway, err := rtl.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)
cnt := 0
for {
readConnection()
if time.Now().Sub(lastRequestTime).Milliseconds() >= 10000 {
makeHTTPRequest()
cnt++
fmt.Fprintf(terminal, "-------- %d --------\r\n", cnt)
}
}
}
func readConnection() {
if conn != nil {
for n, err := conn.Read(buf[:]); n > 0; n, err = conn.Read(buf[:]) {
if err != nil {
fmt.Fprintf(terminal, "Read error: "+err.Error()+"\r\n")
} else {
fmt.Fprintf(terminal, 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)
}
fmt.Fprintf(terminal, "Connected!\r\n")
fmt.Fprintf(terminal, "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)
fmt.Fprintf(terminal, "Sent!\r\n\r\n")
lastRequestTime = time.Now()
}
func message(msg string) {
fmt.Fprintf(terminal, "%s\r\n", msg)
}
@@ -0,0 +1,97 @@
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/ili9341"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
var (
display = ili9341.NewSPI(
machine.SPI3,
machine.LCD_DC,
machine.LCD_SS_PIN,
machine.LCD_RESET,
)
backlight = machine.LCD_BACKLIGHT
)
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})
}
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)
if debug {
waitSerial()
}
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
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
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)
}
+116
View File
@@ -0,0 +1,116 @@
package main
import (
"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"
// password = "your-password"
// debug = true
// server = "tinygo.org"
// }
var (
ssid string
password string
server string = "tinygo.org"
debug = false
)
var buf [0x400]byte
var lastRequestTime time.Time
var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.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)
cnt := 0
for {
readConnection()
if time.Now().Sub(lastRequestTime).Milliseconds() >= 10000 {
makeHTTPRequest()
cnt++
fmt.Printf("-------- %d --------\r\n", cnt)
}
}
}
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()
}
func message(msg string) {
println(msg, "\r")
}
@@ -0,0 +1,71 @@
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
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)
waitSerial()
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
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
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)
}
+2
View File
@@ -6,4 +6,6 @@ require (
github.com/eclipse/paho.mqtt.golang v1.2.0
github.com/frankban/quicktest v1.10.2
github.com/tinygo-org/tinyfs v0.0.0-20210620184125-5b00ebcf68bb
tinygo.org/x/tinyfont v0.2.1 // indirect
tinygo.org/x/tinyterm v0.1.0 // indirect
)
+8
View File
@@ -1,3 +1,4 @@
github.com/bgould/http v0.0.0-20190627042742-d268792bdee7/go.mod h1:BTqvVegvwifopl4KTEDth6Zezs9eR+lCWhvGKvkxJHE=
github.com/eclipse/paho.mqtt.golang v1.2.0 h1:1F8mhG9+aO5/xpdtFkW4SxOJB67ukuDC3t2y2qayIX0=
github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts=
github.com/frankban/quicktest v1.10.2 h1:19ARM85nVi4xH7xPXuc5eM/udya5ieh7b/Sv+d844Tk=
@@ -15,6 +16,13 @@ github.com/tinygo-org/tinyfs v0.0.0-20210514090915-924e60a7bcf8 h1:pYwuKe1XuNeJn
github.com/tinygo-org/tinyfs v0.0.0-20210514090915-924e60a7bcf8/go.mod h1:HGuyo42bGd1zWSuS1gwgyyjN36ZZMlEpwM0vSrglmXc=
github.com/tinygo-org/tinyfs v0.0.0-20210620184125-5b00ebcf68bb h1:lgwaY6CLUvZoH4DMwHn3vKjYRx6npRX1FwjWuJEpZao=
github.com/tinygo-org/tinyfs v0.0.0-20210620184125-5b00ebcf68bb/go.mod h1:HGuyo42bGd1zWSuS1gwgyyjN36ZZMlEpwM0vSrglmXc=
github.com/valyala/fastjson v1.6.3/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
tinygo.org/x/drivers v0.14.0/go.mod h1:uT2svMq3EpBZpKkGO+NQHjxjGf1f42ra4OnMMwQL2aI=
tinygo.org/x/drivers v0.15.1/go.mod h1:uT2svMq3EpBZpKkGO+NQHjxjGf1f42ra4OnMMwQL2aI=
tinygo.org/x/drivers v0.16.0/go.mod h1:uT2svMq3EpBZpKkGO+NQHjxjGf1f42ra4OnMMwQL2aI=
tinygo.org/x/tinyfont v0.2.1 h1:FAaemBzw8wsfhAtG6fWW+QjyWw/K8YqEeiWo4N1pv4o=
tinygo.org/x/tinyfont v0.2.1/go.mod h1:eLqnYSrFRjt5STxWaMeOWJTzrKhXqpWw7nU3bPfKOAM=
tinygo.org/x/tinyterm v0.1.0 h1:80i+j+KWoxCFa/Xfp6pWbh79x+8zUdMXC1vaKj2QhkY=
tinygo.org/x/tinyterm v0.1.0/go.mod h1:/DDhNnGwNF2/tNgHywvyZuCGnbH3ov49Z/6e8LPLRR4=
+21
View File
@@ -0,0 +1,21 @@
# RTL8720DN Driver
This package provides a driver to use a separate connected WiFi processor `RTL8720DN` for TCP/UDP communication.
At this time, only part of TCP is supported.
## Using th RTL8720DN Driver
For now, it is only available for the `RTL8720DN` on `Wio Terminal`.
You can try the following command.
```
$ tinygo flash --target wioterminal --size short ./examples/rtl8720dn/webclient/
$ tinygo flash --target wioterminal --size short ./examples/rtl8720dn/tlsclient/
```
## RTL8720DN Firmware
Follow the steps below to update.
The firmware must be version 2.1.2 or later.
https://wiki.seeedstudio.com/Wio-Terminal-Network-Overview/
+35
View File
@@ -0,0 +1,35 @@
package rtl8720dn
// https://github.com/EmbeddedRPC/erpc/blob/develop/erpc_python/erpc/crc16.py
const (
crcStart = 0xEF4A
)
var table = [256]uint16{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,
}
func computeCRC16(data []byte) uint16 {
crc := uint16(crcStart)
for _, d := range data {
crc = ((crc << 8) ^ table[((crc>>8)^uint16(d))&0xFF]) & 0xFFFF
}
return crc
}
+278
View File
@@ -0,0 +1,278 @@
package rtl8720dn
import (
"fmt"
"strconv"
)
// Here is the implementation of tinygo-org/x/drivers/net.DeviceDriver.
func (r *RTL8720DN) GetDNS(domain string) (string, error) {
if r.debug {
fmt.Printf("GetDNS(%q)\r\n", domain)
}
ipaddr := [4]byte{}
_, err := r.Rpc_netconn_gethostbyname(domain, ipaddr[:])
if err != nil {
return "", err
}
ret, err := fmt.Sprintf("%d.%d.%d.%d", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]), nil
if r.debug {
fmt.Printf("-> %s\r\n", ret)
fmt.Printf("-> %02X.%02X.%02X.%02X\r\n", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3])
}
return ret, err
}
func (r *RTL8720DN) ConnectTCPSocket(addr, port string) error {
if r.debug {
fmt.Printf("ConnectTCPSocket(%q, %q)\r\n", addr, port)
}
ipaddr := [4]byte{}
_, err := r.Rpc_netconn_gethostbyname(addr, ipaddr[:])
if err != nil {
return err
}
portNum, err := strconv.ParseUint(port, 0, 0)
if err != nil {
return err
}
socket, err := r.Rpc_lwip_socket(0x02, 0x01, 0x00)
if err != nil {
return err
}
r.socket = socket
r.connectionType = ConnectionTypeTCP
_, err = r.Rpc_lwip_fcntl(socket, 0x00000003, 0x00000000)
if err != nil {
return err
}
_, err = r.Rpc_lwip_fcntl(socket, 0x00000004, 0x00000001)
if err != nil {
return err
}
name := []byte{0x00, 0x02, 0x00, 0x50, 0xC0, 0xA8, 0x01, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
name[2] = byte(portNum >> 8)
name[3] = byte(portNum)
name[4] = byte(ipaddr[0])
name[5] = byte(ipaddr[1])
name[6] = byte(ipaddr[2])
name[7] = byte(ipaddr[3])
_, err = r.Rpc_lwip_connect(socket, name, uint32(len(name)))
if err != nil {
return err
}
readset := []byte{}
writeset := []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
exceptset := []byte{}
timeout := []byte{}
_, err = r.Rpc_lwip_select(0x01, readset, writeset, exceptset, timeout)
if err != nil {
return err
}
optlen := uint32(4)
_, err = r.Rpc_lwip_getsockopt(socket, 0x00000FFF, 0x00001007, []byte{0xA5, 0xA5, 0xA5, 0xA5}, nil, optlen)
if err != nil {
return err
}
_, err = r.Rpc_lwip_fcntl(socket, 0x00000003, 0x00000000)
if err != nil {
return err
}
_, err = r.Rpc_lwip_fcntl(socket, 0x00000004, 0x00000000)
if err != nil {
return err
}
readset = []byte{}
writeset = []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
exceptset = []byte{}
timeout = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0F, 0x00, 0xFF, 0xFF, 0xFF, 0xFF}
_, err = r.Rpc_lwip_select(0x01, readset, writeset, exceptset, timeout)
if err != nil {
return err
}
return nil
}
func (r *RTL8720DN) ConnectSSLSocket(addr, port string) error {
if r.debug {
fmt.Printf("ConnectSSLSocket(%q, %q)\r\n", addr, port)
}
client, err := r.Rpc_wifi_ssl_client_create()
if err != nil {
return err
}
r.client = client
r.connectionType = ConnectionTypeTLS
err = r.Rpc_wifi_ssl_init(client)
if err != nil {
return err
}
err = r.Rpc_wifi_ssl_set_timeout(client, 0x0001D4C0)
if err != nil {
return err
}
_, err = r.Rpc_wifi_ssl_set_rootCA(client, *r.root_ca)
if err != nil {
return err
}
// TODO: use port
_, err = r.Rpc_wifi_start_ssl_client(client, addr, 443, 0x0001D4C0)
if err != nil {
return err
}
_, err = r.Rpc_wifi_ssl_get_socket(client)
if err != nil {
return err
}
return nil
}
func (r *RTL8720DN) ConnectUDPSocket(addr, sendport, listenport string) error {
if r.debug {
fmt.Printf("ConnectUDPSocket(%q, %q, %q)\r\n", addr, sendport, listenport)
}
fmt.Printf("not implemented yet\r\n")
return nil
}
func (r *RTL8720DN) DisconnectSocket() error {
if r.debug {
fmt.Printf("DisconnectSocket()\r\n")
}
switch r.connectionType {
case ConnectionTypeTCP:
_, err := r.Rpc_lwip_close(r.socket)
if err != nil {
return err
}
case ConnectionTypeTLS:
err := r.Rpc_wifi_stop_ssl_socket(r.client)
if err != nil {
return err
}
err = r.Rpc_wifi_ssl_client_destroy(r.client)
if err != nil {
return err
}
default:
}
r.connectionType = ConnectionTypeNone
return nil
}
func (r *RTL8720DN) StartSocketSend(size int) error {
if r.debug {
fmt.Printf("StartSocketSend(%d)\r\n", size)
}
// No implementation required
return nil
}
func (r *RTL8720DN) Write(b []byte) (n int, err error) {
if r.debug {
fmt.Printf("Write(%#v)\r\n", b)
}
switch r.connectionType {
case ConnectionTypeTCP:
sn, err := r.Rpc_lwip_send(r.socket, b, 0x00000008)
if err != nil {
return 0, err
}
n = int(sn)
case ConnectionTypeTLS:
sn, err := r.Rpc_wifi_send_ssl_data(r.client, b, uint16(len(b)))
if err != nil {
return 0, err
}
n = int(sn)
default:
return 0, nil
}
return n, nil
}
func (r *RTL8720DN) ReadSocket(b []byte) (n int, err error) {
if r.debug {
//fmt.Printf("ReadSocket(b)\r\n")
}
if r.connectionType == ConnectionTypeNone {
return 0, nil
}
switch r.connectionType {
case ConnectionTypeTCP:
nn, err := r.Rpc_lwip_recv(r.socket, b, uint32(len(b)), 0x00000008, 0x00002800)
if err != nil {
return 0, err
}
if nn == -1 {
return 0, nil
} else if nn == 0 {
return 0, r.DisconnectSocket()
}
if r.length == 0 {
header := httpHeader(b[:nn])
r.length = header.ContentLength()
}
r.length -= int(nn)
if r.length == 0 {
return int(nn), r.DisconnectSocket()
}
n = int(nn)
case ConnectionTypeTLS:
nn, err := r.Rpc_wifi_get_ssl_receive(r.client, b, int32(len(b)))
if err != nil {
return 0, err
}
if nn < 0 {
return 0, fmt.Errorf("error %d", n)
} else if nn == 0 || nn == -30848 {
return 0, r.DisconnectSocket()
}
n = int(nn)
default:
}
return n, nil
}
func (r *RTL8720DN) IsSocketDataAvailable() bool {
if r.debug {
fmt.Printf("IsSocketDataAvailable()\r\n")
}
fmt.Printf("not implemented yet\r\n")
return true
}
func (r *RTL8720DN) Response(timeout int) ([]byte, error) {
if r.debug {
fmt.Printf("Response(%d))\r\n", timeout)
}
// No implementation required
return nil, nil
}
+9422
View File
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
package rtl8720dn
import (
"fmt"
"io"
"time"
)
var (
headerBuf [4]byte
readBuf [4]byte
startWriteMessageBuf [1024]byte
payload [1024 + 256]byte
)
const (
xVersion = 1
)
func startWriteMessage(msgType, service, requestNumber, sequence uint32) []byte {
startWriteMessageBuf[0] = byte(msgType)
startWriteMessageBuf[1] = byte(requestNumber)
startWriteMessageBuf[2] = byte(service)
startWriteMessageBuf[3] = byte(xVersion)
startWriteMessageBuf[4] = byte(sequence)
startWriteMessageBuf[5] = byte(sequence >> 8)
startWriteMessageBuf[6] = byte(sequence >> 16)
startWriteMessageBuf[7] = byte(sequence >> 24)
return startWriteMessageBuf[:8]
}
func (r *RTL8720DN) performRequest(msg []byte) error {
crc := computeCRC16(msg)
headerBuf[0] = byte(len(msg))
headerBuf[1] = byte(len(msg) >> 8)
headerBuf[2] = byte(crc)
headerBuf[3] = byte(crc >> 8)
if r.debug {
fmt.Printf("tx : %2d : ", len(headerBuf))
dumpHex(headerBuf[:])
fmt.Printf("\r\n")
}
r.port.Write(headerBuf[:])
if r.debug {
fmt.Printf("tx : %2d : ", len(msg))
dumpHex(msg)
fmt.Printf("\r\n")
}
r.port.Write(msg)
return nil
}
func dumpHex(b []byte) {
for i := range b {
if i == 0 {
fmt.Printf("%02X", b[i])
} else {
fmt.Printf(" %02X", b[i])
}
}
}
func (r *RTL8720DN) readThread() {
for {
n, _ := io.ReadFull(r.port, readBuf[:4])
if n == 0 {
continue
}
if r.debug {
fmt.Printf("rx : %2d : ", n)
dumpHex(readBuf[:n])
fmt.Printf("\r\n")
}
length := uint16(readBuf[0]) + uint16(readBuf[1])<<8
crc := uint16(readBuf[2]) + uint16(readBuf[3])<<8
//fmt.Printf("len %d (%X) crc %04X\r\n", length, length, crc)
n, _ = io.ReadFull(r.port, payload[:length])
if r.debug {
fmt.Printf("rx : %2d : ", length)
dumpHex(payload[0:n])
fmt.Printf("\r\n")
}
n = int(length)
//fmt.Printf("rx : %2d : %s\n", n, dumpHex(payload[:n]))
crcNew := computeCRC16(payload[:n])
if g, e := crcNew, crc; g != e {
fmt.Printf("err CRC16: got %04X want %04X\n", g, e)
}
if payload[0] == 0x02 || payload[0] == 0x00 {
r.received <- true
// switch goroutine
time.Sleep(1)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
package rtl8720dn
import "io"
type RTL8720DN struct {
port io.ReadWriter
seq uint64
received chan bool
debug bool
connectionType ConnectionType
socket int32
client uint32
length int
root_ca *string
}
type ConnectionType int
const (
ConnectionTypeNone ConnectionType = iota
ConnectionTypeTCP
ConnectionTypeUDP
ConnectionTypeTLS
)
func New(r io.ReadWriter) *RTL8720DN {
ret := &RTL8720DN{
port: r,
seq: 1,
received: make(chan bool, 1),
debug: false,
}
go ret.readThread()
return ret
}
func (r *RTL8720DN) SetSeq(s uint64) {
r.seq = s
}
func (r *RTL8720DN) Debug(b bool) {
r.debug = b
}
func (r *RTL8720DN) SetRootCA(s *string) {
r.root_ca = s
}
func (r *RTL8720DN) Version() (string, error) {
return r.Rpc_system_version()
}
+37
View File
@@ -0,0 +1,37 @@
package rtl8720dn
// TODO: 後で整理する
// https://github.com/Seeed-Studio/seeed-ambd-firmware/blob/master/erpc_idl/erpc_shim/rpc_system_header.h
type RPC_T_GAP_CAUSE int32
type RPC_T_LE_KEY_ENTRY int32
type RPC_T_APP_RESULT int32
type RPC_T_GAP_PARAM_TYPE int32
type RPC_T_LE_BOND_PARAM_TYPE int32
type RPC_T_GAP_CFM_CAUSE int32
type RPC_T_GAP_REMOTE_ADDR_TYPE int32
type RPC_T_GAP_SEC_LEVEL int32
type RPC_T_GAP_LE_PARAM_TYPE int32
type RPC_T_GAP_WHITE_LIST_OP int32
type RPC_T_GAP_RAND_ADDR_TYPE int32
type RPC_T_GAP_IDENT_ADDR_TYPE int32
type RPC_T_GAP_CONFIG_GATT_CCCD_NOT_CHECK int32
type RPC_T_LE_ADV_PARAM_TYPE int32
type RPC_T_LE_SCAN_PARAM_TYPE int32
type RPC_T_LE_CONN_PARAM_TYPE int32
type RPC_T_GAP_CONN_INFO int32
type RPC_T_GAP_PHYS_OPTIONS int32
type RPC_T_GAP_CONN_PARAM_TYPE int32
type RPC_T_GAP_LE_CONN_REQ_PARAM int32
type RPC_T_GAP_LOCAL_ADDR_TYPE int32
type RPC_T_LOCAL_NAME int32
type RPC_T_LOCAL_APPEARANCE int32
type RPC_T_LE_CCCD int32
type RPC_T_LE_KEY_TYPE int32
type RPC_T_GATT_WRITE_TYPE int32
type RPC_T_GATT_PDU_TYPE int32
type RPC_T_SERVICE_CALLBACK_TYPE int32
+51
View File
@@ -0,0 +1,51 @@
package rtl8720dn
import (
"bytes"
"encoding/binary"
"fmt"
"strconv"
"strings"
)
type httpHeader []byte
func (h httpHeader) ContentLength() int {
contentLength := -1
idx := bytes.Index(h, []byte("Content-Length: "))
if 0 <= idx {
_, err := fmt.Sscanf(string(h[idx+16:]), "%d", &contentLength)
if err != nil {
return -1
}
}
return contentLength
}
// TODO: IPAddress implementation should be moved under drivers/net
// The same implementation exists in wifinina.
type IPAddress []byte
func (addr IPAddress) String() string {
if len(addr) < 4 {
return ""
}
return strconv.Itoa(int(addr[0])) + "." + strconv.Itoa(int(addr[1])) + "." + strconv.Itoa(int(addr[2])) + "." + strconv.Itoa(int(addr[3]))
}
func ParseIPv4(s string) (IPAddress, error) {
v := strings.Split(s, ".")
v0, _ := strconv.Atoi(v[0])
v1, _ := strconv.Atoi(v[1])
v2, _ := strconv.Atoi(v[2])
v3, _ := strconv.Atoi(v[3])
return IPAddress([]byte{byte(v0), byte(v1), byte(v2), byte(v3)}), nil
}
func (addr IPAddress) AsUint32() uint32 {
if len(addr) < 4 {
return 0
}
b := []byte(string(addr))
return binary.BigEndian.Uint32(b[0:4])
}
+72
View File
@@ -0,0 +1,72 @@
package rtl8720dn
import (
"fmt"
"time"
)
func (r *RTL8720DN) ConnectToAP(ssid string, password string) error {
if len(ssid) == 0 || len(password) == 0 {
return fmt.Errorf("connection failed: either ssid or password not set")
}
_, err := r.Rpc_wifi_off()
if err != nil {
return err
}
_, err = r.Rpc_wifi_on(0x00000001)
if err != nil {
return err
}
_, err = r.Rpc_wifi_disconnect()
if err != nil {
return err
}
numTry := 5
securityType := uint32(0x00400004)
for i := 0; i < numTry; i++ {
ret, err := r.Rpc_wifi_connect(ssid, password, securityType, -1, 0)
if err != nil {
return err
}
if ret != 0 {
if i == numTry-1 {
return fmt.Errorf("connection failed: rpc_wifi_connect failed")
}
time.Sleep(100 * time.Millisecond)
} else {
break
}
}
_, err = r.Rpc_tcpip_adapter_dhcpc_start(0)
if err != nil {
return err
}
for i := 0; i < 3; i++ {
_, err = r.Rpc_wifi_is_connected_to_ap()
if err != nil {
return err
}
time.Sleep(1 * time.Second)
}
return nil
}
func (r *RTL8720DN) GetIP() (ip, subnet, gateway IPAddress, err error) {
ip_info := make([]byte, 12)
_, err = r.Rpc_tcpip_adapter_get_ip_info(0, ip_info)
if err != nil {
return nil, nil, nil, err
}
ip = IPAddress(ip_info[0:4])
subnet = IPAddress(ip_info[4:8])
gateway = IPAddress(ip_info[8:12])
return ip, subnet, gateway, nil
}