Compare commits

..

1 Commits

Author SHA1 Message Date
sago35 592f66e1ca rtl8720dn: add Rpc_tcpip_adapter_init_with_timeout() 2022-08-01 17:37:15 +09:00
140 changed files with 1373 additions and 2281 deletions
-65
View File
@@ -1,68 +1,3 @@
0.23.0
---
- **new devices**
- Add GC9A01 Driver (#452)
- Initial support for VL6180x sensor
- **enhancements**
- **rtl8720dn**
- refactor by bringing this driver more in line with wifinina and espat
- **ssd1306**
- add getter method to the current buffer
- **makeybutton**
- revise to better match the algorithm defined by the original
- **espat,wifinina,rtl8720dn**
- change ssid/pass from const to var
- **bugfixes**
- **microbitmatrix**
- fix inverted axis
- **espat**
- Trim quotes from IP returned by espat's GetDNS()
- **all**
- correct go fmt
- **examples**
- **rtl8720dn**
- remove wifi setting
- add call to optional debug setting
- update all remaining examples for refactored API
0.22.0
---
- **new devices**
- epd: add waveshare 2.9in (v1)
- makeybutton: add driver for MakeyMakey-like button
- **enhancements**
- **rtl8720dn**
- add UDP close function
- improve error handling
- **net/http**
- improve header parsing
- add last-will-and-testament to MQTT
- **net/mqtt**
- adds keepalive pinging, disconnect, and graceful goroutine cleanup
- support for cookies when https
- add support for retained messsages
- **bugfixes**
- irremote: Fix irremote reporting incorrect NEC addresses and command codes (#422)
- net/http: Fix http.Get() with port specification
- **build**
- Makefile recursively finds unit-tests
- switching to GHA
- **updates**
- update tinyfont to v0.3.0
- update tinyfs to v0.2.0
- **examples**
- rtl8720dn: add ./examples/rtl8720dn/version
0.21.0 0.21.0
--- ---
- **new devices** - **new devices**
-4
View File
@@ -53,8 +53,6 @@ smoke-test:
@md5sum ./build/test.hex @md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=pyportal ./examples/flash/console/qspi tinygo build -size short -o ./build/test.hex -target=pyportal ./examples/flash/console/qspi
@md5sum ./build/test.hex @md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/gc9a01/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m0 ./examples/gps/i2c/main.go tinygo build -size short -o ./build/test.hex -target=feather-m0 ./examples/gps/i2c/main.go
@md5sum ./build/test.hex @md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m0 ./examples/gps/uart/main.go tinygo build -size short -o ./build/test.hex -target=feather-m0 ./examples/gps/uart/main.go
@@ -145,8 +143,6 @@ smoke-test:
@md5sum ./build/test.hex @md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/vl53l1x/main.go tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/vl53l1x/main.go
@md5sum ./build/test.hex @md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/vl6180x/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/waveshare-epd/epd2in13/main.go tinygo build -size short -o ./build/test.hex -target=microbit ./examples/waveshare-epd/epd2in13/main.go
@md5sum ./build/test.hex @md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/waveshare-epd/epd2in13x/main.go tinygo build -size short -o ./build/test.hex -target=microbit ./examples/waveshare-epd/epd2in13x/main.go
+1 -4
View File
@@ -52,7 +52,7 @@ func main() {
## Currently supported devices ## Currently supported devices
The following 83 devices are supported. The following 81 devices are supported.
| Device Name | Interface Type | | Device Name | Interface Type |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------| |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------|
@@ -135,12 +135,9 @@ The following 83 devices are supported.
| [UC8151 All-in-one driver IC for ESL](https://www.buydisplay.com/download/ic/UC8151C.pdf) | I2C | | [UC8151 All-in-one driver IC for ESL](https://www.buydisplay.com/download/ic/UC8151C.pdf) | I2C |
| [VEML6070 UV light sensor](https://www.vishay.com/docs/84277/veml6070.pdf) | I2C | | [VEML6070 UV light sensor](https://www.vishay.com/docs/84277/veml6070.pdf) | I2C |
| [VL53L1X time-of-flight distance sensor](https://www.st.com/resource/en/datasheet/vl53l1x.pdf) | I2C | | [VL53L1X time-of-flight distance sensor](https://www.st.com/resource/en/datasheet/vl53l1x.pdf) | I2C |
| [VL6180X time-of-flight distance sensor](https://www.st.com/resource/en/datasheet/vl6180x.pdf) | I2C |
| [Waveshare 2.13" (B & C) e-paper display](https://www.waveshare.com/w/upload/d/d3/2.13inch-e-paper-b-Specification.pdf) | SPI | | [Waveshare 2.13" (B & C) e-paper display](https://www.waveshare.com/w/upload/d/d3/2.13inch-e-paper-b-Specification.pdf) | SPI |
| [Waveshare 2.13" e-paper display](https://www.waveshare.com/w/upload/e/e6/2.13inch_e-Paper_Datasheet.pdf) | SPI | | [Waveshare 2.13" e-paper display](https://www.waveshare.com/w/upload/e/e6/2.13inch_e-Paper_Datasheet.pdf) | SPI |
| [Waveshare 2.9" e-paper display (V1)](https://www.waveshare.com/w/upload/e/e6/2.9inch_e-Paper_Datasheet.pdf) | SPI |
| [Waveshare 4.2" e-paper B/W display](https://www.waveshare.com/w/upload/6/6a/4.2inch-e-paper-specification.pdf) | SPI | | [Waveshare 4.2" e-paper B/W display](https://www.waveshare.com/w/upload/6/6a/4.2inch-e-paper-specification.pdf) | SPI |
| [Waveshare GC9A01 TFT round display](https://www.waveshare.com/w/upload/5/5e/GC9A01A.pdf) | SPI |
| [WS2812 RGB LED](https://cdn-shop.adafruit.com/datasheets/WS2812.pdf) | GPIO | | [WS2812 RGB LED](https://cdn-shop.adafruit.com/datasheets/WS2812.pdf) | GPIO |
| [XPT2046 touch controller](http://grobotronics.com/images/datasheets/xpt2046-datasheet.pdf) | GPIO | | [XPT2046 touch controller](http://grobotronics.com/images/datasheets/xpt2046-datasheet.pdf) | GPIO |
| [Semtech SX126x Lora](https://www.semtech.com/products/wireless-rf/lora-transceiv-ers/sx1261) | SPI | | [Semtech SX126x Lora](https://www.semtech.com/products/wireless-rf/lora-transceiv-ers/sx1261) | SPI |
+1
View File
@@ -1,6 +1,7 @@
// Package adt7410 provides a driver for the adt7410 I2C Temperature Sensor. // Package adt7410 provides a driver for the adt7410 I2C Temperature Sensor.
// //
// Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ADT7410.pdf // Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ADT7410.pdf
//
package adt7410 // import "tinygo.org/x/drivers/adt7410" package adt7410 // import "tinygo.org/x/drivers/adt7410"
import ( import (
+1
View File
@@ -3,6 +3,7 @@
// Datasheet EN: http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf // Datasheet EN: http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf
// //
// Datasheet JP: http://www.analog.com/media/jp/technical-documentation/data-sheets/ADXL345_jp.pdf // Datasheet JP: http://www.analog.com/media/jp/technical-documentation/data-sheets/ADXL345_jp.pdf
//
package adxl345 // import "tinygo.org/x/drivers/adxl345" package adxl345 // import "tinygo.org/x/drivers/adxl345"
import "tinygo.org/x/drivers" import "tinygo.org/x/drivers"
+1
View File
@@ -2,6 +2,7 @@
// a digital proximity, ambient light, RGB and gesture sensor. // a digital proximity, ambient light, RGB and gesture sensor.
// //
// Datasheet: https://cdn.sparkfun.com/assets/learn_tutorials/3/2/1/Avago-APDS-9960-datasheet.pdf // Datasheet: https://cdn.sparkfun.com/assets/learn_tutorials/3/2/1/Avago-APDS-9960-datasheet.pdf
//
package apds9960 package apds9960
import ( import (
+1
View File
@@ -3,6 +3,7 @@
// //
// http://www.x-powers.com/en.php/Info/product_detail/article_id/29 // http://www.x-powers.com/en.php/Info/product_detail/article_id/29
// Datasheet: https://github.com/m5stack/M5-Schematic/blob/master/Core/AXP192%20Datasheet_v1.1_en_draft_2211.pdf // Datasheet: https://github.com/m5stack/M5-Schematic/blob/master/Core/AXP192%20Datasheet_v1.1_en_draft_2211.pdf
//
package axp192 // import "tinygo.org/x/drivers/axp192" package axp192 // import "tinygo.org/x/drivers/axp192"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// //
// Datasheet: // Datasheet:
// https://www.mouser.com/ds/2/348/bh1750fvi-e-186247.pdf // https://www.mouser.com/ds/2/348/bh1750fvi-e-186247.pdf
//
package bh1750 // import "tinygo.org/x/drivers/bh1750" package bh1750 // import "tinygo.org/x/drivers/bh1750"
import ( import (
+1
View File
@@ -1,6 +1,7 @@
// Package blinkm implements a driver for the BlinkM I2C RGB LED. // Package blinkm implements a driver for the BlinkM I2C RGB LED.
// //
// Datasheet: http://thingm.com/fileadmin/thingm/downloads/BlinkM_datasheet.pdf // Datasheet: http://thingm.com/fileadmin/thingm/downloads/BlinkM_datasheet.pdf
//
package blinkm // import "tinygo.org/x/drivers/blinkm" package blinkm // import "tinygo.org/x/drivers/blinkm"
import "tinygo.org/x/drivers" import "tinygo.org/x/drivers"
+1 -1
View File
@@ -3,6 +3,7 @@
// //
// Datasheet: // Datasheet:
// https://cdn-shop.adafruit.com/datasheets/BST-BME280_DS001-10.pdf // https://cdn-shop.adafruit.com/datasheets/BST-BME280_DS001-10.pdf
//
package bme280 package bme280
import ( import (
@@ -148,7 +149,6 @@ func (d *Device) ReadHumidity() (int32, error) {
// ReadAltitude returns the current altitude in meters based on the // ReadAltitude returns the current altitude in meters based on the
// current barometric pressure and estimated pressure at sea level. // current barometric pressure and estimated pressure at sea level.
// Calculation is based on code from Adafruit BME280 library // Calculation is based on code from Adafruit BME280 library
//
// https://github.com/adafruit/Adafruit_BME280_Library // https://github.com/adafruit/Adafruit_BME280_Library
func (d *Device) ReadAltitude() (alt int32, err error) { func (d *Device) ReadAltitude() (alt int32, err error) {
mPa, _ := d.ReadPressure() mPa, _ := d.ReadPressure()
+1
View File
@@ -3,6 +3,7 @@
// //
// Datasheet: // Datasheet:
// https://cdn-shop.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf // https://cdn-shop.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
//
package bmp180 // import "tinygo.org/x/drivers/bmp180" package bmp180 // import "tinygo.org/x/drivers/bmp180"
import ( import (
+1
View File
@@ -1,4 +1,5 @@
// Package buzzer provides a very simplistic driver for a connected buzzer or low-fidelity speaker. // Package buzzer provides a very simplistic driver for a connected buzzer or low-fidelity speaker.
//
package buzzer // import "tinygo.org/x/drivers/buzzer" package buzzer // import "tinygo.org/x/drivers/buzzer"
import ( import (
+1
View File
@@ -38,4 +38,5 @@
// Each individual driver is contained within its own sub-package within this package and // Each individual driver is contained within its own sub-package within this package and
// there are no interdependencies in order to minimize the final size of compiled code that // there are no interdependencies in order to minimize the final size of compiled code that
// uses any of these drivers. // uses any of these drivers.
//
package drivers // import "tinygo.org/x/drivers" package drivers // import "tinygo.org/x/drivers"
+1
View File
@@ -2,6 +2,7 @@
// //
// Datasheet: // Datasheet:
// https://datasheets.maximintegrated.com/en/ds/DS1307.pdf // https://datasheets.maximintegrated.com/en/ds/DS1307.pdf
//
package ds1307 // import "tinygo.org/x/drivers/ds1307" package ds1307 // import "tinygo.org/x/drivers/ds1307"
import ( import (
+1
View File
@@ -15,6 +15,7 @@
// //
// AT command set: // AT command set:
// https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf // https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
//
package espat // import "tinygo.org/x/drivers/espat" package espat // import "tinygo.org/x/drivers/espat"
import ( import (
+1 -1
View File
@@ -29,7 +29,7 @@ func (d *Device) GetDNS(domain string) (string, error) {
return "", errors.New("Invalid domain lookup result") return "", errors.New("Invalid domain lookup result")
} }
res := strings.Split(r[1], "\r\n") res := strings.Split(r[1], "\r\n")
return strings.Trim(res[0], `"`), nil return res[0], nil
} }
// ConnectTCPSocket creates a new TCP socket connection for the ESP8266/ESP32. // ConnectTCPSocket creates a new TCP socket connection for the ESP8266/ESP32.
+3 -4
View File
@@ -6,6 +6,7 @@
// //
// More information on the Espressif AT command set at: // More information on the Espressif AT command set at:
// https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf // https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
//
package main package main
import ( import (
@@ -18,11 +19,9 @@ import (
// change actAsAP to true to act as an access point instead of connecting to one. // change actAsAP to true to act as an access point instead of connecting to one.
const actAsAP = false const actAsAP = false
var (
// access point info // access point info
ssid string const ssid = "YOURSSID"
pass string const pass = "YOURPASS"
)
// these are the default pins for the Arduino Nano33 IoT. // these are the default pins for the Arduino Nano33 IoT.
// change these to connect to a different UART or pins for the ESP8266/ESP32 // change these to connect to a different UART or pins for the ESP8266/ESP32
+3 -4
View File
@@ -3,6 +3,7 @@
// //
// In other words: // In other words:
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 <--> INTERNET // Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 <--> INTERNET
//
package main package main
import ( import (
@@ -16,11 +17,9 @@ import (
// change actAsAP to true to act as an access point instead of connecting to one. // change actAsAP to true to act as an access point instead of connecting to one.
const actAsAP = false const actAsAP = false
var (
// access point info // access point info
ssid string const ssid = "YOURSSID"
pass string const pass = "YOURPASS"
)
// these are the default pins for the Arduino Nano33 IoT. // these are the default pins for the Arduino Nano33 IoT.
// change these to connect to a different UART or pins for the ESP8266/ESP32 // change these to connect to a different UART or pins for the ESP8266/ESP32
+3 -4
View File
@@ -3,6 +3,7 @@
// //
// In other words: // In other words:
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 // Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266
//
package main package main
import ( import (
@@ -13,11 +14,9 @@ import (
"tinygo.org/x/drivers/net" "tinygo.org/x/drivers/net"
) )
var (
// access point info // access point info
ssid string const ssid = "YOURSSID"
pass string const pass = "YOURPASS"
)
// IP address of the listener aka "hub". Replace with your own info. // IP address of the listener aka "hub". Replace with your own info.
const hubIP = "0.0.0.0" const hubIP = "0.0.0.0"
+3 -4
View File
@@ -8,6 +8,7 @@
// You must install the Paho MQTT package to build this program: // You must install the Paho MQTT package to build this program:
// //
// go get -u github.com/eclipse/paho.mqtt.golang // go get -u github.com/eclipse/paho.mqtt.golang
//
package main package main
import ( import (
@@ -19,11 +20,9 @@ import (
"tinygo.org/x/drivers/net/mqtt" "tinygo.org/x/drivers/net/mqtt"
) )
var (
// access point info // access point info
ssid string const ssid = "YOURSSID"
pass string const pass = "YOURPASS"
)
// IP address of the MQTT broker to use. Replace with your own info. // IP address of the MQTT broker to use. Replace with your own info.
const server = "tcp://test.mosquitto.org:1883" const server = "tcp://test.mosquitto.org:1883"
+3 -4
View File
@@ -8,6 +8,7 @@
// You must also install the Paho MQTT package to build this program: // You must also install the Paho MQTT package to build this program:
// //
// go get -u github.com/eclipse/paho.mqtt.golang // go get -u github.com/eclipse/paho.mqtt.golang
//
package main package main
import ( import (
@@ -20,11 +21,9 @@ import (
"tinygo.org/x/drivers/net/mqtt" "tinygo.org/x/drivers/net/mqtt"
) )
var (
// access point info // access point info
ssid string const ssid = "YOURSSID"
pass string const pass = "YOURPASS"
)
// IP address of the MQTT broker to use. Replace with your own info. // IP address of the MQTT broker to use. Replace with your own info.
//const server = "tcp://test.mosquitto.org:1883" //const server = "tcp://test.mosquitto.org:1883"
+3 -4
View File
@@ -3,6 +3,7 @@
// //
// In other words: // In other words:
// Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266 // Your computer <--> UART0 <--> MCU <--> UART1 <--> ESP8266
//
package main package main
import ( import (
@@ -13,11 +14,9 @@ import (
"tinygo.org/x/drivers/net" "tinygo.org/x/drivers/net"
) )
var (
// access point info // access point info
ssid string const ssid = "YOURSSID"
pass string const pass = "YOURPASS"
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const serverIP = "0.0.0.0" const serverIP = "0.0.0.0"
-39
View File
@@ -1,39 +0,0 @@
package main
import (
"machine"
"time"
"image/color"
"tinygo.org/x/drivers/gc9a01"
)
func main() {
machine.SPI0.Configure(machine.SPIConfig{
Frequency: 80000000,
})
display := gc9a01.New(machine.SPI0, machine.P6, machine.P7, machine.P8, machine.P9)
display.Configure(gc9a01.Config{Orientation: gc9a01.HORIZONTAL, Width: 240, Height: 240})
width, height := display.Size()
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}
black := color.RGBA{0, 0, 0, 255}
display.FillScreen(black)
display.FillRectangle(0, 0, width/2, height/2, white)
display.FillRectangle(width/2, 0, width/2, height/2, red)
display.FillRectangle(0, height/2, width/2, height/2, green)
display.FillRectangle(width/2, height/2, width/2, height/2, blue)
display.FillRectangle(width/4, height/4, width/2, height/2, black)
for {
time.Sleep(time.Hour)
}
}
+2
View File
@@ -9,6 +9,8 @@ import (
"tinygo.org/x/drivers/ili9341" "tinygo.org/x/drivers/ili9341"
) )
var ()
func InitDisplay() *ili9341.Device { func InitDisplay() *ili9341.Device {
machine.SPI0.Configure(machine.SPIConfig{ machine.SPI0.Configure(machine.SPIConfig{
SCK: machine.SPI0_SCK_PIN, SCK: machine.SPI0_SCK_PIN,
+2 -3
View File
@@ -9,7 +9,7 @@ import (
var ( var (
led machine.Pin = machine.LED led machine.Pin = machine.LED
button machine.Pin = machine.D10 button machine.Pin = machine.BUTTON
key *makeybutton.Button key *makeybutton.Button
) )
@@ -25,7 +25,6 @@ func main() {
case makeybutton.Released: case makeybutton.Released:
led.Low() led.Low()
} }
// the more frequent the more responsive time.Sleep(100 * time.Millisecond)
time.Sleep(50 * time.Millisecond)
} }
} }
+1
View File
@@ -2,6 +2,7 @@
// to read data from the onboard MEMS microphone. // to read data from the onboard MEMS microphone.
// //
// Uses ideas from the https://github.com/adafruit/Adafruit_CircuitPlayground repo. // Uses ideas from the https://github.com/adafruit/Adafruit_CircuitPlayground repo.
//
package main package main
import ( import (
+11 -11
View File
@@ -12,11 +12,10 @@
// You can check that mqttpub is running successfully with the following command. // You can check that mqttpub is running successfully with the following command.
// //
// mosquitto_sub -h test.mosquitto.org -t tinygo // mosquitto_sub -h test.mosquitto.org -t tinygo
//
package main package main
import ( import (
"machine"
"fmt" "fmt"
"math/rand" "math/rand"
"time" "time"
@@ -29,14 +28,14 @@ import (
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// debug = true // debug = true
// server = "tinygo.org" // server = "tinygo.org"
// } // }
var ( var (
ssid string ssid string
pass string password string
server string = "tcp://test.mosquitto.org:1883" server string = "tcp://test.mosquitto.org:1883"
debug = false debug = false
) )
@@ -45,7 +44,7 @@ var buf [0x400]byte
var lastRequestTime time.Time var lastRequestTime time.Time
var conn net.Conn var conn net.Conn
var adaptor *rtl8720dn.Driver var adaptor *rtl8720dn.RTL8720DN
func main() { func main() {
err := run() err := run()
@@ -60,17 +59,18 @@ var (
) )
func run() error { func run() error {
// change the UART and pins as needed for platforms other than the WioTerminal. rtl, err := setupRTL8720DN()
adaptor = rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) if err != nil {
adaptor.Debug(debug) return err
adaptor.Configure() }
net.UseDriver(rtl)
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,74 @@
//go:build wioterminal
// +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)
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)
}
+11 -11
View File
@@ -13,11 +13,10 @@
// //
// mosquitto_sub -h test.mosquitto.org -t tinygo/tx // mosquitto_sub -h test.mosquitto.org -t tinygo/tx
// mosquitto_pub -h test.mosquitto.org -t tinygo/rx -m "hello world" // mosquitto_pub -h test.mosquitto.org -t tinygo/rx -m "hello world"
//
package main package main
import ( import (
"machine"
"fmt" "fmt"
"math/rand" "math/rand"
"time" "time"
@@ -30,14 +29,14 @@ import (
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// debug = true // debug = true
// server = "tinygo.org" // server = "tinygo.org"
// } // }
var ( var (
ssid string ssid string
pass string password string
server string = "tcp://test.mosquitto.org:1883" server string = "tcp://test.mosquitto.org:1883"
debug = false debug = false
) )
@@ -46,7 +45,7 @@ var buf [0x400]byte
var lastRequestTime time.Time var lastRequestTime time.Time
var conn net.Conn var conn net.Conn
var adaptor *rtl8720dn.Driver var adaptor *rtl8720dn.RTL8720DN
func main() { func main() {
err := run() err := run()
@@ -69,17 +68,18 @@ func subHandler(client mqtt.Client, msg mqtt.Message) {
} }
func run() error { func run() error {
// change the UART and pins as needed for platforms other than the WioTerminal. rtl, err := setupRTL8720DN()
adaptor = rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) if err != nil {
adaptor.Debug(debug) return err
adaptor.Configure() }
net.UseDriver(rtl)
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
+74
View File
@@ -0,0 +1,74 @@
//go:build wioterminal
// +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)
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)
}
+9 -10
View File
@@ -4,29 +4,26 @@
package main package main
import ( import (
"machine"
"errors" "errors"
"fmt" "fmt"
"runtime" "runtime"
"time" "time"
"tinygo.org/x/drivers/net" "tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/rtl8720dn"
) )
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// ntpHost = "129.6.15.29" // ntpHost = "129.6.15.29"
// debug = true // debug = true
// } // }
var ( var (
ssid string ssid string
pass string password string
ntpHost = "129.6.15.29" ntpHost = "129.6.15.29"
debug = false debug = false
) )
@@ -44,16 +41,18 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) rtl, err := setupRTL8720DN()
adaptor.Debug(debug) if err != nil {
adaptor.Configure() return err
}
net.UseDriver(rtl)
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,72 @@
//go:build wioterminal
// +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)
}
+11 -11
View File
@@ -4,30 +4,28 @@
// You can open a server to accept connections from this program using: // You can open a server to accept connections from this program using:
// //
// nc -w 5 -lk 8080 // nc -w 5 -lk 8080
//
package main package main
import ( import (
"machine"
"bytes" "bytes"
"fmt" "fmt"
"time" "time"
"tinygo.org/x/drivers/net" "tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/rtl8720dn"
) )
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "sghome-gw"
// pass = "your-password" // password = "3af25537b4524"
// serverIP = "192.168.1.119" // serverIP = "192.168.1.119"
// debug = true // debug = true
// } // }
var ( var (
ssid string ssid string
pass string password string
serverIP = "" serverIP = ""
debug = false debug = false
) )
@@ -43,16 +41,18 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) rtl, err := setupRTL8720DN()
adaptor.Debug(debug) if err != nil {
adaptor.Configure() return err
}
net.UseDriver(rtl)
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,72 @@
//go:build wioterminal
// +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)
}
+11 -11
View File
@@ -1,8 +1,6 @@
package main package main
import ( import (
"machine"
"bufio" "bufio"
"fmt" "fmt"
"strings" "strings"
@@ -16,7 +14,7 @@ import (
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// debug = true // debug = true
// url = "https://www.example.com" // url = "https://www.example.com"
// test_root_ca = "..." // test_root_ca = "..."
@@ -24,7 +22,7 @@ import (
var ( var (
ssid string ssid string
pass string password string
url string = "https://www.example.com" url string = "https://www.example.com"
debug = false debug = false
) )
@@ -59,6 +57,7 @@ var buf [0x1000]byte
var lastRequestTime time.Time var lastRequestTime time.Time
var conn net.Conn var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
func main() { func main() {
err := run() err := run()
@@ -69,19 +68,20 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) rtl, err := setupRTL8720DN()
adaptor.Debug(debug) if err != nil {
adaptor.Configure() return err
}
adaptor.SetRootCA(&test_root_ca) rtl.SetRootCA(&test_root_ca)
net.UseDriver(rtl)
http.SetBuf(buf[:]) http.SetBuf(buf[:])
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,72 @@
//go:build wioterminal
// +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)
}
+9 -11
View File
@@ -1,29 +1,26 @@
package main package main
import ( import (
"machine"
"fmt" "fmt"
"strconv" "strconv"
"time" "time"
"tinygo.org/x/drivers/net" "tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http" "tinygo.org/x/drivers/net/http"
"tinygo.org/x/drivers/rtl8720dn"
) )
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// hubIP = "192.168.1.118" // hubIP = "192.168.1.118"
// debug = true // debug = true
// } // }
var ( var (
ssid string ssid string
pass string password string
hubIP = "" hubIP = ""
debug = false debug = false
) )
@@ -39,18 +36,19 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) rtl, err := setupRTL8720DN()
adaptor.Debug(debug) if err != nil {
adaptor.Configure() return err
}
net.UseDriver(rtl)
http.SetBuf(buf[:]) http.SetBuf(buf[:])
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,72 @@
//go:build wioterminal
// +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)
}
+7 -7
View File
@@ -1,12 +1,10 @@
package main package main
import ( import (
"machine"
"fmt" "fmt"
"time" "time"
"tinygo.org/x/drivers/rtl8720dn" "tinygo.org/x/drivers/examples/rtl8720dn"
) )
var ( var (
@@ -22,11 +20,13 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) //rtl8720dn.Debug(true)
adaptor.Debug(debug) rtl, err := rtl8720dn.Setup()
adaptor.Configure() if err != nil {
return err
}
ver, err := adaptor.Version() ver, err := rtl.Version()
if err != nil { if err != nil {
return nil return nil
} }
+10 -36
View File
@@ -1,18 +1,14 @@
package main package main
import ( import (
"machine"
"bufio" "bufio"
"fmt" "fmt"
"image/color" "image/color"
"strings" "strings"
"time" "time"
"tinygo.org/x/drivers/ili9341" "tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http" "tinygo.org/x/drivers/net/http"
"tinygo.org/x/drivers/rtl8720dn"
"tinygo.org/x/tinyfont/proggy" "tinygo.org/x/tinyfont/proggy"
"tinygo.org/x/tinyterm" "tinygo.org/x/tinyterm"
) )
@@ -21,28 +17,19 @@ import (
// If debug is enabled, a serial connection is required. // If debug is enabled, a serial connection is required.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// debug = false // true // debug = false // true
// server = "tinygo.org" // server = "tinygo.org"
// } // }
var ( var (
ssid string ssid string
pass string password string
url = "http://tinygo.org/" url = "http://tinygo.org/"
debug = false debug = false
) )
var ( var (
display = ili9341.NewSPI(
machine.SPI3,
machine.LCD_DC,
machine.LCD_SS_PIN,
machine.LCD_RESET,
)
backlight = machine.LCD_BACKLIGHT
terminal = tinyterm.NewTerminal(display) terminal = tinyterm.NewTerminal(display)
black = color.RGBA{0, 0, 0, 255} black = color.RGBA{0, 0, 0, 255}
@@ -79,22 +66,21 @@ func run() error {
fmt.Fprintf(terminal, "Running in debug mode.\r\n") fmt.Fprintf(terminal, "Running in debug mode.\r\n")
fmt.Fprintf(terminal, "A serial connection is required to continue execution.\r\n") fmt.Fprintf(terminal, "A serial connection is required to continue execution.\r\n")
} }
rtl, err := setupRTL8720DN()
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) if err != nil {
adaptor.Debug(debug) return err
adaptor.Configure() }
net.UseDriver(rtl)
http.UseDriver(adaptor)
http.SetBuf(buf[:]) http.SetBuf(buf[:])
fmt.Fprintf(terminal, "ConnectToAP()\r\n") fmt.Fprintf(terminal, "ConnectToAP()\r\n")
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
fmt.Fprintf(terminal, "connected\r\n\r\n") fmt.Fprintf(terminal, "connected\r\n\r\n")
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -148,15 +134,3 @@ func run() error {
time.Sleep(10 * time.Second) 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})
}
@@ -0,0 +1,98 @@
//go:build wioterminal
// +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)
}
+10 -12
View File
@@ -1,28 +1,26 @@
package main package main
import ( import (
"machine"
"bufio" "bufio"
"fmt" "fmt"
"strings" "strings"
"time" "time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http" "tinygo.org/x/drivers/net/http"
"tinygo.org/x/drivers/rtl8720dn"
) )
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// url = "http://tinygo.org/" // url = "http://tinygo.org/"
// debug = true // debug = true
// } // }
var ( var (
ssid string ssid string
pass string password string
url = "http://tinygo.org/" url = "http://tinygo.org/"
debug = false debug = false
) )
@@ -38,19 +36,19 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) rtl, err := setupRTL8720DN()
adaptor.Debug(debug) if err != nil {
adaptor.Configure() return err
}
http.UseDriver(adaptor) net.UseDriver(rtl)
http.SetBuf(buf[:]) http.SetBuf(buf[:])
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,72 @@
//go:build wioterminal
// +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)
}
+9 -10
View File
@@ -7,19 +7,18 @@ import (
"time" "time"
"tinygo.org/x/drivers/net/http" "tinygo.org/x/drivers/net/http"
"tinygo.org/x/drivers/rtl8720dn"
) )
// You can override the setting with the init() in another source code. // You can override the setting with the init() in another source code.
// func init() { // func init() {
// ssid = "your-ssid" // ssid = "your-ssid"
// pass = "your-password" // password = "your-password"
// debug = true // debug = true
// } // }
var ( var (
ssid string ssid string
pass string password string
debug = false debug = false
) )
@@ -38,18 +37,18 @@ func main() {
} }
func run() error { func run() error {
adaptor := rtl8720dn.New(machine.UART3, machine.PB24, machine.PC24, machine.RTL8720D_CHIP_PU) rtl, err := setupRTL8720DN()
adaptor.Debug(debug) if err != nil {
adaptor.Configure() return err
}
http.UseDriver(rtl)
http.UseDriver(adaptor) err = rtl.ConnectToAccessPoint(ssid, password, 10*time.Second)
err := adaptor.ConnectToAccessPoint(ssid, pass, 10*time.Second)
if err != nil { if err != nil {
return err return err
} }
ip, subnet, gateway, err := adaptor.GetIP() ip, subnet, gateway, err := rtl.GetIP()
if err != nil { if err != nil {
return err return err
} }
@@ -0,0 +1,74 @@
//go:build wioterminal
// +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)
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)
}
+79
View File
@@ -0,0 +1,79 @@
//go:build wioterminal
// +build wioterminal
package rtl8720dn
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
debug bool
)
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 Setup() (*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_with_timeout(10 * time.Second)
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)
}
func Debug(b bool) {
debug = b
}
-34
View File
@@ -1,34 +0,0 @@
package main
import (
"machine"
"tinygo.org/x/drivers/vl6180x"
"time"
)
func main() {
time.Sleep(3 * time.Second)
machine.I2C0.Configure(machine.I2CConfig{
Frequency: 400000,
})
sensor := vl6180x.New(machine.I2C0)
connected := sensor.Connected()
if !connected {
println("VL6180X device not found")
return
}
println("VL6180X device found")
sensor.Configure(true)
var value uint16
var status uint8
for {
value = sensor.Read()
status = sensor.ReadStatus()
println("Distance (mm):", value)
println("Status:", status)
println("---")
time.Sleep(100 * time.Millisecond)
}
}
-84
View File
@@ -1,84 +0,0 @@
package main
import (
"machine"
"image/color"
"time"
"tinygo.org/x/drivers/waveshare-epd/epd2in9"
)
var display epd2in9.Device
const (
width = 128
height = 296
)
func main() {
machine.SPI0.Configure(machine.SPIConfig{
Frequency: 8000000,
Mode: 0,
})
display = epd2in9.New(machine.SPI0, machine.GPIO2, machine.GPIO3, machine.GPIO4, machine.GPIO5)
display.Configure(epd2in9.Config{
Width: width,
LogicalWidth: width,
Height: height,
})
black := color.RGBA{1, 1, 1, 255}
white := color.RGBA{0, 0, 0, 255}
display.ClearBuffer()
println("Clear the display")
display.ClearDisplay()
display.WaitUntilIdle()
println("Waiting for 2 seconds")
time.Sleep(2 * time.Second)
// Show a checkered board
for i := int16(0); i < width/8; i++ {
for j := int16(0); j < height/8; j++ {
if (i+j)%2 == 0 {
showRect(i*8, j*8, 8, 8, black)
}
}
}
println("Show checkered board")
display.Display()
display.WaitUntilIdle()
println("Waiting for 2 seconds")
time.Sleep(2 * time.Second)
println("Set partial lut")
display.SetLUT(false) // partial updates (faster, but with some ghosting)
println("Show smaller striped area")
for i := int16(40); i < 88; i++ {
for j := int16(83); j < 166; j++ {
if (i+j)%4 == 0 || (i+j)%4 == 1 {
display.SetPixel(i, j, black)
} else {
display.SetPixel(i, j, white)
}
}
}
display.Display()
display.WaitUntilIdle()
display.DeepSleep()
println("You could remove power now")
}
func showRect(x int16, y int16, w int16, h int16, c color.RGBA) {
for i := x; i < x+w; i++ {
for j := y; j < y+h; j++ {
display.SetPixel(i, j, c)
}
}
}
+3 -4
View File
@@ -4,6 +4,7 @@
// You can open a server to accept connections from this program using: // You can open a server to accept connections from this program using:
// //
// nc -w 5 -lk 8080 // nc -w 5 -lk 8080
//
package main package main
import ( import (
@@ -14,11 +15,9 @@ import (
"tinygo.org/x/drivers/net" "tinygo.org/x/drivers/net"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const serverIP = "" const serverIP = ""
+2 -4
View File
@@ -9,11 +9,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// these are the default pins for the Arduino Nano33 IoT. // these are the default pins for the Arduino Nano33 IoT.
// change these to connect to a different UART or pins for the ESP8266/ESP32 // change these to connect to a different UART or pins for the ESP8266/ESP32
+3 -4
View File
@@ -9,6 +9,7 @@
// //
// examples/wifinina/webclient // examples/wifinina/webclient
// examples/wifinina/tlsclient // examples/wifinina/tlsclient
//
package main package main
import ( import (
@@ -23,11 +24,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
// Can specify a URL starting with http or https // Can specify a URL starting with http or https
+3 -4
View File
@@ -8,6 +8,7 @@
// You must install the Paho MQTT package to build this program: // You must install the Paho MQTT package to build this program:
// //
// go get -u github.com/eclipse/paho.mqtt.golang // go get -u github.com/eclipse/paho.mqtt.golang
//
package main package main
import ( import (
@@ -20,11 +21,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the MQTT broker to use. Replace with your own info. // IP address of the MQTT broker to use. Replace with your own info.
const server = "tcp://test.mosquitto.org:1883" const server = "tcp://test.mosquitto.org:1883"
+3 -4
View File
@@ -8,6 +8,7 @@
// You must also install the Paho MQTT package to build this program: // You must also install the Paho MQTT package to build this program:
// //
// go get -u github.com/eclipse/paho.mqtt.golang // go get -u github.com/eclipse/paho.mqtt.golang
//
package main package main
import ( import (
@@ -20,11 +21,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the MQTT broker to use. Replace with your own info. // IP address of the MQTT broker to use. Replace with your own info.
const server = "tcp://test.mosquitto.org:1883" const server = "tcp://test.mosquitto.org:1883"
+2 -4
View File
@@ -14,11 +14,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const ntpHost = "129.6.15.29" const ntpHost = "129.6.15.29"
+3 -4
View File
@@ -4,6 +4,7 @@
// You can open a server to accept connections from this program using: // You can open a server to accept connections from this program using:
// //
// nc -w 5 -lk 8080 // nc -w 5 -lk 8080
//
package main package main
import ( import (
@@ -16,11 +17,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const serverIP = "" const serverIP = ""
+3 -4
View File
@@ -4,6 +4,7 @@
// You shall see "strict-transport-security" header in the response, // You shall see "strict-transport-security" header in the response,
// this confirms communication is indeed over HTTPS // this confirms communication is indeed over HTTPS
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
//
package main package main
import ( import (
@@ -17,11 +18,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const server = "tinygo.org" const server = "tinygo.org"
+3 -4
View File
@@ -3,6 +3,7 @@
// //
// In other words: // In other words:
// Your computer <--> UART0 <--> MCU <--> SPI <--> ESP32 // Your computer <--> UART0 <--> MCU <--> SPI <--> ESP32
//
package main package main
import ( import (
@@ -14,11 +15,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const hubIP = "" const hubIP = ""
+3 -4
View File
@@ -3,6 +3,7 @@
// Arduino example: // Arduino example:
// //
// https://github.com/arduino-libraries/WiFiNINA/blob/master/examples/WiFiWebClientRepeating/ // https://github.com/arduino-libraries/WiFiNINA/blob/master/examples/WiFiWebClientRepeating/
//
package main package main
import ( import (
@@ -14,11 +15,9 @@ import (
"tinygo.org/x/drivers/wifinina" "tinygo.org/x/drivers/wifinina"
) )
var (
// access point info // access point info
ssid string const ssid = ""
pass string const pass = ""
)
// IP address of the server aka "hub". Replace with your own info. // IP address of the server aka "hub". Replace with your own info.
const server = "tinygo.org" const server = "tinygo.org"
+1 -1
View File
@@ -2,6 +2,7 @@
// panel controller. // panel controller.
// //
// Datasheet: https://focuslcds.com/content/FT6236.pdf // Datasheet: https://focuslcds.com/content/FT6236.pdf
//
package ft6336 package ft6336
import ( import (
@@ -41,7 +42,6 @@ func (d *Device) Configure(config Config) error {
} }
// SetGMode sets interrupt mode. // SetGMode sets interrupt mode.
//
// 0x00 : Interrupt Polling mode // 0x00 : Interrupt Polling mode
// 0x01 : Interrupt Trigger mode (default) // 0x01 : Interrupt Trigger mode (default)
func (d *Device) SetGMode(v uint8) { func (d *Device) SetGMode(v uint8) {
-567
View File
@@ -1,567 +0,0 @@
// Package gc9a01 implements a driver for the gc9a01 LCD round display
//
// Datasheet: https://www.waveshare.com/w/upload/5/5e/GC9A01A.pdf
package gc9a01 // import "tinygo.org/x/drivers/gc9a01"
import (
"image/color"
"machine"
"time"
"errors"
"tinygo.org/x/drivers"
)
// Rotation controls the rotation used by the display.
type Orientation uint8
// FrameRate controls the frame rate used by the display.
type FrameRate uint8
// Device wraps an SPI connection.
type Device struct {
bus drivers.SPI
dcPin machine.Pin
resetPin machine.Pin
csPin machine.Pin
blPin machine.Pin
width int16
height int16
columnOffsetCfg int16
rowOffsetCfg int16
columnOffset int16
rowOffset int16
frameRate FrameRate
isBGR bool
vSyncLines int16
orientation Orientation
batchLength int16
batchData []uint8
}
// Config is the configuration for the display
type Config struct {
Orientation Orientation
RowOffset int16
ColumnOffset int16
FrameRate FrameRate
VSyncLines int16
Width int16
Height int16
}
// New creates a new ST7789 connection. The SPI wire must already be configured.
func New(bus drivers.SPI, resetPin, dcPin, csPin, blPin machine.Pin) Device {
resetPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
dcPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
csPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
blPin.Configure(machine.PinConfig{Mode: machine.PinOutput})
return Device{
bus: bus,
resetPin: resetPin,
dcPin: dcPin,
csPin: csPin,
blPin: blPin,
}
}
// Reset the Device
func (d *Device) Reset() {
d.resetPin.High()
time.Sleep(100 * time.Millisecond)
d.resetPin.Low()
time.Sleep(100 * time.Millisecond)
d.resetPin.High()
time.Sleep(100 * time.Millisecond)
}
// Sets Device configuration for screen orientation using the initialzation values
func (d *Device) SetDeviceOrientation() {
var MemoryAccessReg uint8
//Get GRAM and LCD width and height
if d.orientation == HORIZONTAL {
MemoryAccessReg = 0xc8
} else {
MemoryAccessReg = 0x68
}
// Set the read / write scan direction of the frame memory
d.Command(MADCTR)
//0x08 set RGB
d.Command(MemoryAccessReg)
}
// setWindow prepares the screen to be modified at a given rectangle
func (d *Device) setWindow(x, y, w, h int16) {
if d.orientation == HORIZONTAL {
x += d.columnOffset
y += d.rowOffset
} else {
x += d.rowOffset
y += d.columnOffset
}
d.Tx([]uint8{CASET}, true)
d.Tx([]uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)}, false)
d.Tx([]uint8{RASET}, true)
d.Tx([]uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)}, false)
d.Command(RAMWR)
}
// FillScreen fills the screen with a given color
func (d *Device) FillScreen(c color.RGBA) {
d.FillRectangle(0, 0, d.height, d.width, c)
}
// FillRectangle fills a rectangle at a given coordinates with a color
func (d *Device) FillRectangle(x, y, width, height int16, c color.RGBA) error {
k, j := d.Size()
var i int32
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
x >= k || (x+width) > k || y >= j || (y+height) > j {
return errors.New("rectangle coordinates outside display area")
}
d.setWindow(x, y, width, height)
c565 := RGBATo565(c)
c1 := uint8(c565 >> 8)
c2 := uint8(c565)
for i = 0; i < int32(d.batchLength); i++ {
d.batchData[i*2] = c1
d.batchData[i*2+1] = c2
}
i = int32(width) * int32(height)
batchLength := int32(d.batchLength)
for i > 0 {
if i >= batchLength {
d.Tx(d.batchData, false)
} else {
d.Tx(d.batchData[:i*2], false)
}
i -= batchLength
}
return nil
}
// Display sends the whole buffer to the screen
func (d *Device) Display() error {
return nil
}
// FillRectangleWithBuffer fills buffer with a rectangle at a given coordinates.
func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {
h, w := d.Size()
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
x >= h || (x+width) > h || y >= w || (y+height) > w {
return errors.New("rectangle coordinates outside display area")
}
k := int32(width) * int32(height)
l := int32(len(buffer))
if k != l {
return errors.New("buffer length does not match with rectangle size")
}
d.setWindow(x, y, width, height)
offset := int32(0)
batchLength := int32(d.batchLength)
for k > 0 {
for i := int32(0); i < batchLength; i++ {
if offset+i < l {
c565 := RGBATo565(buffer[offset+i])
c1 := uint8(c565 >> 8)
c2 := uint8(c565)
d.batchData[i*2] = c1
d.batchData[i*2+1] = c2
}
}
if k >= batchLength {
d.Tx(d.batchData, false)
} else {
d.Tx(d.batchData[:k*2], false)
}
k -= batchLength
offset += batchLength
}
return nil
}
// DrawFastVLine draws a vertical line faster than using SetPixel
func (d *Device) DrawFastVLine(x, y0, y1 int16, c color.RGBA) {
if y0 > y1 {
y0, y1 = y1, y0
}
d.FillRectangle(x, y0, 1, y1-y0+1, c)
}
// DrawFastHLine draws a horizontal line faster than using SetPixel
func (d *Device) DrawFastHLine(x0, x1, y int16, c color.RGBA) {
if x0 > x1 {
x0, x1 = x1, x0
}
d.FillRectangle(x0, y, x1-x0+1, 1, c)
}
// SetPixel sets a pixel in the screen
func (d *Device) SetPixel(x, y int16, c color.RGBA) {
w, h := d.Size()
if x < 0 || y < 0 || x >= w || y >= h {
return
}
d.FillRectangle(x, y, 1, 1, c)
}
// Command sends a command to the display.
func (d *Device) Command(command uint8) {
d.Tx([]byte{command}, true)
}
// Data sends data to the display.
func (d *Device) Data(data uint8) {
d.Tx([]byte{data}, false)
}
// Tx sends data to the display
func (d *Device) Tx(data []byte, isCommand bool) {
d.dcPin.Set(!isCommand)
d.bus.Tx(data, nil)
}
// Rx reads data from the display
func (d *Device) Rx(command uint8, data []byte) {
d.dcPin.Low()
d.csPin.Low()
d.bus.Transfer(command)
d.dcPin.High()
for i := range data {
data[i], _ = d.bus.Transfer(0xFF)
}
d.csPin.High()
}
// Size returns the current size of the display.
func (d *Device) Size() (w, h int16) {
return d.height, d.width
}
// EnableBacklight enables or disables the backlight
func (d *Device) EnableBacklight(enable bool) {
if enable {
d.blPin.High()
} else {
d.blPin.Low()
}
}
// InvertColors inverts the colors of the screen
func (d *Device) InvertColors(invert bool) {
if invert {
d.Command(INVON)
} else {
d.Command(INVOFF)
}
}
// IsBGR changes the color mode (RGB/BGR)
func (d *Device) IsBGR(bgr bool) {
d.isBGR = bgr
}
// SetScrollArea sets an area to scroll with fixed top and bottom parts of the display.
func (d *Device) SetScrollArea(topFixedArea, bottomFixedArea int16) {
d.Command(VSCRDEF)
d.Tx([]uint8{
uint8(topFixedArea >> 8), uint8(topFixedArea),
uint8(d.height - topFixedArea - bottomFixedArea>>8), uint8(d.height - topFixedArea - bottomFixedArea),
uint8(bottomFixedArea >> 8), uint8(bottomFixedArea)},
false)
}
// SetScroll sets the vertical scroll address of the display.
func (d *Device) SetScroll(line int16) {
d.Command(VSCRSADD)
d.Tx([]uint8{uint8(line >> 8), uint8(line)}, false)
}
// StopScroll returns the display to its normal state.
func (d *Device) StopScroll() {
d.Command(NORON)
}
// RGBATo565 converts a color.RGBA to uint16 used in the display
func RGBATo565(c color.RGBA) uint16 {
r, g, b, _ := c.RGBA()
return uint16((r & 0xF800) +
((g & 0xFC00) >> 5) +
((b & 0xF800) >> 11))
}
// Configure initializes the display with default configuration
func (d *Device) Configure(cfg Config) {
if cfg.Width != 0 {
d.width = cfg.Width
} else {
d.width = 240
}
if cfg.Height != 0 {
d.height = cfg.Height
} else {
d.height = 240
}
d.orientation = cfg.Orientation
d.rowOffsetCfg = cfg.RowOffset
d.columnOffsetCfg = cfg.ColumnOffset
d.batchLength = d.width
if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 {
d.vSyncLines = cfg.VSyncLines
} else {
d.vSyncLines = 16
}
d.batchLength += d.batchLength & 1
d.batchData = make([]uint8, d.batchLength*2)
// Reset the device
d.Reset()
// Set Device Attributes
d.SetDeviceOrientation()
// Common initialization
d.Command(0xEF)
d.Command(0xEB)
d.Data(0x14)
d.Command(INTEN1)
d.Command(0xEF)
d.Command(0xEB)
d.Data(0x14)
d.Command(0x84)
d.Data(0x40)
d.Command(0x85)
d.Data(0xFF)
d.Command(0x86)
d.Data(0xFF)
d.Command(0x87)
d.Data(0xFF)
d.Command(0x88)
d.Data(0x0A)
d.Command(0x89)
d.Data(0x21)
d.Command(0x8A)
d.Data(0x00)
d.Command(0x8B)
d.Data(0x80)
d.Command(0x8C)
d.Data(0x01)
d.Command(0x8D)
d.Data(0x01)
d.Command(0x8E)
d.Data(0xFF)
d.Command(0x8F)
d.Data(0xFF)
d.Command(DISFNCTL)
d.Data(0x00)
d.Data(0x20)
d.Command(MADCTR)
d.Data(0x08) //Set as vertical screen
d.Command(COLMOD)
d.Data(0x05)
d.Command(0x90)
d.Data(0x08)
d.Data(0x08)
d.Data(0x08)
d.Data(0x08)
d.Command(0xBD)
d.Data(0x06)
d.Command(0xBC)
d.Data(0x00)
d.Command(0xFF)
d.Data(0x60)
d.Data(0x01)
d.Data(0x04)
d.Command(PWCTR3)
d.Data(0x13)
d.Command(PWCTR4)
d.Data(0x13)
d.Command(0xC9)
d.Data(0x22)
d.Command(0xBE)
d.Data(0x11)
d.Command(0xE1)
d.Data(0x10)
d.Data(0x0E)
d.Command(0xDF)
d.Data(0x21)
d.Data(0x0c)
d.Data(0x02)
d.Command(GMSET1)
d.Data(0x45)
d.Data(0x09)
d.Data(0x08)
d.Data(0x08)
d.Data(0x26)
d.Data(0x2A)
d.Command(GMSET2)
d.Data(0x43)
d.Data(0x70)
d.Data(0x72)
d.Data(0x36)
d.Data(0x37)
d.Data(0x6F)
d.Command(GMSET3)
d.Data(0x45)
d.Data(0x09)
d.Data(0x08)
d.Data(0x08)
d.Data(0x26)
d.Data(0x2A)
d.Command(GMSET4)
d.Data(0x43)
d.Data(0x70)
d.Data(0x72)
d.Data(0x36)
d.Data(0x37)
d.Data(0x6F)
d.Command(0xED)
d.Data(0x1B)
d.Data(0x0B)
d.Command(0xAE)
d.Data(0x77)
d.Command(0xCD)
d.Data(0x63)
d.Command(0x70)
d.Data(0x07)
d.Data(0x07)
d.Data(0x04)
d.Data(0x0E)
d.Data(0x0F)
d.Data(0x09)
d.Data(0x07)
d.Data(0x08)
d.Data(0x03)
d.Command(FRMCTL)
d.Data(0x34)
d.Command(0x62)
d.Data(0x18)
d.Data(0x0D)
d.Data(0x71)
d.Data(0xED)
d.Data(0x70)
d.Data(0x70)
d.Data(0x18)
d.Data(0x0F)
d.Data(0x71)
d.Data(0xEF)
d.Data(0x70)
d.Data(0x70)
d.Command(0x63)
d.Data(0x18)
d.Data(0x11)
d.Data(0x71)
d.Data(0xF1)
d.Data(0x70)
d.Data(0x70)
d.Data(0x18)
d.Data(0x13)
d.Data(0x71)
d.Data(0xF3)
d.Data(0x70)
d.Data(0x70)
d.Command(0x64)
d.Data(0x28)
d.Data(0x29)
d.Data(0xF1)
d.Data(0x01)
d.Data(0xF1)
d.Data(0x00)
d.Data(0x07)
d.Command(0x66)
d.Data(0x3C)
d.Data(0x00)
d.Data(0xCD)
d.Data(0x67)
d.Data(0x45)
d.Data(0x45)
d.Data(0x10)
d.Data(0x00)
d.Data(0x00)
d.Data(0x00)
d.Command(0x67)
d.Data(0x00)
d.Data(0x3C)
d.Data(0x00)
d.Data(0x00)
d.Data(0x00)
d.Data(0x01)
d.Data(0x54)
d.Data(0x10)
d.Data(0x32)
d.Data(0x98)
d.Command(0x74)
d.Data(0x10)
d.Data(0x85)
d.Data(0x80)
d.Data(0x00)
d.Data(0x00)
d.Data(0x4E)
d.Data(0x00)
d.Command(0x98)
d.Data(0x3e)
d.Data(0x07)
d.Command(TEON)
d.Command(0x21)
d.Command(SLPOUT)
time.Sleep(120 * time.Millisecond)
d.Command(DISPON)
time.Sleep(20 * time.Millisecond)
d.blPin.High()
}
-65
View File
@@ -1,65 +0,0 @@
package gc9a01
// Registers
const (
NOP = 0x00
SWRESET = 0x01
RDDIDIF = 0x04
RDDST = 0x09
SLPIN = 0x10
SLPOUT = 0x11
PTLON = 0x12
NORON = 0x13
INVOFF = 0x20
INVON = 0x21
DISPOFF = 0x28
DISPON = 0x29
CASET = 0x2A
RASET = 0x2B
RAMWR = 0x2C
PTLAR = 0x30
VSCRDEF = 0x33
TEOFF = 0x34
TEON = 0x35
MADCTR = 0x36
VSCRSADD = 0x37
IDMOFF = 0x38
IDMON = 0x39
COLMOD = 0x3A
RMEMCON = 0x3C
STTRSCL = 0x44
GTSCL = 0x45
WRDISBV = 0x51
WRCTRLD = 0x51
MADCTL_MY = 0x80
MADCTL_MX = 0x40
MADCTL_MV = 0x20
MADCTL_ML = 0x10
MADCTL_RGB = 0x00
MADCTL_BGR = 0x08
MADCTL_MH = 0x04
RDID1 = 0xDA
RDID2 = 0xDB
RDID3 = 0xDC
RGBICTR = 0xB0
BLPCHCTRL = 0xB5
DISFNCTL = 0xB6
TECTL = 0xBA
INTCTL = 0xBA
FRMCTL = 0xE8
SPICTL = 0xE9
PWCTR1 = 0xC1
PWCTR2 = 0xC2
PWCTR3 = 0xC3
PWCTR4 = 0xC4
PWCTR7 = 0xC7
INTEN1 = 0xFE
INTEN2 = 0xEF
GMSET1 = 0xF0
GMSET2 = 0xF1
GMSET3 = 0xF2
GMSET4 = 0xF3
HORIZONTAL Orientation = 0
VERTICAL Orientation = 1
)
+1
View File
@@ -1,6 +1,7 @@
// Package hd44780 provides a driver for the HD44780 LCD controller. // Package hd44780 provides a driver for the HD44780 LCD controller.
// //
// Datasheet: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf // Datasheet: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf
//
package hd44780 // import "tinygo.org/x/drivers/hd44780" package hd44780 // import "tinygo.org/x/drivers/hd44780"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// with an I2C adapter. // with an I2C adapter.
// //
// Datasheet: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf // Datasheet: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf
//
package hd44780i2c package hd44780i2c
import ( import (
+2
View File
@@ -2,6 +2,7 @@
// a capacitive digital sensor for relative humidity and temperature. // a capacitive digital sensor for relative humidity and temperature.
// //
// Datasheet: https://www.st.com/resource/en/datasheet/hts221.pdf // Datasheet: https://www.st.com/resource/en/datasheet/hts221.pdf
//
package hts221 package hts221
import ( import (
@@ -84,6 +85,7 @@ func (d *Device) ReadTemperature() (temperature int32, err error) {
// Resolution sets the HTS221's resolution mode. // Resolution sets the HTS221's resolution mode.
// The higher resolutions are more accurate but comsume more power (see datasheet). // The higher resolutions are more accurate but comsume more power (see datasheet).
// The number of averaged samples will be (h + 2) ^ 2, (t + 1) ^ 2 // The number of averaged samples will be (h + 2) ^ 2, (t + 1) ^ 2
//
func (d *Device) Resolution(h uint8, t uint8) { func (d *Device) Resolution(h uint8, t uint8) {
if h > 7 { if h > 7 {
h = 3 // default h = 3 // default
+1
View File
@@ -2,6 +2,7 @@
// //
// Guide: https://cdn-learn.adafruit.com/downloads/pdf/32x16-32x32-rgb-led-matrix.pdf // Guide: https://cdn-learn.adafruit.com/downloads/pdf/32x16-32x32-rgb-led-matrix.pdf
// This driver was inspired by https://github.com/2dom/PxMatrix // This driver was inspired by https://github.com/2dom/PxMatrix
//
package hub75 // import "tinygo.org/x/drivers/hub75" package hub75 // import "tinygo.org/x/drivers/hub75"
import ( import (
@@ -7,13 +7,13 @@ package flate
// dictDecoder implements the LZ77 sliding dictionary as used in decompression. // dictDecoder implements the LZ77 sliding dictionary as used in decompression.
// LZ77 decompresses data through sequences of two forms of commands: // LZ77 decompresses data through sequences of two forms of commands:
// //
// - Literal insertions: Runs of one or more symbols are inserted into the data // * Literal insertions: Runs of one or more symbols are inserted into the data
// stream as is. This is accomplished through the writeByte method for a // stream as is. This is accomplished through the writeByte method for a
// single symbol, or combinations of writeSlice/writeMark for multiple symbols. // single symbol, or combinations of writeSlice/writeMark for multiple symbols.
// Any valid stream must start with a literal insertion if no preset dictionary // Any valid stream must start with a literal insertion if no preset dictionary
// is used. // is used.
// //
// - Backward copies: Runs of one or more symbols are copied from previously // * Backward copies: Runs of one or more symbols are copied from previously
// emitted data. Backward copies come as the tuple (dist, length) where dist // emitted data. Backward copies come as the tuple (dist, length) where dist
// determines how far back in the stream to copy from and length determines how // determines how far back in the stream to copy from and length determines how
// many bytes to copy. Note that it is valid for the length to be greater than // many bytes to copy. Note that it is valid for the length to be greater than
@@ -124,17 +124,12 @@ const maxBitsLimit = 16
// The cases of 0, 1, and 2 literals are handled by special case code. // The cases of 0, 1, and 2 literals are handled by special case code.
// //
// list An array of the literals with non-zero frequencies // list An array of the literals with non-zero frequencies
//
// and their associated frequencies. The array is in order of increasing // and their associated frequencies. The array is in order of increasing
// frequency, and has as its last element a special element with frequency // frequency, and has as its last element a special element with frequency
// MaxInt32 // MaxInt32
//
// maxBits The maximum number of bits that should be used to encode any literal. // maxBits The maximum number of bits that should be used to encode any literal.
//
// Must be less than 16. // Must be less than 16.
//
// return An integer array in which array[i] indicates the number of literals // return An integer array in which array[i] indicates the number of literals
//
// that should be encoded in i bits. // that should be encoded in i bits.
func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 { func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
if maxBits >= maxBitsLimit { if maxBits >= maxBitsLimit {
-2
View File
@@ -326,9 +326,7 @@ func (d *decoder) parsetRNS(length uint32) error {
// Read presents one or more IDAT chunks as one continuous stream (minus the // Read presents one or more IDAT chunks as one continuous stream (minus the
// intermediate chunk headers and footers). If the PNG data looked like: // intermediate chunk headers and footers). If the PNG data looked like:
//
// ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2 // ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2
//
// then this reader presents xxxyy. For well-formed PNG data, the decoder state // then this reader presents xxxyy. For well-formed PNG data, the decoder state
// immediately before the first Read call is that d.r is positioned between the // immediately before the first Read call is that d.r is positioned between the
// first IDAT and xxx, and the decoder state immediately after the last Read // first IDAT and xxx, and the decoder state immediately after the last Read
+1
View File
@@ -43,6 +43,7 @@ func New(bus drivers.I2C) Device {
// * VoltConvTime = CONVTIME_1100USEC // * VoltConvTime = CONVTIME_1100USEC
// * CurrentConvTime = CONVTIME_1100USEC // * CurrentConvTime = CONVTIME_1100USEC
// * Mode = MODE_CONTINUOUS | MODE_VOLTAGE | MODE_CURRENT // * Mode = MODE_CONTINUOUS | MODE_VOLTAGE | MODE_CURRENT
//
func (d *Device) Configure(cfg Config) { func (d *Device) Configure(cfg Config) {
var val uint16 var val uint16
+1 -2
View File
@@ -7,12 +7,11 @@
// https://www.adafruit.com/product/3163 // https://www.adafruit.com/product/3163
// //
// Datasheet: // Datasheet:
//
// https://www.lumissil.com/assets/pdf/core/IS31FL3731_DS.pdf // https://www.lumissil.com/assets/pdf/core/IS31FL3731_DS.pdf
// //
// This driver inspired by Adafruit Python driver: // This driver inspired by Adafruit Python driver:
//
// https://github.com/adafruit/Adafruit_CircuitPython_IS31FL3731 // https://github.com/adafruit/Adafruit_CircuitPython_IS31FL3731
//
package is31fl3731 package is31fl3731
import ( import (
+1
View File
@@ -38,6 +38,7 @@ type DeviceAdafruitCharlieWing15x7 struct {
// | + - - - - - - - - - - - - - + // | + - - - - - - - - - - - - - +
// | // |
// start (address 0x00) // start (address 0x00)
//
func (d *DeviceAdafruitCharlieWing15x7) enableLEDs() (err error) { func (d *DeviceAdafruitCharlieWing15x7) enableLEDs() (err error) {
for frame := FRAME_0; frame <= FRAME_7; frame++ { for frame := FRAME_0; frame <= FRAME_7; frame++ {
err = d.selectCommand(frame) err = d.selectCommand(frame)
+1
View File
@@ -2,6 +2,7 @@
// typically used to control DC motors. // typically used to control DC motors.
// //
// Datasheet: https://www.ti.com/lit/ds/symlink/l293d.pdf // Datasheet: https://www.ti.com/lit/ds/symlink/l293d.pdf
//
package l293x // import "tinygo.org/x/drivers/l293x" package l293x // import "tinygo.org/x/drivers/l293x"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// typically used to control DC motors. // typically used to control DC motors.
// //
// Datasheet: https://www.elecrow.com/download/datasheet-l9110.pdf // Datasheet: https://www.elecrow.com/download/datasheet-l9110.pdf
//
package l9110x // import "tinygo.org/x/drivers/l9110x" package l9110x // import "tinygo.org/x/drivers/l9110x"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// a magnetic sensor which is included on BBC micro:bit v1.5. // a magnetic sensor which is included on BBC micro:bit v1.5.
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lis2mdl.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lis2mdl.pdf
//
package lis2mdl // import "tinygo.org/x/drivers/lis2mdl" package lis2mdl // import "tinygo.org/x/drivers/lis2mdl"
import ( import (
+1
View File
@@ -1,6 +1,7 @@
// Package lis3dh provides a driver for the LIS3DH digital accelerometer. // Package lis3dh provides a driver for the LIS3DH digital accelerometer.
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lis3dh.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lis3dh.pdf
//
package lis3dh // import "tinygo.org/x/drivers/lis3dh" package lis3dh // import "tinygo.org/x/drivers/lis3dh"
import "tinygo.org/x/drivers" import "tinygo.org/x/drivers"
+1
View File
@@ -1,6 +1,7 @@
// Package lps22hb implements a driver for LPS22HB, a MEMS nano pressure sensor. // Package lps22hb implements a driver for LPS22HB, a MEMS nano pressure sensor.
// //
// Datasheet: https://www.st.com/resource/en/datasheet/dm00140895.pdf // Datasheet: https://www.st.com/resource/en/datasheet/dm00140895.pdf
//
package lps22hb package lps22hb
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// a 3 axis accelerometer/magnetic sensor which is included on BBC micro:bits v1.5. // a 3 axis accelerometer/magnetic sensor which is included on BBC micro:bits v1.5.
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lsm303agr.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lsm303agr.pdf
//
package lsm303agr // import "tinygo.org/x/drivers/lsm303agr" package lsm303agr // import "tinygo.org/x/drivers/lsm303agr"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// Measurement Unit (IMU) // Measurement Unit (IMU)
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lsm6ds3.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lsm6ds3.pdf
//
package lsm6ds3 // import "tinygo.org/x/drivers/lsm6ds3" package lsm6ds3 // import "tinygo.org/x/drivers/lsm6ds3"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// a 6 axis Inertial Measurement Unit (IMU) // a 6 axis Inertial Measurement Unit (IMU)
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lsm6ds3tr.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lsm6ds3tr.pdf
//
package lsm6ds3tr // import "tinygo.org/x/drivers/lsm6ds3tr" package lsm6ds3tr // import "tinygo.org/x/drivers/lsm6ds3tr"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// a 6 axis Inertial Measurement Unit (IMU) // a 6 axis Inertial Measurement Unit (IMU)
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lsm6dsox.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lsm6dsox.pdf
//
package lsm6dsox // import "tinygo.org/x/drivers/lsm6dsox" package lsm6dsox // import "tinygo.org/x/drivers/lsm6dsox"
import ( import (
+1
View File
@@ -1,6 +1,7 @@
// LSM9DS1, 9 axis Inertial Measurement Unit (IMU) // LSM9DS1, 9 axis Inertial Measurement Unit (IMU)
// //
// Datasheet: https://www.st.com/resource/en/datasheet/lsm6ds3.pdf // Datasheet: https://www.st.com/resource/en/datasheet/lsm6ds3.pdf
//
package lsm9ds1 // import "tinygo.org/x/drivers/lsm9ds1" package lsm9ds1 // import "tinygo.org/x/drivers/lsm9ds1"
import ( import (
+1
View File
@@ -2,6 +2,7 @@
// Freescale/NXP. // Freescale/NXP.
// //
// Datasheet: https://www.nxp.com/docs/en/data-sheet/MAG3110.pdf // Datasheet: https://www.nxp.com/docs/en/data-sheet/MAG3110.pdf
//
package mag3110 // import "tinygo.org/x/drivers/mag3110" package mag3110 // import "tinygo.org/x/drivers/mag3110"
import "tinygo.org/x/drivers" import "tinygo.org/x/drivers"
+24 -43
View File
@@ -1,17 +1,11 @@
package makeybutton package makeybutton
const ( const bufferSize = 6
bufferSize = 3
maxSumAllowed = 4
)
// Buffer is a buffer to keep track of the most recent readings for a button. // Buffer is a buffer to keep track of the most recent readings for a button.
// in bit form.
type Buffer struct { type Buffer struct {
data [bufferSize]byte readings [bufferSize]bool
byteCounter int index int
bitCounter int
sum int
} }
// NewBuffer returns a new buffer. // NewBuffer returns a new buffer.
@@ -19,47 +13,34 @@ func NewBuffer() *Buffer {
return &Buffer{} return &Buffer{}
} }
// Sum returns the sum of all measurements // Used returns how many bytes in buffer have been used.
func (b *Buffer) Sum() int { func (b *Buffer) Used() int {
return b.sum return b.index
} }
// Put stores a boolean button state into the buffer. // Put stores a boolean in the buffer.
func (b *Buffer) Put(val bool) { func (b *Buffer) Put(val bool) bool {
currentMeasurement, oldestMeasurement := b.updateData(val) b.index++
b.updateCounters() if b.index >= bufferSize {
b.index = 0
if currentMeasurement != 0 && b.sum < maxSumAllowed {
b.sum++
} }
if oldestMeasurement != 0 && b.sum > 0 { b.readings[b.index] = val
b.sum--
} return true
} }
func (b *Buffer) updateData(val bool) (byte, byte) { // Avg returns the "average" of all the readings in the buffer, by
currentByte := b.data[b.byteCounter] // treating a true as 1 and a false as -1.
oldestMeasurement := (currentByte >> b.bitCounter) & 0x01 func (b *Buffer) Avg() int {
avg := 0
if val { for i := 0; i < bufferSize; i++ {
currentByte |= (1 << b.bitCounter) if b.readings[i] {
avg += 1
} else { } else {
currentByte &= ^(1 << b.bitCounter) avg -= 1
}
} }
b.data[b.byteCounter] = currentByte return avg
return (currentByte >> b.bitCounter) & 0x01, oldestMeasurement
}
func (b *Buffer) updateCounters() {
b.bitCounter++
if b.bitCounter == 8 {
b.bitCounter = 0
b.byteCounter++
if b.byteCounter == bufferSize {
b.byteCounter = 0
}
}
} }
+20 -34
View File
@@ -4,8 +4,6 @@
// Inspired by the amazing MakeyMakey // Inspired by the amazing MakeyMakey
// https://makeymakey.com/ // https://makeymakey.com/
// //
// This code is a reinterpretation of
// https://github.com/sparkfun/MaKeyMaKey/blob/master/firmware/Arduino/makey_makey/makey_makey.ino
package makeybutton package makeybutton
import ( import (
@@ -13,11 +11,6 @@ import (
"time" "time"
) )
var (
pressThreshold int = 1
releaseThreshold int = 0
)
// ButtonState represents the state of a MakeyButton. // ButtonState represents the state of a MakeyButton.
type ButtonState int type ButtonState int
@@ -40,7 +33,6 @@ const (
type Button struct { type Button struct {
pin machine.Pin pin machine.Pin
state ButtonState state ButtonState
pressed bool
readings *Buffer readings *Buffer
HighMeansPressed bool HighMeansPressed bool
} }
@@ -57,7 +49,7 @@ func NewButton(pin machine.Pin) *Button {
// Configure configures the Makey Button pin to have the correct settings to detect touches. // Configure configures the Makey Button pin to have the correct settings to detect touches.
func (b *Button) Configure() error { func (b *Button) Configure() error {
// Note that on AVR we have to first turn on the pullup, and then turn off the pullup, // Note that we have to first turn on the pullup, and then turn off the pullup,
// in order for the pin to be properly floating. // in order for the pin to be properly floating.
b.pin.Configure(machine.PinConfig{Mode: machine.PinInputPullup}) b.pin.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
@@ -70,36 +62,30 @@ func (b *Button) Configure() error {
// Get returns a ButtonEvent based on the most recent state of the button, // Get returns a ButtonEvent based on the most recent state of the button,
// and if it has changed by being pressed or released. // and if it has changed by being pressed or released.
func (b *Button) Get() ButtonEvent { func (b *Button) Get() ButtonEvent {
b.update() // if pin is pulled up, a low value means the key is pressed
pressed := !b.pin.Get()
if b.pressed { if b.HighMeansPressed {
// the button had previously been pressed, // otherwise, a high value means the key is pressed
// but now appears to have been released. pressed = !pressed
if b.readings.Sum() <= releaseThreshold {
b.pressed = false
b.state = Release
return Released
} }
} else {
// the button had previously not been pressed, avg := b.readings.Avg()
// but now appears to have been pressed. b.readings.Put(pressed)
if b.readings.Sum() >= pressThreshold {
b.pressed = true switch {
case pressed && avg > -1*bufferSize+2:
if b.state == Press {
return NotChanged
}
b.state = Press b.state = Press
return Pressed return Pressed
case !pressed:
if b.state == Press {
b.state = Release
return Released
} }
} }
return NotChanged return NotChanged
} }
func (b *Button) update() {
// if pin is pulled up, a low value means the key is pressed
press := !b.pin.Get()
if b.HighMeansPressed {
// otherwise, a high value means the key is pressed
press = !press
}
b.readings.Put(press)
}
+1
View File
@@ -1,6 +1,7 @@
// Package mcp2515 implements a driver for the MCP2515 CAN Controller. // Package mcp2515 implements a driver for the MCP2515 CAN Controller.
// //
// Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/MCP2515-Stand-Alone-CAN-Controller-with-SPI-20001801J.pdf // Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/MCP2515-Stand-Alone-CAN-Controller-with-SPI-20001801J.pdf
//
package mcp2515 // import "tinygo.org/x/drivers/mcp2515" package mcp2515 // import "tinygo.org/x/drivers/mcp2515"
const DebugEn = 0 const DebugEn = 0
+1
View File
@@ -1,6 +1,7 @@
// Package mcp3008 implements a driver for the MCP3008 Analog to Digital Converter. // Package mcp3008 implements a driver for the MCP3008 Analog to Digital Converter.
// //
// Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21295d.pdf // Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21295d.pdf
//
package mcp3008 // import "tinygo.org/x/drivers/mcp3008" package mcp3008 // import "tinygo.org/x/drivers/mcp3008"
import ( import (
+1
View File
@@ -4,6 +4,7 @@
// Package microbitmatrix implements a driver for the BBC micro:bit's LED matrix. // Package microbitmatrix implements a driver for the BBC micro:bit's LED matrix.
// //
// Schematic: https://github.com/bbcmicrobit/hardware/blob/master/SCH_BBC-Microbit_V1.3B.pdf // Schematic: https://github.com/bbcmicrobit/hardware/blob/master/SCH_BBC-Microbit_V1.3B.pdf
//
package microbitmatrix // import "tinygo.org/x/drivers/microbitmatrix" package microbitmatrix // import "tinygo.org/x/drivers/microbitmatrix"
import ( import (
+1
View File
@@ -4,6 +4,7 @@
// Package microbitmatrix implements a driver for the BBC micro:bit version 2 LED matrix. // Package microbitmatrix implements a driver for the BBC micro:bit version 2 LED matrix.
// //
// Schematic: // Schematic:
//
package microbitmatrix // import "tinygo.org/x/drivers/microbitmatrix" package microbitmatrix // import "tinygo.org/x/drivers/microbitmatrix"
import ( import (
+4 -3
View File
@@ -1,6 +1,7 @@
// Package microbitmatrix implements a driver for the BBC micro:bit's LED matrix. // Package microbitmatrix implements a driver for the BBC micro:bit's LED matrix.
// //
// Schematic: https://github.com/bbcmicrobit/hardware/blob/master/SCH_BBC-Microbit_V1.3B.pdf // Schematic: https://github.com/bbcmicrobit/hardware/blob/master/SCH_BBC-Microbit_V1.3B.pdf
//
package microbitmatrix // import "tinygo.org/x/drivers/microbitmatrix" package microbitmatrix // import "tinygo.org/x/drivers/microbitmatrix"
import ( import (
@@ -27,9 +28,9 @@ func (d *Device) SetPixel(x int16, y int16, c color.RGBA) {
return return
} }
if c.R != 0 || c.G != 0 || c.B != 0 { if c.R != 0 || c.G != 0 || c.B != 0 {
d.buffer[matrixRotations[d.rotation][y][x][0]][matrixRotations[d.rotation][y][x][1]] = true d.buffer[matrixRotations[d.rotation][x][y][0]][matrixRotations[d.rotation][x][y][1]] = true
} else { } else {
d.buffer[matrixRotations[d.rotation][y][x][0]][matrixRotations[d.rotation][y][x][1]] = false d.buffer[matrixRotations[d.rotation][x][y][0]][matrixRotations[d.rotation][x][y][1]] = false
} }
} }
@@ -38,5 +39,5 @@ func (d *Device) GetPixel(x int16, y int16) bool {
if x < 0 || x >= 5 || y < 0 || y >= 5 { if x < 0 || x >= 5 || y < 0 || y >= 5 {
return false return false
} }
return d.buffer[matrixRotations[d.rotation][y][x][0]][matrixRotations[d.rotation][y][x][1]] return d.buffer[matrixRotations[d.rotation][x][y][0]][matrixRotations[d.rotation][x][y][1]]
} }
+2
View File
@@ -2,6 +2,7 @@
// For example, the Adafruit PDM MEMS breakout board (https://www.adafruit.com/product/3492) // For example, the Adafruit PDM MEMS breakout board (https://www.adafruit.com/product/3492)
// //
// Datasheet: https://cdn-learn.adafruit.com/assets/assets/000/049/977/original/MP34DT01-M.pdf // Datasheet: https://cdn-learn.adafruit.com/assets/assets/000/049/977/original/MP34DT01-M.pdf
//
package microphone // import "tinygo.org/x/drivers/microphone" package microphone // import "tinygo.org/x/drivers/microphone"
import ( import (
@@ -140,6 +141,7 @@ func (d *Device) GetSoundPressure() (int32, int32) {
// for that sample. // for that sample.
// //
// For more information: https://en.wikipedia.org/wiki/Sinc_filter // For more information: https://en.wikipedia.org/wiki/Sinc_filter
//
var sincfilter = [quantizeSteps]uint16{ var sincfilter = [quantizeSteps]uint16{
0, 2, 9, 21, 39, 63, 94, 132, 0, 2, 9, 21, 39, 63, 94, 132,
179, 236, 302, 379, 467, 565, 674, 792, 179, 236, 302, 379, 467, 565, 674, 792,
+1
View File
@@ -3,6 +3,7 @@
// //
// Datasheet: // Datasheet:
// https://www.nxp.com/docs/en/data-sheet/MMA8653FC.pdf // https://www.nxp.com/docs/en/data-sheet/MMA8653FC.pdf
//
package mma8653 // import "tinygo.org/x/drivers/mma8653" package mma8653 // import "tinygo.org/x/drivers/mma8653"
import "tinygo.org/x/drivers" import "tinygo.org/x/drivers"
+1
View File
@@ -4,6 +4,7 @@
// Datasheets: // Datasheets:
// https://store.invensense.com/datasheets/invensense/MPU-6050_DataSheet_V3%204.pdf // https://store.invensense.com/datasheets/invensense/MPU-6050_DataSheet_V3%204.pdf
// https://www.invensense.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf // https://www.invensense.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf
//
package mpu6050 // import "tinygo.org/x/drivers/mpu6050" package mpu6050 // import "tinygo.org/x/drivers/mpu6050"
import "tinygo.org/x/drivers" import "tinygo.org/x/drivers"
+1
View File
@@ -33,6 +33,7 @@ import (
// with the expectation that the Jar will insert those mutated cookies // with the expectation that the Jar will insert those mutated cookies
// with the updated values (assuming the origin matches). // with the updated values (assuming the origin matches).
// If Jar is nil, the initial cookies are forwarded without change. // If Jar is nil, the initial cookies are forwarded without change.
//
type Client struct { type Client struct {
// Transport specifies the mechanism by which individual // Transport specifies the mechanism by which individual
// HTTP requests are made. // HTTP requests are made.
-2
View File
@@ -358,11 +358,9 @@ func sanitizeCookieName(n string) string {
// https://tools.ietf.org/html/rfc6265#section-4.1.1 // https://tools.ietf.org/html/rfc6265#section-4.1.1
// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) // cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E // cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
//
// ; US-ASCII characters excluding CTLs, // ; US-ASCII characters excluding CTLs,
// ; whitespace DQUOTE, comma, semicolon, // ; whitespace DQUOTE, comma, semicolon,
// ; and backslash // ; and backslash
//
// We loosen this as spaces and commas are common in cookie values // We loosen this as spaces and commas are common in cookie values
// but we produce a quoted cookie-value if and only if v contains // but we produce a quoted cookie-value if and only if v contains
// commas or spaces. // commas or spaces.
-3
View File
@@ -105,11 +105,8 @@ func (r *Response) Cookies() []*Cookie {
} }
// RFC 7234, section 5.4: Should treat // RFC 7234, section 5.4: Should treat
//
// Pragma: no-cache // Pragma: no-cache
//
// like // like
//
// Cache-Control: no-cache // Cache-Control: no-cache
func fixPragmaCacheControl(header Header) { func fixPragmaCacheControl(header Header) {
if hp, ok := header["Pragma"]; ok && len(hp) > 0 && hp[0] == "no-cache" { if hp, ok := header["Pragma"]; ok && len(hp) > 0 && hp[0] == "no-cache" {
+2 -2
View File
@@ -142,7 +142,7 @@ func Error(w ResponseWriter, error string, code int) {
func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) } func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
// NotFoundHandler returns a simple request handler // NotFoundHandler returns a simple request handler
// that replies to each request with a 404 page not found reply. // that replies to each request with a ``404 page not found'' reply.
func NotFoundHandler() Handler { return HandlerFunc(NotFound) } func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
// StripPrefix returns a handler that serves HTTP requests by removing the // StripPrefix returns a handler that serves HTTP requests by removing the
@@ -435,7 +435,7 @@ func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool {
// the pattern that will match after following the redirect. // the pattern that will match after following the redirect.
// //
// If there is no registered handler that applies to the request, // If there is no registered handler that applies to the request,
// Handler returns a page not found handler and an empty pattern. // Handler returns a ``page not found'' handler and an empty pattern.
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) { func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
// CONNECT requests are not canonicalized. // CONNECT requests are not canonicalized.
+22 -108
View File
@@ -5,7 +5,6 @@ package mqtt
import ( import (
"errors" "errors"
"strings" "strings"
"sync"
"time" "time"
"github.com/eclipse/paho.mqtt.golang/packets" "github.com/eclipse/paho.mqtt.golang/packets"
@@ -20,12 +19,6 @@ import (
func NewClient(o *ClientOptions) Client { func NewClient(o *ClientOptions) Client {
c := &mqttclient{opts: o, adaptor: o.Adaptor} c := &mqttclient{opts: o, adaptor: o.Adaptor}
c.msgRouter, c.stopRouter = newRouter() c.msgRouter, c.stopRouter = newRouter()
c.inboundPacketChan = make(chan packets.ControlPacket, 10)
c.stopInbound = make(chan struct{})
c.incomingPubChan = make(chan *packets.PublishPacket, 10)
// this launches a goroutine, so only call once per client:
c.msgRouter.matchAndDispatch(c.incomingPubChan, c.opts.Order, c)
return c return c
} }
@@ -35,17 +28,11 @@ type mqttclient struct {
connected bool connected bool
opts *ClientOptions opts *ClientOptions
mid uint16 mid uint16
inboundPacketChan chan packets.ControlPacket inbound chan packets.ControlPacket
stopInbound chan struct{} stop chan struct{}
msgRouter *router msgRouter *router
stopRouter chan bool stopRouter chan bool
incomingPubChan chan *packets.PublishPacket incomingPubChan chan *packets.PublishPacket
// stats for keepalive
lastReceive time.Time
lastSend time.Time
// keep track of routines and signal a shutdown
workers sync.WaitGroup
shutdown bool
} }
// AddRoute allows you to add a handler for messages on a specific topic // AddRoute allows you to add a handler for messages on a specific topic
@@ -69,9 +56,6 @@ func (c *mqttclient) IsConnectionOpen() bool {
// Connect will create a connection to the message broker. // Connect will create a connection to the message broker.
func (c *mqttclient) Connect() Token { func (c *mqttclient) Connect() Token {
if c.IsConnected() {
return &mqtttoken{}
}
var err error var err error
// make connection // make connection
@@ -93,6 +77,10 @@ func (c *mqttclient) Connect() Token {
} }
c.mid = 1 c.mid = 1
c.inbound = make(chan packets.ControlPacket, 10)
c.stop = make(chan struct{})
c.incomingPubChan = make(chan *packets.PublishPacket, 10)
c.msgRouter.matchAndDispatch(c.incomingPubChan, c.opts.Order, c)
// send the MQTT connect message // send the MQTT connect message
connectPkt := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket) connectPkt := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket)
@@ -110,7 +98,7 @@ func (c *mqttclient) Connect() Token {
connectPkt.ClientIdentifier = c.opts.ClientID connectPkt.ClientIdentifier = c.opts.ClientID
connectPkt.ProtocolVersion = byte(c.opts.ProtocolVersion) connectPkt.ProtocolVersion = byte(c.opts.ProtocolVersion)
connectPkt.ProtocolName = "MQTT" connectPkt.ProtocolName = "MQTT"
connectPkt.Keepalive = uint16(c.opts.KeepAlive) connectPkt.Keepalive = 60
connectPkt.WillFlag = c.opts.WillEnabled connectPkt.WillFlag = c.opts.WillEnabled
connectPkt.WillTopic = c.opts.WillTopic connectPkt.WillTopic = c.opts.WillTopic
@@ -122,7 +110,6 @@ func (c *mqttclient) Connect() Token {
if err != nil { if err != nil {
return &mqtttoken{err: err} return &mqtttoken{err: err}
} }
c.lastSend = time.Now()
// TODO: handle timeout as ReadPacket blocks until it gets a packet. // TODO: handle timeout as ReadPacket blocks until it gets a packet.
// CONNECT response. // CONNECT response.
@@ -140,34 +127,18 @@ func (c *mqttclient) Connect() Token {
} }
} }
go processInbound(c)
go readMessages(c) go readMessages(c)
go keepAlive(c) go processInbound(c)
return &mqtttoken{} return &mqtttoken{}
} }
// Disconnect will end the connection with the server, but not before waiting // Disconnect will end the connection with the server, but not before waiting
// the specified number of milliseconds to wait for existing work to be // the specified number of milliseconds to wait for existing work to be
// completed. Blocks until disconnected. // completed.
func (c *mqttclient) Disconnect(quiesce uint) { func (c *mqttclient) Disconnect(quiesce uint) {
c.shutdownRoutines()
// block until all done
for c.connected {
time.Sleep(time.Millisecond * 10)
}
return
}
// shutdownRoutines will disconnect and shut down all processes. If you want to trigger a
// disconnect internally, make sure you call this instead of Disconnect() to avoid deadlocks
func (c *mqttclient) shutdownRoutines() {
if c.shutdown {
return
}
c.shutdown = true
c.conn.Close() c.conn.Close()
c.stopInbound <- struct{}{} return
} }
// Publish will publish a message with the specified QoS and content // Publish will publish a message with the specified QoS and content
@@ -182,7 +153,6 @@ func (c *mqttclient) Publish(topic string, qos byte, retained bool, payload inte
pub.Qos = qos pub.Qos = qos
pub.TopicName = topic pub.TopicName = topic
pub.Retain = retained pub.Retain = retained
switch payload.(type) { switch payload.(type) {
case string: case string:
pub.Payload = []byte(payload.(string)) pub.Payload = []byte(payload.(string))
@@ -198,8 +168,6 @@ func (c *mqttclient) Publish(topic string, qos byte, retained bool, payload inte
if err != nil { if err != nil {
return &mqtttoken{err: err} return &mqtttoken{err: err}
} }
// update this for every control message that is sent successfully, for keepalive
c.lastSend = time.Now()
return &mqtttoken{} return &mqtttoken{}
} }
@@ -227,7 +195,6 @@ func (c *mqttclient) Subscribe(topic string, qos byte, callback MessageHandler)
if err != nil { if err != nil {
return &mqtttoken{err: err} return &mqtttoken{err: err}
} }
c.lastSend = time.Now()
return &mqtttoken{} return &mqtttoken{}
} }
@@ -253,13 +220,12 @@ func (c *mqttclient) OptionsReader() ClientOptionsReader {
} }
func processInbound(c *mqttclient) { func processInbound(c *mqttclient) {
PROCESS:
for { for {
select { select {
case msg := <-c.inboundPacketChan: case msg := <-c.inbound:
switch m := msg.(type) { switch m := msg.(type) {
case *packets.PingrespPacket: case *packets.PingrespPacket:
// println("pong") // TODO: handle this
case *packets.SubackPacket: case *packets.SubackPacket:
// TODO: handle this // TODO: handle this
case *packets.UnsubackPacket: case *packets.UnsubackPacket:
@@ -276,85 +242,33 @@ PROCESS:
case *packets.PubcompPacket: case *packets.PubcompPacket:
// TODO: handle this // TODO: handle this
} }
case <-c.stopInbound: case <-c.stop:
break PROCESS return
} }
} }
// as this routine could be the last to finish (if a lot of messages are queued in the
// channel), it is the last to turn out the lights
c.workers.Wait()
c.connected = false
c.shutdown = false
} }
// readMessages reads incoming messages off the wire. // readMessages reads incoming messages off the wire.
// incoming messages are then send into inbound buffered channel. // incoming messages are then send into inbound channel.
func readMessages(c *mqttclient) { func readMessages(c *mqttclient) {
c.workers.Add(1)
defer c.workers.Done()
var err error var err error
var cp packets.ControlPacket var cp packets.ControlPacket
for !c.shutdown { PROCESS:
for {
if cp, err = c.ReadPacket(); err != nil { if cp, err = c.ReadPacket(); err != nil {
c.shutdownRoutines() break PROCESS
return
} }
if cp != nil { if cp != nil {
c.inboundPacketChan <- cp c.inbound <- cp
// notify keepalive logic that we recently received a packet // TODO: Notify keepalive logic that we recently received a packet
c.lastReceive = time.Now()
} }
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
} }
}
// keepAlive is a goroutine to handle sending ping requests according to the MQTT spec. If the keepalive time has // TODO: handle if we received an error on read.
// been reached with no messages being sent, we will send a ping request and check back to see if we've // If disconnect is in progress, swallow error and return
// had any activity by the timeout. If not, disconnect.
func keepAlive(c *mqttclient) {
c.workers.Add(1)
defer c.workers.Done()
var err error
var ping *packets.PingreqPacket
var timeout, pingsent time.Time
for !c.shutdown {
// As long as we haven't reached the keepalive value...
if time.Since(c.lastSend) < time.Duration(c.opts.KeepAlive)*time.Second {
// ...sleep and check shutdown status again
time.Sleep(time.Millisecond * 100)
continue
}
// value has been reached, so send a ping request
ping = packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket)
if err = ping.Write(c.conn); err != nil {
// if connection is lost, report disconnect
c.shutdownRoutines()
return
}
// println("ping")
c.lastSend = time.Now()
pingsent = time.Now()
timeout = pingsent.Add(c.opts.PingTimeout)
// as long as we are still connected and haven't received anything after the ping...
for !c.shutdown && c.lastReceive.Before(pingsent) {
// if the timeout has passed, disconnect
if time.Now().After(timeout) {
c.shutdownRoutines()
return
}
time.Sleep(time.Millisecond * 100)
}
}
} }
func (c *mqttclient) ackFunc(packet *packets.PublishPacket) func() { func (c *mqttclient) ackFunc(packet *packets.PublishPacket) func() {
+1 -20
View File
@@ -42,11 +42,9 @@ const (
// with an MQTT server using non-blocking methods that allow work // with an MQTT server using non-blocking methods that allow work
// to be done in the background. // to be done in the background.
// An application may connect to an MQTT server using: // An application may connect to an MQTT server using:
//
// A plain TCP socket // A plain TCP socket
// A secure SSL/TLS socket // A secure SSL/TLS socket
// A websocket // A websocket
//
// To enable ensured message delivery at Quality of Service (QoS) levels // To enable ensured message delivery at Quality of Service (QoS) levels
// described in the MQTT spec, a message persistence mechanism must be // described in the MQTT spec, a message persistence mechanism must be
// used. This is done by providing a type which implements the Store // used. This is done by providing a type which implements the Store
@@ -212,7 +210,7 @@ type ClientOptions struct {
// NewClientOptions returns a new ClientOptions struct. // NewClientOptions returns a new ClientOptions struct.
func NewClientOptions() *ClientOptions { func NewClientOptions() *ClientOptions {
return &ClientOptions{Adaptor: net.ActiveDevice, ProtocolVersion: 4, KeepAlive: 60, PingTimeout: time.Second * 10} return &ClientOptions{Adaptor: net.ActiveDevice, ProtocolVersion: 4}
} }
// AddBroker adds a broker URI to the list of brokers to be used. The format should be // AddBroker adds a broker URI to the list of brokers to be used. The format should be
@@ -259,23 +257,6 @@ func (o *ClientOptions) SetPassword(p string) *ClientOptions {
return o return o
} }
// SetKeepAlive will set the amount of time (in seconds) that the client
// should wait before sending a PING request to the broker. This will
// allow the client to know that a connection has not been lost with the
// server.
func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions {
o.KeepAlive = int64(k / time.Second)
return o
}
// SetPingTimeout will set the amount of time (in seconds) that the client
// will wait after sending a PING request to the broker, before deciding
// that the connection has been lost. Default is 10 seconds.
func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions {
o.PingTimeout = k
return o
}
// SetWill accepts a string will message to be set. When the client connects, // SetWill accepts a string will message to be set. When the client connects,
// it will give this will message to the broker, which will then publish the // it will give this will message to the broker, which will then publish the
// provided payload (the will) to any clients that are subscribed to the provided // provided payload (the will) to any clients that are subscribed to the provided
+2
View File
@@ -234,6 +234,7 @@ func (c *SerialConn) SetWriteDeadline(t time.Time) error {
// ResolveTCPAddr returns an address of TCP end point. // ResolveTCPAddr returns an address of TCP end point.
// //
// The network must be a TCP network name. // The network must be a TCP network name.
//
func ResolveTCPAddr(network, address string) (*TCPAddr, error) { func ResolveTCPAddr(network, address string) (*TCPAddr, error) {
// TODO: make sure network is 'tcp' // TODO: make sure network is 'tcp'
// separate domain from port, if any // separate domain from port, if any
@@ -256,6 +257,7 @@ func ResolveTCPAddr(network, address string) (*TCPAddr, error) {
// ResolveUDPAddr returns an address of UDP end point. // ResolveUDPAddr returns an address of UDP end point.
// //
// The network must be a UDP network name. // The network must be a UDP network name.
//
func ResolveUDPAddr(network, address string) (*UDPAddr, error) { func ResolveUDPAddr(network, address string) (*UDPAddr, error) {
// TODO: make sure network is 'udp' // TODO: make sure network is 'udp'
// separate domain from port, if any // separate domain from port, if any
-5
View File
@@ -91,9 +91,7 @@ func (d Dev) Top() uint32 {
// Set sets the `on` value of a PWM channel in the range [0..15]. // Set sets the `on` value of a PWM channel in the range [0..15].
// Max value `on` can take is 4095. // Max value `on` can take is 4095.
// Example: // Example:
//
// d.Set(1, d.Top()/4) // d.Set(1, d.Top()/4)
//
// sets the dutycycle of second (LED1) channel to 25%. // sets the dutycycle of second (LED1) channel to 25%.
func (d Dev) Set(channel uint8, on uint32) { func (d Dev) Set(channel uint8, on uint32) {
if on > maxtop { if on > maxtop {
@@ -103,7 +101,6 @@ func (d Dev) Set(channel uint8, on uint32) {
} }
// SetAll sets all PWM signals to a ON value. Equivalent of calling // SetAll sets all PWM signals to a ON value. Equivalent of calling
//
// Dev.Set(pca9685.ALLLED, value) // Dev.Set(pca9685.ALLLED, value)
func (d Dev) SetAll(on uint32) { func (d Dev) SetAll(on uint32) {
d.Set(ALLLED, on) d.Set(ALLLED, on)
@@ -143,7 +140,6 @@ func (d Dev) SetAI(ai bool) error {
} }
// SetDrive configures PWM output connection in MODE2 register. // SetDrive configures PWM output connection in MODE2 register.
//
// false: The 16 LEDn outputs are configured with an open-drain structure. // false: The 16 LEDn outputs are configured with an open-drain structure.
// true: The 16 LEDn outputs are configured with a totem pole structure. // true: The 16 LEDn outputs are configured with a totem pole structure.
func (d Dev) SetDrive(outdrv bool) error { func (d Dev) SetDrive(outdrv bool) error {
@@ -160,7 +156,6 @@ func (d Dev) SetDrive(outdrv bool) error {
} }
// Sleep sets/unsets SLEEP bit in MODE1. // Sleep sets/unsets SLEEP bit in MODE1.
//
// if sleepEnabled // if sleepEnabled
// Stops PWM. Allows writing to PRE_SCALE register. // Stops PWM. Allows writing to PRE_SCALE register.
// else // else

Some files were not shown because too many files have changed in this diff Show More