Checkpoint
This commit is contained in:
125 files changed
+59376
No files matched your search
@@ -0,0 +1,264 @@
|
||||
package lcdproc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/textproto"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.maze.io/go/bragi/config"
|
||||
"git.maze.io/go/bragi/display"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultPort = "13666"
|
||||
DefaultAddr = "localhost:" + DefaultPort
|
||||
screenName = "bragi"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
Version string
|
||||
ProtocolVersion string
|
||||
|
||||
addr string
|
||||
conn *textproto.Conn
|
||||
width, height int
|
||||
cellWidth, cellHeight int
|
||||
text [][]byte
|
||||
}
|
||||
|
||||
func New(config *config.Display) (display.Text, error) {
|
||||
var (
|
||||
addr, host, port string
|
||||
err error
|
||||
)
|
||||
if host = config.Host; host == "" {
|
||||
host = "localhost"
|
||||
}
|
||||
if port = config.Port; port == "" {
|
||||
port = DefaultPort
|
||||
}
|
||||
addr = net.JoinHostPort(host, port)
|
||||
|
||||
log := logrus.WithFields(logrus.Fields{
|
||||
"driver": "lcdproc",
|
||||
"addr": addr,
|
||||
})
|
||||
log.Debug("connecting to server")
|
||||
|
||||
conn, err := textproto.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := &Client{
|
||||
addr: addr,
|
||||
conn: conn,
|
||||
}
|
||||
if err = c.hello(log); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = c.setup(log); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.text = make([][]byte, c.height)
|
||||
for i := 0; i < c.height; i++ {
|
||||
c.text[i] = make([]byte, c.width)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Client) hello(log *logrus.Entry) (err error) {
|
||||
log.Trace("sending hello")
|
||||
var id uint
|
||||
if id, err = c.conn.Cmd("hello"); err != nil {
|
||||
return
|
||||
}
|
||||
c.conn.StartResponse(id)
|
||||
defer c.conn.EndResponse(id)
|
||||
|
||||
var line string
|
||||
if line, err = c.conn.ReadLine(); err != nil {
|
||||
return
|
||||
}
|
||||
log.WithFields(logrus.Fields{
|
||||
"data": line,
|
||||
"id": id,
|
||||
}).Trace("recieved response")
|
||||
|
||||
var parts = strings.Split(line, " ")
|
||||
for i := 0; i < len(parts); i++ {
|
||||
switch part := parts[i]; part {
|
||||
case "connect":
|
||||
i++ // ignore "LCDproc"
|
||||
c.Version = parts[i]
|
||||
i++
|
||||
log.Debugf("received version %s", c.Version)
|
||||
case "protocol":
|
||||
i++
|
||||
c.ProtocolVersion = parts[i]
|
||||
log.Debugf("received protocol version %s", c.ProtocolVersion)
|
||||
case "lcd": // ignore
|
||||
case "wid":
|
||||
i++
|
||||
c.width, _ = strconv.Atoi(parts[i])
|
||||
case "hgt":
|
||||
i++
|
||||
c.height, _ = strconv.Atoi(parts[i])
|
||||
case "cellwid":
|
||||
i++
|
||||
c.cellWidth, _ = strconv.Atoi(parts[i])
|
||||
case "cellhgt":
|
||||
i++
|
||||
c.cellHeight, _ = strconv.Atoi(parts[i])
|
||||
}
|
||||
}
|
||||
|
||||
log.Debugf("%dx%d display", c.width*c.cellWidth, c.height*c.cellHeight)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) setup(log *logrus.Entry) (err error) {
|
||||
if err = c.sendCommand("client_set -name Bragi"); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = c.fireCommand("screen_del %s", screenName); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = c.fireCommand("screen_add %s", screenName); err != nil {
|
||||
return
|
||||
}
|
||||
if err = c.sendCommand("screen_set %s -cursor off -heartbeat off -priority foreground -duration -wid %d -hgt %d", screenName, c.width, c.height); err != nil {
|
||||
return
|
||||
}
|
||||
for y := 0; y < c.height; y++ {
|
||||
if err = c.sendCommand("widget_add %s row%d string", screenName, y); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) log() *logrus.Entry {
|
||||
return logrus.WithFields(logrus.Fields{
|
||||
"driver": "lcdproc",
|
||||
"addr": c.addr,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) sendCommand(format string, args ...interface{}) (err error) {
|
||||
log := c.log().WithField("command", fmt.Sprintf(format, args...))
|
||||
log.Debug("sending command")
|
||||
|
||||
var id uint
|
||||
if id, err = c.conn.Cmd(format, args...); err != nil {
|
||||
return
|
||||
}
|
||||
c.conn.StartResponse(id)
|
||||
defer c.conn.EndResponse(id)
|
||||
|
||||
log = log.WithField("id", id)
|
||||
log.Trace("reading response")
|
||||
for {
|
||||
var line string
|
||||
if line, err = c.conn.ReadLine(); err != nil {
|
||||
log.WithError(err).Error("error reading response")
|
||||
c.conn.EndResponse(id)
|
||||
return
|
||||
}
|
||||
|
||||
log.WithField("data", line).Trace("response")
|
||||
switch {
|
||||
case line == "success":
|
||||
return
|
||||
case strings.HasPrefix(line, "huh? "):
|
||||
return textproto.ProtocolError(line[5:])
|
||||
case strings.HasPrefix(line, "listen "):
|
||||
continue
|
||||
case strings.HasPrefix(line, "ignore "):
|
||||
continue
|
||||
default:
|
||||
return textproto.ProtocolError("unexpected response: " + line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) fireCommand(format string, args ...interface{}) (err error) {
|
||||
log := c.log().WithField("command", fmt.Sprintf(format, args...))
|
||||
log.Debug("sending command")
|
||||
|
||||
var id uint
|
||||
if id, err = c.conn.Cmd(format, args...); err != nil {
|
||||
return
|
||||
}
|
||||
c.conn.StartResponse(id)
|
||||
defer c.conn.EndResponse(id)
|
||||
|
||||
log = log.WithField("id", id)
|
||||
log.Trace("reading response")
|
||||
for {
|
||||
var line string
|
||||
if line, err = c.conn.ReadLine(); err != nil {
|
||||
log.WithError(err).Error("error reading response")
|
||||
c.conn.EndResponse(id)
|
||||
return
|
||||
}
|
||||
|
||||
log.WithField("data", line).Trace("response")
|
||||
switch {
|
||||
case line == "success":
|
||||
return
|
||||
case strings.HasPrefix(line, "huh? "):
|
||||
return
|
||||
case strings.HasPrefix(line, "listen "):
|
||||
continue
|
||||
case strings.HasPrefix(line, "ignore "):
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) String() string {
|
||||
return fmt.Sprintf("lcdproc %s at %s", c.Version, c.addr)
|
||||
}
|
||||
|
||||
func (c *Client) Columns() int {
|
||||
return c.width
|
||||
}
|
||||
|
||||
func (c *Client) Rows() int {
|
||||
return c.height
|
||||
}
|
||||
|
||||
func (c *Client) Halt() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
func (Client) Refresh() error { return nil }
|
||||
|
||||
func (c *Client) Size() (w, h int) {
|
||||
return c.width * c.cellWidth, c.height * c.cellHeight
|
||||
}
|
||||
|
||||
func (c *Client) Text(x, y int, message string) {
|
||||
w := len(message)
|
||||
if x+w > c.width {
|
||||
message = message[:c.width-x]
|
||||
}
|
||||
_ = c.fireCommand("widget_set %s main %d %d %q", screenName, x+1, y+1, message)
|
||||
}
|
||||
|
||||
func init() {
|
||||
display.Register("lcdproc", func(config *config.Display) (display.Display, error) {
|
||||
return New(config)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package sdl
|
||||
|
||||
import "git.maze.io/go/harmon/input"
|
||||
|
||||
type keyboardInput struct {
|
||||
//events chan *sdl.KeyboardEvent
|
||||
events chan input.Event
|
||||
}
|
||||
|
||||
func newKeyboardInput() *keyboardInput {
|
||||
return &keyboardInput{
|
||||
events: make(chan input.Event),
|
||||
}
|
||||
}
|
||||
|
||||
func (keyboardInput) Name() string {
|
||||
return "keyboard"
|
||||
}
|
||||
|
||||
func (k *keyboardInput) Events() (<-chan input.Event, error) {
|
||||
return k.events, nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package sdl
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/veandco/go-sdl2/sdl"
|
||||
|
||||
"git.maze.io/go/harmon/input"
|
||||
)
|
||||
|
||||
var (
|
||||
initOnce sync.Once
|
||||
initTime time.Time
|
||||
quitOnce sync.Once
|
||||
)
|
||||
|
||||
type Device struct {
|
||||
window *sdl.Window
|
||||
surface *sdl.Surface
|
||||
keyboardInput *keyboardInput
|
||||
}
|
||||
|
||||
func New() (*Device, error) {
|
||||
var err error
|
||||
initOnce.Do(func() {
|
||||
err = sdl.Init(sdl.INIT_EVERYTHING)
|
||||
if err == nil {
|
||||
initTime = time.Now()
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
b int32 = 32
|
||||
w int32 = 256
|
||||
h int32 = 32
|
||||
)
|
||||
|
||||
window, err := sdl.CreateWindow("Bragi OLED emulator",
|
||||
sdl.WINDOWPOS_UNDEFINED,
|
||||
sdl.WINDOWPOS_UNDEFINED,
|
||||
w+2*b,
|
||||
h+2*b,
|
||||
sdl.WINDOW_SHOWN)
|
||||
if err != nil {
|
||||
sdl.Quit()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
surface, err := window.GetSurface()
|
||||
if err != nil {
|
||||
_ = window.Destroy()
|
||||
sdl.Quit()
|
||||
return nil, err
|
||||
}
|
||||
surface.FillRect(nil, 0)
|
||||
|
||||
surface.FillRect(&sdl.Rect{0, 0, b + b + w, b + b + h}, sdl.MapRGBA(surface.Format, 128, 64, 0, 255))
|
||||
surface.FillRect(&sdl.Rect{b, b, w, h}, sdl.MapRGBA(surface.Format, 255, 128, 0, 255))
|
||||
window.UpdateSurface()
|
||||
|
||||
d := &Device{
|
||||
window: window,
|
||||
surface: surface,
|
||||
keyboardInput: newKeyboardInput(),
|
||||
}
|
||||
|
||||
input.Register(func() ([]input.Source, error) {
|
||||
return []input.Source{
|
||||
d.keyboardInput,
|
||||
}, nil
|
||||
})
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *Device) Close() error {
|
||||
err := d.window.Destroy()
|
||||
quitOnce.Do(sdl.Quit)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Device) Run() error {
|
||||
for running := true; running; {
|
||||
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
|
||||
switch event := event.(type) {
|
||||
case *sdl.QuitEvent:
|
||||
running = false
|
||||
break
|
||||
|
||||
case *sdl.KeyboardEvent:
|
||||
d.handleKeyboardEvent(event)
|
||||
|
||||
case *sdl.MouseMotionEvent:
|
||||
//select {
|
||||
//case d.mouseMotionEvents <- event:
|
||||
//default:
|
||||
//}
|
||||
|
||||
default:
|
||||
log.Printf("SDL event: %T", event)
|
||||
}
|
||||
}
|
||||
}
|
||||
return d.Close()
|
||||
}
|
||||
|
||||
func (d *Device) handleKeyboardEvent(event *sdl.KeyboardEvent) {
|
||||
/*
|
||||
var kind input.EventType
|
||||
switch event.Type {
|
||||
case sdl.KEYDOWN:
|
||||
kind = input.KeyPress
|
||||
case sdl.KEYUP:
|
||||
kind = input.KeyRelease
|
||||
}
|
||||
d.keyboardInput.events <- input.Event{
|
||||
Type: kind,
|
||||
Time: initTime.Add(time.Duration(event.Timestamp) * time.Second),
|
||||
Code: int(event.Keysym.Sym),
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package ssd1306
|
||||
|
||||
import "git.maze.io/go/harmon/display"
|
||||
|
||||
// Registers
|
||||
const (
|
||||
Address = 0x3D
|
||||
Address_128_32 = 0x3C
|
||||
|
||||
SETCONTRAST = 0x81
|
||||
DISPLAYALLON_RESUME = 0xA4
|
||||
DISPLAYALLON = 0xA5
|
||||
NORMALDISPLAY = 0xA6
|
||||
INVERTDISPLAY = 0xA7
|
||||
DISPLAYOFF = 0xAE
|
||||
DISPLAYON = 0xAF
|
||||
SETDISPLAYOFFSET = 0xD3
|
||||
SETCOMPINS = 0xDA
|
||||
SETVCOMDETECT = 0xDB
|
||||
SETDISPLAYCLOCKDIV = 0xD5
|
||||
SETPRECHARGE = 0xD9
|
||||
SETMULTIPLEX = 0xA8
|
||||
SETLOWCOLUMN = 0x00
|
||||
SETHIGHCOLUMN = 0x10
|
||||
SETSTARTLINE = 0x40
|
||||
MEMORYMODE = 0x20
|
||||
COLUMNADDR = 0x21
|
||||
PAGEADDR = 0x22
|
||||
COMSCANINC = 0xC0
|
||||
COMSCANDEC = 0xC8
|
||||
SEGREMAP = 0xA0
|
||||
CHARGEPUMP = 0x8D
|
||||
ACTIVATE_SCROLL = 0x2F
|
||||
DEACTIVATE_SCROLL = 0x2E
|
||||
SET_VERTICAL_SCROLL_AREA = 0xA3
|
||||
RIGHT_HORIZONTAL_SCROLL = 0x26
|
||||
LEFT_HORIZONTAL_SCROLL = 0x27
|
||||
VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29
|
||||
VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A
|
||||
|
||||
EXTERNALVCC VccMode = 0x1
|
||||
SWITCHCAPVCC VccMode = 0x2
|
||||
|
||||
NO_ROTATION = display.NoRotation
|
||||
ROTATION_180 = display.Rotate180
|
||||
)
|
||||
@@ -0,0 +1,411 @@
|
||||
package ssd1306
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"time"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/display/oled"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("ssd1306", newDevice)
|
||||
}
|
||||
|
||||
var (
|
||||
errBufferSize = errors.New("invalid size buffer")
|
||||
errOutOfRange = errors.New("out of screen range")
|
||||
)
|
||||
|
||||
type ResetValue [2]byte
|
||||
|
||||
// Device wraps I2C or SPI connection.
|
||||
type Device struct {
|
||||
bus oled.Bus
|
||||
buffer pixel.Image[pixel.Monochrome]
|
||||
width int16
|
||||
height int16
|
||||
bufferSize int16
|
||||
vccState VccMode
|
||||
canReset bool
|
||||
resetCol ResetValue
|
||||
resetPage ResetValue
|
||||
rotation display.Rotation
|
||||
}
|
||||
|
||||
// Config is the configuration for the display
|
||||
type Config struct {
|
||||
Width int16
|
||||
Height int16
|
||||
VccState VccMode
|
||||
//Address uint16
|
||||
// ResetCol and ResetPage are used to reset the screen to 0x0
|
||||
// This is useful for some screens that have a different size than 128x64
|
||||
// For example, the Thumby's screen is 72x40
|
||||
// The default values are normally set automatically based on the size.
|
||||
// If you're using a different size, you might need to set these values manually.
|
||||
ResetCol ResetValue
|
||||
ResetPage ResetValue
|
||||
Rotation display.Rotation
|
||||
}
|
||||
|
||||
type VccMode uint8
|
||||
|
||||
func newDevice(config *config.Display) (display.Display, error) {
|
||||
width, height, err := display.ParseSize(config.Size, 128, 0)
|
||||
if err != nil || height == 0 {
|
||||
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||
}
|
||||
|
||||
rotation, err := display.ParseRotation(config.Rotate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bus, err := oled.NewBus(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := &Device{
|
||||
bus: bus,
|
||||
}
|
||||
if err = d.Configure(Config{
|
||||
Width: int16(width),
|
||||
Height: int16(height),
|
||||
Rotation: rotation,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Configure initializes the display with default configuration
|
||||
func (d *Device) Configure(cfg Config) error {
|
||||
var zeroReset ResetValue
|
||||
if cfg.Width != 0 {
|
||||
d.width = cfg.Width
|
||||
} else {
|
||||
d.width = 128
|
||||
}
|
||||
if cfg.Height != 0 {
|
||||
d.height = cfg.Height
|
||||
} else {
|
||||
d.height = 64
|
||||
}
|
||||
if cfg.VccState != 0 {
|
||||
d.vccState = cfg.VccState
|
||||
} else {
|
||||
d.vccState = SWITCHCAPVCC
|
||||
}
|
||||
if cfg.ResetCol != zeroReset {
|
||||
d.resetCol = cfg.ResetCol
|
||||
} else {
|
||||
d.resetCol = ResetValue{0, uint8(d.width - 1)}
|
||||
}
|
||||
if cfg.ResetPage != zeroReset {
|
||||
d.resetPage = cfg.ResetPage
|
||||
} else {
|
||||
d.resetPage = ResetValue{0, uint8(d.height/8) - 1}
|
||||
}
|
||||
d.bufferSize = d.width * d.height / 8
|
||||
d.buffer = pixel.NewImage[pixel.Monochrome](int(d.width), int(d.height))
|
||||
//d.buffer = make([]byte, d.bufferSize)
|
||||
//d.canReset = cfg.Address != 0 || d.width != 128 || d.height != 64 // I2C or not 128x64
|
||||
|
||||
time.Sleep(100 * time.Nanosecond)
|
||||
d.Command(DISPLAYOFF)
|
||||
d.Command(SETDISPLAYCLOCKDIV)
|
||||
d.Command(0x80)
|
||||
d.Command(SETMULTIPLEX)
|
||||
d.Command(uint8(d.height - 1))
|
||||
d.Command(SETDISPLAYOFFSET)
|
||||
d.Command(0x0)
|
||||
d.Command(SETSTARTLINE | 0x0)
|
||||
d.Command(CHARGEPUMP)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x10)
|
||||
} else {
|
||||
d.Command(0x14)
|
||||
}
|
||||
d.Command(MEMORYMODE)
|
||||
d.Command(0x00)
|
||||
|
||||
d.SetRotation(cfg.Rotation)
|
||||
|
||||
if (d.width == 128 && d.height == 64) || (d.width == 64 && d.height == 48) { // 128x64 or 64x48
|
||||
d.Command(SETCOMPINS)
|
||||
d.Command(0x12)
|
||||
d.Command(SETCONTRAST)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x9F)
|
||||
} else {
|
||||
d.Command(0xCF)
|
||||
}
|
||||
} else if d.width == 128 && d.height == 32 { // 128x32
|
||||
d.Command(SETCOMPINS)
|
||||
d.Command(0x02)
|
||||
d.Command(SETCONTRAST)
|
||||
d.Command(0x8F)
|
||||
} else if d.width == 96 && d.height == 16 { // 96x16
|
||||
d.Command(SETCOMPINS)
|
||||
d.Command(0x2)
|
||||
d.Command(SETCONTRAST)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x10)
|
||||
} else {
|
||||
d.Command(0xAF)
|
||||
}
|
||||
} else {
|
||||
// fail silently, it might work
|
||||
println("there's no configuration for this display's size")
|
||||
}
|
||||
|
||||
d.Command(SETPRECHARGE)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x22)
|
||||
} else {
|
||||
d.Command(0xF1)
|
||||
}
|
||||
d.Command(SETVCOMDETECT)
|
||||
d.Command(0x40)
|
||||
d.Command(DISPLAYALLON_RESUME)
|
||||
d.Command(NORMALDISPLAY)
|
||||
d.Command(DEACTIVATE_SCROLL)
|
||||
return d.Command(DISPLAYON)
|
||||
}
|
||||
|
||||
// ClearBuffer clears the image buffer
|
||||
func (d *Device) ClearBuffer() {
|
||||
/*
|
||||
for i := int16(0); i < d.bufferSize; i++ {
|
||||
d.buffer[i] = 0
|
||||
}
|
||||
*/
|
||||
d.buffer.Clear()
|
||||
}
|
||||
|
||||
// ClearDisplay clears the image buffer and clear the display
|
||||
func (d *Device) ClearDisplay() error {
|
||||
d.ClearBuffer()
|
||||
return d.Refresh()
|
||||
}
|
||||
|
||||
// Refresh sends the whole buffer to the screen
|
||||
func (d *Device) Refresh() error {
|
||||
// Reset the screen to 0x0
|
||||
// This works fine with I2C
|
||||
// In the 128x64 (SPI) screen resetting to 0x0 after 128 times corrupt the buffer
|
||||
// Since we're printing the whole buffer, avoid resetting it in this case
|
||||
if d.canReset {
|
||||
d.Command(COLUMNADDR)
|
||||
d.Command(d.resetCol[0])
|
||||
d.Command(d.resetCol[1])
|
||||
d.Command(PAGEADDR)
|
||||
d.Command(d.resetPage[0])
|
||||
d.Command(d.resetPage[1])
|
||||
}
|
||||
|
||||
return d.Tx(d.buffer.RawBuffer(), false)
|
||||
}
|
||||
|
||||
// SetPixel enables or disables a pixel in the buffer
|
||||
// color.RGBA{0, 0, 0, 255} is consider transparent, anything else
|
||||
// with enable a pixel on the screen
|
||||
func (d *Device) SetPixel(x int16, y int16, c pixel.Monochrome) {
|
||||
if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 {
|
||||
x, y = y, x
|
||||
}
|
||||
/*
|
||||
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||
return
|
||||
}
|
||||
byteIndex := x + (y/8)*d.width
|
||||
if c == pixel.Off {
|
||||
d.buffer[byteIndex] &^= 1 << uint8(y%8)
|
||||
} else {
|
||||
d.buffer[byteIndex] |= 1 << uint8(y%8)
|
||||
}
|
||||
*/
|
||||
d.buffer.SetPixel(int(x), int(y), c)
|
||||
}
|
||||
|
||||
// GetPixel returns if the specified pixel is on (true) or off (false)
|
||||
func (d *Device) GetPixel(x int16, y int16) pixel.Monochrome {
|
||||
if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 {
|
||||
x, y = y, x
|
||||
}
|
||||
/*
|
||||
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||
return false
|
||||
}
|
||||
byteIndex := x + (y/8)*d.width
|
||||
return (d.buffer[byteIndex] >> uint8(y%8) & 0x1) == 1
|
||||
*/
|
||||
return d.buffer.GetPixel(int(x), int(y))
|
||||
}
|
||||
|
||||
/*
|
||||
// SetBuffer changes the whole buffer at once
|
||||
func (d *Device) SetBuffer(buffer []byte) error {
|
||||
if int16(len(buffer)) != d.bufferSize {
|
||||
return errBufferSize
|
||||
}
|
||||
for i := int16(0); i < d.bufferSize; i++ {
|
||||
d.buffer[i] = buffer[i]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
*/
|
||||
|
||||
// GetBuffer returns the whole buffer
|
||||
func (d *Device) GetBuffer() []byte {
|
||||
return d.buffer.RawBuffer()
|
||||
}
|
||||
|
||||
// Command sends a command to the display
|
||||
func (d *Device) Command(command uint8) error {
|
||||
return d.bus.Tx([]byte{command}, true)
|
||||
}
|
||||
|
||||
// Tx sends data to the display
|
||||
func (d *Device) Tx(data []byte, isCommand bool) error {
|
||||
return d.bus.Tx(data, isCommand)
|
||||
}
|
||||
|
||||
// Size returns the current size of the display.
|
||||
func (d *Device) Size16() (w, h int16) {
|
||||
return d.width, d.height
|
||||
}
|
||||
|
||||
// DrawBitmap copies the bitmap to the screen at the given coordinates.
|
||||
func (d *Device) DrawBitmap(x, y int16, bitmap pixel.Image[pixel.Monochrome]) error {
|
||||
width, height := bitmap.Size()
|
||||
if x < 0 || x+int16(width) > d.width || y < 0 || y+int16(height) > d.height {
|
||||
return errOutOfRange
|
||||
}
|
||||
|
||||
for i := 0; i < width; i++ {
|
||||
for j := 0; j < height; j++ {
|
||||
d.SetPixel(x+int16(i), y+int16(j), bitmap.GetPixel(i, j))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rotation returns the currently configured rotation.
|
||||
func (d *Device) Rotation() display.Rotation {
|
||||
return d.rotation
|
||||
}
|
||||
|
||||
// SetRotation changes the rotation of the device (clock-wise).
|
||||
func (d *Device) SetRotation(rotation display.Rotation) error {
|
||||
d.rotation = rotation
|
||||
switch d.rotation {
|
||||
case display.NoRotation:
|
||||
d.Command(SEGREMAP | 0x1) // Reverse horizontal mapping
|
||||
d.Command(COMSCANDEC) // Reverse vertical mapping
|
||||
case display.Rotate180:
|
||||
d.Command(SEGREMAP) // Normal horizontal mapping
|
||||
d.Command(COMSCANINC) // Normal vertical mapping
|
||||
// nothing to do
|
||||
default:
|
||||
d.Command(SEGREMAP | 0x1) // Reverse horizontal mapping
|
||||
d.Command(COMSCANDEC) // Reverse vertical mapping
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set the sleep mode for this display. When sleeping, the panel uses a lot
|
||||
// less power. The display won't show an image anymore, but the memory contents
|
||||
// should be kept.
|
||||
func (d *Device) Sleep(sleepEnabled bool) error {
|
||||
if sleepEnabled {
|
||||
d.Command(DISPLAYOFF)
|
||||
} else {
|
||||
d.Command(DISPLAYON)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FillRectangle fills a rectangle at a given coordinates with a color
|
||||
func (d *Device) FillRectangle(x, y, width, height int16, c pixel.Monochrome) error {
|
||||
dw, dh := d.Size16()
|
||||
|
||||
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||
x >= d.width || (x+width) > dw || y >= dh || (y+height) > dh {
|
||||
return errOutOfRange
|
||||
}
|
||||
|
||||
if x+width == dw && y+height == dh && c == pixel.Off {
|
||||
d.ClearDisplay()
|
||||
return nil
|
||||
}
|
||||
|
||||
for i := x; i < x+width; i++ {
|
||||
for j := y; j < y+height; j++ {
|
||||
d.SetPixel(i, j, c)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetScroll sets the vertical scrolling for the display, which is a NOP for this display.
|
||||
func (d *Device) SetScroll(line int16) {
|
||||
return
|
||||
}
|
||||
|
||||
/* draw.Image interface */
|
||||
|
||||
func (d *Device) At(x, y int) color.Color {
|
||||
return d.GetPixel(int16(x), int16(y))
|
||||
}
|
||||
|
||||
func (d *Device) Bounds() image.Rectangle {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||
}
|
||||
return image.Rect(0, 0, int(d.height), int(d.width))
|
||||
}
|
||||
|
||||
func (d *Device) ColorModel() color.Model {
|
||||
return pixel.MonochromeModel
|
||||
}
|
||||
|
||||
func (d *Device) Set(x, y int, c color.Color) {
|
||||
c = pixel.MonochromeModel.Convert(c)
|
||||
d.SetPixel(int16(x), int16(y), c.(pixel.Monochrome))
|
||||
}
|
||||
|
||||
/* display.Image interface */
|
||||
|
||||
func (d *Device) Halt() error {
|
||||
return d.bus.Halt()
|
||||
}
|
||||
|
||||
func (d *Device) Size() image.Point {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
return image.Pt(int(d.width), int(d.height))
|
||||
}
|
||||
return image.Pt(int(d.height), int(d.width))
|
||||
}
|
||||
|
||||
func (d *Device) String() string {
|
||||
return fmt.Sprintf("ssd1306:%dx%d", d.width, d.height)
|
||||
}
|
||||
|
||||
/* display.imageDrawer interface */
|
||||
|
||||
func (d *Device) DrawImage(img image.Image) error {
|
||||
draw.Draw(d.buffer, d.buffer.Bounds(), img, image.Point{}, draw.Src)
|
||||
return d.Refresh()
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package st7789
|
||||
|
||||
type FrameRate uint8
|
||||
|
||||
// Registers
|
||||
const (
|
||||
NOP = 0x00
|
||||
SWRESET = 0x01
|
||||
RDDID = 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
|
||||
RAMRD = 0x2E
|
||||
PTLAR = 0x30
|
||||
COLMOD = 0x3A
|
||||
MADCTL = 0x36
|
||||
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
|
||||
RDID4 = 0xDD
|
||||
FRMCTR1 = 0xB1
|
||||
RGBCTRL = 0xB1
|
||||
FRMCTR2 = 0xB2
|
||||
PORCTRL = 0xB2
|
||||
FRMCTR3 = 0xB3
|
||||
INVCTR = 0xB4
|
||||
DISSET5 = 0xB6
|
||||
PWCTR1 = 0xC0
|
||||
PWCTR2 = 0xC1
|
||||
PWCTR3 = 0xC2
|
||||
PWCTR4 = 0xC3
|
||||
PWCTR5 = 0xC4
|
||||
VMCTR1 = 0xC5
|
||||
FRCTRL2 = 0xC6
|
||||
PWCTR6 = 0xFC
|
||||
GMCTRP1 = 0xE0
|
||||
GMCTRN1 = 0xE1
|
||||
GSCAN = 0x45
|
||||
|
||||
// Allowable frame rate codes for FRCTRL2 (Identifier is in Hz)
|
||||
FRAMERATE_111 FrameRate = 0x01
|
||||
FRAMERATE_105 FrameRate = 0x02
|
||||
FRAMERATE_99 FrameRate = 0x03
|
||||
FRAMERATE_94 FrameRate = 0x04
|
||||
FRAMERATE_90 FrameRate = 0x05
|
||||
FRAMERATE_86 FrameRate = 0x06
|
||||
FRAMERATE_82 FrameRate = 0x07
|
||||
FRAMERATE_78 FrameRate = 0x08
|
||||
FRAMERATE_75 FrameRate = 0x09
|
||||
FRAMERATE_72 FrameRate = 0x0A
|
||||
FRAMERATE_69 FrameRate = 0x0B
|
||||
FRAMERATE_67 FrameRate = 0x0C
|
||||
FRAMERATE_64 FrameRate = 0x0D
|
||||
FRAMERATE_62 FrameRate = 0x0E
|
||||
FRAMERATE_60 FrameRate = 0x0F // 60 is default
|
||||
FRAMERATE_58 FrameRate = 0x10
|
||||
FRAMERATE_57 FrameRate = 0x11
|
||||
FRAMERATE_55 FrameRate = 0x12
|
||||
FRAMERATE_53 FrameRate = 0x13
|
||||
FRAMERATE_52 FrameRate = 0x14
|
||||
FRAMERATE_50 FrameRate = 0x15
|
||||
FRAMERATE_49 FrameRate = 0x16
|
||||
FRAMERATE_48 FrameRate = 0x17
|
||||
FRAMERATE_46 FrameRate = 0x18
|
||||
FRAMERATE_45 FrameRate = 0x19
|
||||
FRAMERATE_44 FrameRate = 0x1A
|
||||
FRAMERATE_43 FrameRate = 0x1B
|
||||
FRAMERATE_42 FrameRate = 0x1C
|
||||
FRAMERATE_41 FrameRate = 0x1D
|
||||
FRAMERATE_40 FrameRate = 0x1E
|
||||
FRAMERATE_39 FrameRate = 0x1F
|
||||
|
||||
MAX_VSYNC_SCANLINES = 254
|
||||
)
|
||||
@@ -0,0 +1,535 @@
|
||||
package st7789
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
"periph.io/x/conn/v3/spi/spireg"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("st7789", newDevice)
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
conn spi.Conn
|
||||
reset, cs, dc, bl gpio.PinOut
|
||||
width int16
|
||||
height int16
|
||||
columnOffsetCfg int16
|
||||
rowOffsetCfg int16
|
||||
columnOffset int16
|
||||
rowOffset int16
|
||||
rotation display.Rotation
|
||||
frameRate FrameRate
|
||||
batchLength int32
|
||||
isBGR bool
|
||||
vSyncLines int16
|
||||
}
|
||||
|
||||
type Opts struct {
|
||||
Width int16
|
||||
Height int16
|
||||
Rotation display.Rotation
|
||||
RowOffset int16
|
||||
ColumnOffset int16
|
||||
FrameRate FrameRate
|
||||
VSyncLines int16
|
||||
}
|
||||
|
||||
var DefaultOpts = Opts{
|
||||
Width: 240,
|
||||
Height: 320,
|
||||
}
|
||||
|
||||
func newDevice(config *config.Display) (display.Display, error) {
|
||||
log := logrus.WithFields(logrus.Fields{
|
||||
"type": "st7789",
|
||||
"name": config.Name,
|
||||
})
|
||||
|
||||
log.WithField("port", config.Port).Trace("opening SPI port")
|
||||
port, err := spireg.Open(config.Port)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
bits = 8
|
||||
reset gpio.PinOut
|
||||
dc gpio.PinOut
|
||||
cs gpio.PinOut
|
||||
bl gpio.PinOut
|
||||
)
|
||||
if config.DC == "" {
|
||||
bits = 9
|
||||
} else {
|
||||
if dc, err = display.LookupPinOut(config.DC); err != nil {
|
||||
return nil, fmt.Errorf("invalid dc pin: %w", err)
|
||||
}
|
||||
if err = dc.Out(gpio.Low); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if reset, err = display.LookupPinOut(config.Reset); err != nil {
|
||||
return nil, fmt.Errorf("invalid reset pin: %w", err)
|
||||
}
|
||||
if cs, err = display.LookupPinOut(config.CS); err != nil {
|
||||
return nil, fmt.Errorf("invalid cs pin: %w", err)
|
||||
}
|
||||
if bl, err = display.LookupPinOut(config.BL); err != nil {
|
||||
return nil, fmt.Errorf("invalid bl pin: %w", err)
|
||||
}
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"mode": spi.Mode0,
|
||||
"bits": bits,
|
||||
"reset": reset.Name(),
|
||||
"dc": dc.Name(),
|
||||
"cs": cs.Name(),
|
||||
"bl": bl.Name(),
|
||||
}).Debug("connecting on SPI port")
|
||||
conn, err := port.Connect(300*physic.KiloHertz, spi.Mode0, bits)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := &Device{
|
||||
conn: conn,
|
||||
reset: reset,
|
||||
cs: cs,
|
||||
dc: dc,
|
||||
bl: bl,
|
||||
}
|
||||
cfg := DefaultOpts
|
||||
|
||||
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.rotation = cfg.Rotation
|
||||
d.rowOffsetCfg = cfg.RowOffset
|
||||
d.columnOffsetCfg = cfg.ColumnOffset
|
||||
|
||||
if cfg.FrameRate != 0 {
|
||||
d.frameRate = cfg.FrameRate
|
||||
} else {
|
||||
d.frameRate = FRAMERATE_60
|
||||
}
|
||||
|
||||
if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 {
|
||||
d.vSyncLines = cfg.VSyncLines
|
||||
} else {
|
||||
d.vSyncLines = 16
|
||||
}
|
||||
|
||||
d.batchLength = int32(d.width)
|
||||
if d.height > d.width {
|
||||
d.batchLength = int32(d.height)
|
||||
}
|
||||
d.batchLength += d.batchLength & 1
|
||||
|
||||
// Reset the device
|
||||
log.Trace("reset device")
|
||||
if err = d.reset.Out(gpio.High); err != nil {
|
||||
_ = port.Close()
|
||||
return nil, err
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if err = d.reset.Out(gpio.Low); err != nil {
|
||||
_ = port.Close()
|
||||
return nil, err
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if err = d.reset.Out(gpio.High); err != nil {
|
||||
_ = port.Close()
|
||||
return nil, err
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Common initialization
|
||||
log.Trace("configure device")
|
||||
d.Command(SWRESET) // Soft reset
|
||||
time.Sleep(150 * time.Millisecond) //
|
||||
|
||||
d.Command(SLPOUT) // Exit sleep mode
|
||||
time.Sleep(500 * time.Millisecond) //
|
||||
|
||||
// Memory initialization
|
||||
d.Command(COLMOD) // Set color mode
|
||||
d.Data(0x55) // 16-bit color
|
||||
time.Sleep(10 * time.Millisecond) //
|
||||
|
||||
d.SetRotation(d.rotation) // Memory orientation
|
||||
|
||||
d.setWindow(0, 0, d.width, d.height) // Full draw window
|
||||
d.FillScreen(color.RGBA{0, 0, 0, 255}) // Clear screen
|
||||
|
||||
// Framerate
|
||||
d.Command(FRCTRL2) // Frame rate for normal mode
|
||||
d.Data(uint8(d.frameRate)) // Default is 60Hz
|
||||
|
||||
// Frame vertical sync and "porch"
|
||||
//
|
||||
// Front and back porch controls vertical scanline sync time before and after
|
||||
// a frame, where memory can be safely written without tearing.
|
||||
//
|
||||
fp := uint8(d.vSyncLines / 2) // Split the desired pause half and half
|
||||
bp := uint8(d.vSyncLines - int16(fp)) // between front and back porch.
|
||||
|
||||
d.Command(PORCTRL)
|
||||
d.Data(bp) // Back porch 5bit (0x7F max 0x08 default)
|
||||
d.Data(fp) // Front porch 5bit (0x7F max 0x08 default)
|
||||
d.Data(0x00) // Seprarate porch (TODO: what is this?)
|
||||
d.Data(0x22) // Idle mode porch (4bit-back 4bit-front 0x22 default)
|
||||
d.Data(0x22) // Partial mode porch (4bit-back 4bit-front 0x22 default)
|
||||
|
||||
// Ready to display
|
||||
d.Command(INVON) // Inversion ON
|
||||
time.Sleep(10 * time.Millisecond) //
|
||||
|
||||
d.Command(NORON) // Normal mode ON
|
||||
time.Sleep(10 * time.Millisecond) //
|
||||
|
||||
d.Command(DISPON) // Screen ON
|
||||
time.Sleep(10 * time.Millisecond) //
|
||||
|
||||
// Backlight ON
|
||||
if err = d.bl.Out(gpio.High); err != nil {
|
||||
_ = port.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *Device) String() string {
|
||||
return "st7789"
|
||||
}
|
||||
|
||||
func (d *Device) Bounds() image.Rectangle {
|
||||
if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 {
|
||||
return image.Rect(0, 0, int(d.height), int(d.width))
|
||||
}
|
||||
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||
}
|
||||
|
||||
func (d *Device) ColorModel() color.Model {
|
||||
return color.RGBAModel
|
||||
}
|
||||
|
||||
func (d *Device) Halt() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Device) Refresh() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sync waits for the display to hit the next VSYNC pause
|
||||
func (d *Device) Sync() {
|
||||
d.SyncToScanLine(0)
|
||||
}
|
||||
|
||||
// SyncToScanLine waits for the display to hit a specific scanline
|
||||
//
|
||||
// A scanline value of 0 will forward to the beginning of the next VSYNC,
|
||||
// even if the display is currently in a VSYNC pause.
|
||||
//
|
||||
// Syncline values appear to increment once for every two vertical
|
||||
// lines on the display.
|
||||
//
|
||||
// NOTE: Use GetHighestScanLine and GetLowestScanLine to obtain the highest
|
||||
// and lowest useful values. Values are affected by front and back porch
|
||||
// vsync settings (derived from VSyncLines configuration option).
|
||||
func (d *Device) SyncToScanLine(scanline uint16) {
|
||||
scan := d.GetScanLine()
|
||||
|
||||
// Sometimes GetScanLine returns erroneous 0 on first call after draw, so double check
|
||||
if scan == 0 {
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
|
||||
if scanline == 0 {
|
||||
// we dont know where we are in an ongoing vsync so go around
|
||||
for scan < 1 {
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
for scan > 0 {
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
} else {
|
||||
// go around unless we're very close to the target
|
||||
for scan > scanline+4 {
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
for scan < scanline {
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetScanLine reads the current scanline value from the display
|
||||
func (d *Device) GetScanLine() uint16 {
|
||||
data := []uint8{0x00, 0x00}
|
||||
d.Rx(GSCAN, data)
|
||||
return uint16(data[0])<<8 + uint16(data[1])
|
||||
}
|
||||
|
||||
// GetHighestScanLine calculates the last scanline id in the frame before VSYNC pause
|
||||
func (d *Device) GetHighestScanLine() uint16 {
|
||||
// Last scanline id appears to be backporch/2 + 320/2
|
||||
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 160
|
||||
}
|
||||
|
||||
// GetLowestScanLine calculate the first scanline id to appear after VSYNC pause
|
||||
func (d *Device) GetLowestScanLine() uint16 {
|
||||
// First scanline id appears to be backporch/2 + 1
|
||||
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 1
|
||||
}
|
||||
|
||||
// SetPixel sets a pixel in the screen
|
||||
func (d *Device) SetPixel(x int16, y int16, c color.RGBA) {
|
||||
if x < 0 || y < 0 ||
|
||||
(((d.rotation == display.NoRotation || d.rotation == display.Rotate180) && (x >= d.width || y >= d.height)) ||
|
||||
((d.rotation == display.Rotate90 || d.rotation == display.Rotate270) && (x >= d.height || y >= d.width))) {
|
||||
return
|
||||
}
|
||||
d.FillRectangle(x, y, 1, 1, c)
|
||||
}
|
||||
|
||||
// setWindow prepares the screen to be modified at a given rectangle
|
||||
func (d *Device) setWindow(x, y, w, h int16) {
|
||||
x += d.columnOffset
|
||||
y += d.rowOffset
|
||||
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)
|
||||
}
|
||||
|
||||
// FillRectangle fills a rectangle at a given coordinates with a color
|
||||
func (d *Device) FillRectangle(x, y, width, height int16, c color.Color) error {
|
||||
|
||||
k, i := int16(d.Size().X), int16(d.Size().Y)
|
||||
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||
x >= k || (x+width) > k || y >= i || (y+height) > i {
|
||||
return errors.New("rectangle coordinates outside display area")
|
||||
}
|
||||
d.setWindow(x, y, width, height)
|
||||
c565 := pixel.Color565Model.Convert(c).(pixel.Color565)
|
||||
//c565 := RGBATo565(c)
|
||||
c1 := uint8(c565 >> 8)
|
||||
c2 := uint8(c565)
|
||||
|
||||
data := make([]uint8, d.batchLength*2)
|
||||
for i := int32(0); i < d.batchLength; i++ {
|
||||
data[i*2] = c1
|
||||
data[i*2+1] = c2
|
||||
}
|
||||
j := int32(width) * int32(height)
|
||||
for j > 0 {
|
||||
if j >= d.batchLength {
|
||||
d.Tx(data, false)
|
||||
} else {
|
||||
d.Tx(data[:j*2], false)
|
||||
}
|
||||
j -= d.batchLength
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FillRectangle fills a rectangle at a given coordinates with a buffer
|
||||
func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {
|
||||
i, j := int16(d.Size().X), int16(d.Size().Y)
|
||||
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||
x >= i || (x+width) > i || y >= j || (y+height) > j {
|
||||
return errors.New("rectangle coordinates outside display area")
|
||||
}
|
||||
if int32(width)*int32(height) != int32(len(buffer)) {
|
||||
return errors.New("buffer length does not match with rectangle size")
|
||||
}
|
||||
d.setWindow(x, y, width, height)
|
||||
|
||||
k := int32(width) * int32(height)
|
||||
data := make([]uint8, d.batchLength*2)
|
||||
offset := int32(0)
|
||||
for k > 0 {
|
||||
for i := int32(0); i < d.batchLength; i++ {
|
||||
if offset+i < int32(len(buffer)) {
|
||||
c565 := RGBATo565(buffer[offset+i])
|
||||
c1 := uint8(c565 >> 8)
|
||||
c2 := uint8(c565)
|
||||
data[i*2] = c1
|
||||
data[i*2+1] = c2
|
||||
}
|
||||
}
|
||||
if k >= d.batchLength {
|
||||
d.Tx(data, false)
|
||||
} else {
|
||||
d.Tx(data[:k*2], false)
|
||||
}
|
||||
k -= d.batchLength
|
||||
offset += d.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)
|
||||
}
|
||||
|
||||
// FillScreen fills the screen with a given color
|
||||
func (d *Device) FillScreen(c color.Color) {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
d.FillRectangle(0, 0, d.width, d.height, c)
|
||||
} else {
|
||||
d.FillRectangle(0, 0, d.height, d.width, c)
|
||||
}
|
||||
}
|
||||
|
||||
// SetRotation changes the rotation of the device (clock-wise)
|
||||
func (d *Device) SetRotation(rotation display.Rotation) {
|
||||
madctl := uint8(0)
|
||||
switch rotation % 4 {
|
||||
case display.NoRotation:
|
||||
madctl = MADCTL_MX | MADCTL_MY
|
||||
d.rowOffset = d.rowOffsetCfg
|
||||
d.columnOffset = d.columnOffsetCfg
|
||||
break
|
||||
case display.Rotate90:
|
||||
madctl = MADCTL_MY | MADCTL_MV
|
||||
d.rowOffset = d.columnOffsetCfg
|
||||
d.columnOffset = d.rowOffsetCfg
|
||||
break
|
||||
case display.Rotate180:
|
||||
d.rowOffset = 0
|
||||
d.columnOffset = 0
|
||||
break
|
||||
case display.Rotate270:
|
||||
madctl = MADCTL_MX | MADCTL_MV
|
||||
d.rowOffset = 0
|
||||
d.columnOffset = 0
|
||||
break
|
||||
}
|
||||
if d.isBGR {
|
||||
madctl |= MADCTL_BGR
|
||||
}
|
||||
d.Command(MADCTL)
|
||||
d.Data(madctl)
|
||||
}
|
||||
|
||||
// Command sends a command to the display
|
||||
func (d *Device) Command(command uint8) {
|
||||
d.Tx([]byte{command}, true)
|
||||
}
|
||||
|
||||
// Command sends a 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) {
|
||||
if isCommand {
|
||||
d.dc.Out(gpio.Low)
|
||||
} else {
|
||||
d.dc.Out(gpio.High)
|
||||
}
|
||||
d.cs.Out(gpio.Low)
|
||||
d.conn.Tx(data, nil)
|
||||
d.cs.Out(gpio.High)
|
||||
}
|
||||
|
||||
// Rx reads data from the display
|
||||
func (d *Device) Rx(command uint8, read_bytes []byte) {
|
||||
d.dc.Out(gpio.Low)
|
||||
d.cs.Out(gpio.Low)
|
||||
d.conn.Tx([]byte{command}, nil)
|
||||
d.dc.Out(gpio.High)
|
||||
for i := range read_bytes {
|
||||
d.conn.Tx([]byte{0xFF}, read_bytes[i:i+1])
|
||||
}
|
||||
d.cs.Out(gpio.High)
|
||||
}
|
||||
|
||||
// Size returns the current size of the display.
|
||||
func (d *Device) Size() image.Point {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
return image.Pt(int(d.width), int(d.height))
|
||||
}
|
||||
return image.Pt(int(d.height), int(d.width))
|
||||
}
|
||||
|
||||
// EnableBacklight enables or disables the backlight
|
||||
func (d *Device) EnableBacklight(enable bool) {
|
||||
if enable {
|
||||
d.bl.Out(gpio.High)
|
||||
} else {
|
||||
d.bl.Out(gpio.Low)
|
||||
}
|
||||
}
|
||||
|
||||
// InverColors 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
|
||||
}
|
||||
|
||||
func (d *Device) At(x, y int) color.Color {
|
||||
return color.Black
|
||||
}
|
||||
|
||||
func (d *Device) Set(x, y int, c color.Color) {
|
||||
d.FillRectangle(int16(x), int16(y), int16(x)+1, int16(y)+1, color.RGBAModel.Convert(c).(color.RGBA))
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package all
|
||||
|
||||
import (
|
||||
_ "git.maze.io/go/harmon/display/console"
|
||||
_ "git.maze.io/go/harmon/display/sh1106"
|
||||
_ "git.maze.io/go/harmon/display/ssd1305"
|
||||
_ "git.maze.io/go/harmon/display/ssd1306"
|
||||
_ "git.maze.io/go/harmon/display/st7789"
|
||||
_ "git.maze.io/go/harmon/display/virtual"
|
||||
)
|
||||
@@ -0,0 +1,192 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("console", New)
|
||||
}
|
||||
|
||||
type Display struct {
|
||||
p *textImage
|
||||
w, h int
|
||||
}
|
||||
|
||||
func New(config *config.Display) (display.Display, error) {
|
||||
if !term.IsTerminal(0) {
|
||||
return nil, errors.New("console: not a terminal")
|
||||
}
|
||||
|
||||
w, h, err := term.GetSize(0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Display{
|
||||
p: newTextImage(image.Rect(0, 0, w, h<<1)),
|
||||
w: w,
|
||||
h: h,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Display) String() string { return fmt.Sprintf("%dx%d console", d.w, d.h) }
|
||||
func (d *Display) Columns() int { return d.w }
|
||||
func (d *Display) Rows() int { return d.h }
|
||||
func (d *Display) Size() image.Point { return image.Pt(d.w, d.h) }
|
||||
|
||||
func (d *Display) Refresh() error {
|
||||
fmt.Print("\x1b[?25l\x1b[2J") // hide the cursor and clear screen
|
||||
for i, l := 0, d.w*d.h; i < l; i += d.p.Stride {
|
||||
fmt.Println(string(d.p.Pix[i : i+d.p.Stride]))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Display) Bounds() image.Rectangle { return d.p.Rect }
|
||||
func (d *Display) ColorModel() color.Model { return d.p.ColorModel() }
|
||||
func (d *Display) At(x, y int) color.Color { return d.p.At(x, y) }
|
||||
func (d *Display) Set(x, y int, c color.Color) { d.p.Set(x, y, c) }
|
||||
|
||||
func (d *Display) Halt() error {
|
||||
_, err := fmt.Print("\x1b[?25h\x1b[2J") // show the cursor and clear screen
|
||||
return err
|
||||
}
|
||||
|
||||
type textImage struct {
|
||||
// Pix holds the image's pixels, as character values. The pixel at
|
||||
// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
|
||||
Pix []rune
|
||||
|
||||
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
|
||||
Stride int
|
||||
|
||||
// Rect is the image's bounds.
|
||||
Rect image.Rectangle
|
||||
}
|
||||
|
||||
func newTextImage(r image.Rectangle) *textImage {
|
||||
if r.Dy()%2 == 1 {
|
||||
r.Max.Y++
|
||||
}
|
||||
p := make([]rune, r.Dx()*r.Dy()/2)
|
||||
for i := range p {
|
||||
p[i] = ' '
|
||||
}
|
||||
return &textImage{
|
||||
Pix: p,
|
||||
Stride: r.Dx(),
|
||||
Rect: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *textImage) ColorModel() color.Model {
|
||||
return pixel.MonochromeModel
|
||||
}
|
||||
|
||||
func (p *textImage) PixOffset(x, y int) int {
|
||||
return (((y - p.Rect.Min.Y) >> 1) * p.Stride) + (x - p.Rect.Min.X)
|
||||
}
|
||||
|
||||
func (p *textImage) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(p.Rect)) {
|
||||
return pixel.Off
|
||||
}
|
||||
|
||||
i := p.PixOffset(x, y)
|
||||
r := p.Pix[i]
|
||||
if y%2 == 1 {
|
||||
if r == '▀' || r == '█' {
|
||||
return pixel.On
|
||||
}
|
||||
} else {
|
||||
if r == '▄' || r == '█' {
|
||||
return pixel.On
|
||||
}
|
||||
}
|
||||
return pixel.Off
|
||||
}
|
||||
|
||||
func (p *textImage) Set(x, y int, c color.Color) {
|
||||
if !(image.Point{x, y}.In(p.Rect)) {
|
||||
return
|
||||
}
|
||||
|
||||
i := p.PixOffset(x, y)
|
||||
r := p.Pix[i]
|
||||
|
||||
if pixel.IsOn(c) {
|
||||
if y%2 == 1 {
|
||||
if r == '▀' {
|
||||
p.Pix[i] = '█'
|
||||
} else {
|
||||
p.Pix[i] = '▄'
|
||||
}
|
||||
} else {
|
||||
if r == ' ' {
|
||||
p.Pix[i] = '▄'
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if y%2 == 1 {
|
||||
if r == '█' {
|
||||
p.Pix[i] = '▀'
|
||||
} else {
|
||||
p.Pix[i] = ' '
|
||||
}
|
||||
} else {
|
||||
if r == '█' {
|
||||
p.Pix[i] = '▄'
|
||||
} else {
|
||||
p.Pix[i] = ' '
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var quadrants = []rune(" ▄▀█")
|
||||
|
||||
/*
|
||||
func (p *textImage) PixOffset(x, y int) int {
|
||||
return (y-p.Rect.Min.Y)*p.Stride + (x - p.Rect.Min.X)
|
||||
}
|
||||
|
||||
func (p *textImage) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(p.Rect)) {
|
||||
return color.Gray{}
|
||||
}
|
||||
i := p.PixOffset(x, y)
|
||||
return fromGrayScale(p.Pix[i])
|
||||
}
|
||||
|
||||
func (p *textImage) Set(x, y int, c color.Color) {
|
||||
if !(image.Point{x, y}.In(p.Rect)) {
|
||||
return
|
||||
}
|
||||
i := p.PixOffset(x, y)
|
||||
p.Pix[i] = toGrayScale(c)
|
||||
}
|
||||
|
||||
var grayScaleRamp = []rune(" ░░▒▓▓█")
|
||||
|
||||
func toGrayScale(c color.Color) rune {
|
||||
g := color.GrayModel.Convert(c).(color.Gray)
|
||||
return grayScaleRamp[g.Y>>3]
|
||||
}
|
||||
|
||||
func fromGrayScale(r rune) color.Gray {
|
||||
if i := strings.IndexRune(string(grayScaleRamp), r); i > -1 {
|
||||
return color.Gray{Y: uint8(i << 3)}
|
||||
}
|
||||
return color.Gray{}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,90 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.maze.io/go/harmon/hardware"
|
||||
)
|
||||
|
||||
// Display base interface for all displays.
|
||||
type Display interface {
|
||||
hardware.Resource
|
||||
|
||||
Size() image.Point
|
||||
|
||||
// Refresh the display.
|
||||
Refresh() error
|
||||
|
||||
// Image allows this display to be used as canvas.
|
||||
draw.Image
|
||||
}
|
||||
|
||||
// Rotation of the display.
|
||||
type Rotation uint8
|
||||
|
||||
const (
|
||||
NoRotation Rotation = iota
|
||||
Rotate90
|
||||
Rotate180
|
||||
Rotate270
|
||||
)
|
||||
|
||||
func ParseRotation(s string) (Rotation, error) {
|
||||
switch strings.ToLower(s) {
|
||||
case "", "no", "none":
|
||||
return NoRotation, nil
|
||||
case "90", "right", "cw":
|
||||
return Rotate90, nil
|
||||
case "180", "flip":
|
||||
return Rotate180, nil
|
||||
case "270", "left", "ccw":
|
||||
return Rotate270, nil
|
||||
default:
|
||||
return NoRotation, fmt.Errorf("invalid rotation %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
func ParseI2CAddress(addr string) (uint16, error) {
|
||||
if strings.HasPrefix(strings.ToLower(addr), "0x") {
|
||||
addr = addr[2:]
|
||||
}
|
||||
|
||||
v, err := strconv.ParseUint(addr, 16, 16)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint16(v), nil
|
||||
}
|
||||
|
||||
func ParseSize(size string, defaultWidth, defaultHeight int) (width, height int, err error) {
|
||||
if size == "" {
|
||||
return defaultWidth, defaultHeight, nil
|
||||
}
|
||||
|
||||
i := strings.IndexByte(size, 'x')
|
||||
if i == -1 {
|
||||
return 0, 0, fmt.Errorf("display: incorrect size specifier %q: expected `widthxheight`", size)
|
||||
} else if i == 0 {
|
||||
if height, err = strconv.Atoi(size[1:]); err != nil {
|
||||
return
|
||||
}
|
||||
return defaultWidth, height, nil
|
||||
} else if i == len(size)-1 {
|
||||
if width, err = strconv.Atoi(size[:i]); err != nil {
|
||||
return
|
||||
}
|
||||
return width, defaultHeight, nil
|
||||
}
|
||||
|
||||
if width, err = strconv.Atoi(size[:i]); err != nil {
|
||||
return
|
||||
}
|
||||
if height, err = strconv.Atoi(size[i+1:]); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package display_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.maze.io/go/harmon/display"
|
||||
)
|
||||
|
||||
func TestParseSize(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Test string
|
||||
DefaultWidth int
|
||||
DefaultHeight int
|
||||
Width int
|
||||
Height int
|
||||
}{
|
||||
{"", 128, 64, 128, 64},
|
||||
{"x32", 128, 64, 128, 32},
|
||||
{"64x", 128, 64, 64, 64},
|
||||
{"123x456", 128, 64, 123, 456},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.Test, func(it *testing.T) {
|
||||
w, h, err := display.ParseSize(test.Test, test.DefaultWidth, test.DefaultHeight)
|
||||
if err != nil {
|
||||
it.Fatal(err)
|
||||
}
|
||||
if w != test.Width {
|
||||
it.Errorf("expected %q to return width %d, got %d", test.Test, test.Width, w)
|
||||
}
|
||||
if h != test.Height {
|
||||
it.Errorf("expected %q to return height %d, got %d", test.Test, test.Height, h)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"os"
|
||||
|
||||
_ "image/gif" // GIF codec
|
||||
_ "image/jpeg" // JPEG codec
|
||||
_ "image/png" // PNG codec
|
||||
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultTimeFormat = "15:04"
|
||||
DefaultDateFormat = "01-02"
|
||||
)
|
||||
|
||||
type bitmapDrawerAt[T pixel.Color] interface {
|
||||
DrawBitmap(x, y int16, bitmap pixel.Image[T]) error
|
||||
}
|
||||
|
||||
type imageDrawer interface {
|
||||
DrawImage(image.Image) error
|
||||
}
|
||||
|
||||
type imageDrawerAt interface {
|
||||
DrawImageAt(x, y int, img image.Image) error
|
||||
}
|
||||
|
||||
func DrawTime(d Display, format string) {
|
||||
if format == "" {
|
||||
format = DefaultTimeFormat
|
||||
}
|
||||
}
|
||||
|
||||
func DrawSplash(d Display) error {
|
||||
/*
|
||||
var (
|
||||
size = d.Size()
|
||||
origin image.Point
|
||||
)
|
||||
if size.X > size.Y {
|
||||
origin.X = (size.X - size.Y) / 2
|
||||
size.X = size.Y
|
||||
} else {
|
||||
origin.Y = (size.Y - size.X) / 2
|
||||
size.Y = size.X
|
||||
}
|
||||
|
||||
r := image.Rect(0, 0, size.X, size.Y).Add(origin)
|
||||
draw.Draw(d, r, resize.Resize(uint(size.X), uint(size.Y), splashImage, resize.Lanczos3), image.Point{}, draw.Src)
|
||||
return d.Refresh()
|
||||
*/
|
||||
if drawer, ok := d.(bitmapDrawerAt[pixel.RGB565BE]); ok {
|
||||
return drawer.DrawBitmap(0, 0, harmon_240_565BE)
|
||||
}
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func DrawImage(d Display, img image.Image) {
|
||||
if drawer, ok := d.(imageDrawer); ok {
|
||||
logrus.Trace("using DrawImage")
|
||||
if err := drawer.DrawImage(img); err != nil {
|
||||
logrus.WithError(err).Warn("image draw failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//scaled := resize.Resize(uint(size.X), uint(size.Y), img, resize.Bicubic)
|
||||
if drawer, ok := d.(imageDrawerAt); ok {
|
||||
logrus.Trace("using DrawImageAt")
|
||||
if err := drawer.DrawImageAt(0, 0, img); err != nil {
|
||||
logrus.WithError(err).Warn("image draw failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logrus.Trace("using slow cooked draw")
|
||||
}
|
||||
|
||||
func DrawImageFile(d Display, name string) error {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i, _, err := image.Decode(f)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
DrawImage(d, i)
|
||||
return f.Close()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,537 @@
|
||||
// Package gc9a01 provides a driver for the GC9A01 round display controller.
|
||||
package gc9a01
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"time"
|
||||
|
||||
"git.maze.io/go/bragi/hardware"
|
||||
"git.maze.io/go/bragi/hardware/display/pixel"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
)
|
||||
|
||||
var supportedResolutions = [][2]int16{
|
||||
{80, 160},
|
||||
{120, 120},
|
||||
{128, 128},
|
||||
{160, 160},
|
||||
{240, 240},
|
||||
}
|
||||
|
||||
// Orientation is the display orientation.
|
||||
type Orientation uint8
|
||||
|
||||
const (
|
||||
Horizontal Orientation = iota
|
||||
Vertical
|
||||
)
|
||||
|
||||
// Config for the display.
|
||||
type Config struct {
|
||||
hardware.SPIConfig
|
||||
Width int
|
||||
Height int
|
||||
Orientation Orientation
|
||||
VSyncLines int
|
||||
RowOffset int
|
||||
ColumnOffset int
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
conn spi.Conn
|
||||
cs gpio.PinOut
|
||||
dc gpio.PinOut
|
||||
reset gpio.PinOut
|
||||
bl gpio.PinOut
|
||||
width int16
|
||||
height int16
|
||||
columnOffsetCfg int16
|
||||
rowOffsetCfg int16
|
||||
columnOffset int16
|
||||
rowOffset int16
|
||||
vSyncLines int16
|
||||
orientation Orientation
|
||||
batchLength int16
|
||||
batchData []uint8
|
||||
image *pixel.Image565
|
||||
}
|
||||
|
||||
func New(port spi.Port, config Config) (*Device, error) {
|
||||
f := config.Frequency
|
||||
if f == 0 {
|
||||
f = 80 * physic.MegaHertz // 80_000_000
|
||||
}
|
||||
|
||||
c, err := port.Connect(f, spi.Mode0, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := &Device{
|
||||
conn: c,
|
||||
cs: config.CS,
|
||||
dc: config.DC,
|
||||
reset: config.Reset,
|
||||
bl: config.BL,
|
||||
}
|
||||
|
||||
if err = d.configure(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Reset the display.
|
||||
func (d *Device) Reset() error {
|
||||
var err error
|
||||
if err = d.reset.Out(gpio.High); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if err = d.reset.Out(gpio.Low); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if err = d.reset.Out(gpio.High); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Device) command(v uint8) error {
|
||||
return d.tx([]byte{v}, true)
|
||||
}
|
||||
|
||||
func (d *Device) data(v uint8) error {
|
||||
return d.tx([]byte{v}, false)
|
||||
}
|
||||
|
||||
func (d *Device) tx(w []byte, cmd bool) (err error) {
|
||||
level := gpio.Low
|
||||
if cmd {
|
||||
level = gpio.High
|
||||
}
|
||||
if err = d.dc.Out(level); err != nil {
|
||||
return
|
||||
}
|
||||
return d.conn.Tx(w, nil)
|
||||
}
|
||||
|
||||
/*
|
||||
func (d *Device) rx(command uint8, data []byte) (err error) {
|
||||
if err = d.dc.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.cs.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.conn.Tx([]byte{command}, nil); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.dc.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.conn.Tx(nil, data); err != nil {
|
||||
return
|
||||
}
|
||||
return d.cs.Out(gpio.High)
|
||||
}
|
||||
*/
|
||||
|
||||
func (d *Device) setOrientation() (err error) {
|
||||
var reg uint8
|
||||
if d.orientation == Horizontal {
|
||||
reg = 0xc8
|
||||
} else {
|
||||
reg = 0x68
|
||||
}
|
||||
|
||||
if err = d.command(MADCTR); err != nil {
|
||||
return
|
||||
}
|
||||
return d.command(reg)
|
||||
}
|
||||
|
||||
func (d *Device) setWindow(x, y, w, h int) (err error) {
|
||||
if d.orientation == Horizontal {
|
||||
x += int(d.columnOffset)
|
||||
y += int(d.rowOffset)
|
||||
} else {
|
||||
x += int(d.rowOffset)
|
||||
y += int(d.columnOffset)
|
||||
}
|
||||
if err = d.command(CASET); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.tx([]uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)}, false); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.command(RASET); err != nil {
|
||||
return
|
||||
}
|
||||
if err = d.tx([]uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)}, false); err != nil {
|
||||
return
|
||||
}
|
||||
return d.command(RAMWR)
|
||||
}
|
||||
|
||||
func (d *Device) Backlight(on bool) error {
|
||||
if on {
|
||||
return d.bl.Out(gpio.High)
|
||||
}
|
||||
return d.bl.Out(gpio.Low)
|
||||
}
|
||||
|
||||
func (d *Device) Invert(on bool) error {
|
||||
if on {
|
||||
return d.command(INVON)
|
||||
}
|
||||
return d.command(INVOFF)
|
||||
}
|
||||
|
||||
func (d *Device) FillRectangle(x, y, w, h int, c color.Color) (err error) {
|
||||
if x < 0 || y < 0 || w <= 0 || h <= 0 ||
|
||||
x >= int(d.width) || (x+w) > int(d.width) || y >= int(d.height) || (y+h) > int(d.height) {
|
||||
return errors.New("gc9a01: rectangle coordinates outside display area")
|
||||
}
|
||||
|
||||
d.setWindow(x, y, w, h)
|
||||
|
||||
c565 := pixel.Color565Model.Convert(c).(pixel.Color565)
|
||||
c1 := uint8(c565 >> 8)
|
||||
c2 := uint8(c565)
|
||||
for i := 0; i < int(d.batchLength); i++ {
|
||||
d.batchData[i*2+0] = c1
|
||||
d.batchData[i*2+1] = c2
|
||||
}
|
||||
|
||||
i := w * h
|
||||
l := int(d.batchLength)
|
||||
for i > 0 {
|
||||
if i >= l {
|
||||
if err = d.tx(d.batchData, false); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err = d.tx(d.batchData[:i*2], false); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
i -= l
|
||||
}
|
||||
|
||||
for yy := y; yy < y+h; yy++ {
|
||||
for xx := x; xx < x+w; xx++ {
|
||||
d.image.Set(xx, yy, c)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Device) At(x, y int) color.Color {
|
||||
if x < 0 || x >= int(d.width) || y < 0 || y >= int(d.height) {
|
||||
return color.Black
|
||||
}
|
||||
return d.image.At(x, y)
|
||||
}
|
||||
|
||||
func (d *Device) Set(x, y int, c color.Color) {
|
||||
if x < 0 || x >= int(d.width) || y < 0 || y >= int(d.height) {
|
||||
return
|
||||
}
|
||||
_ = d.FillRectangle(x, y, 1, 1, c)
|
||||
}
|
||||
|
||||
func (d *Device) Bounds() image.Rectangle {
|
||||
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||
}
|
||||
|
||||
func (d *Device) ColorModel() color.Model {
|
||||
return pixel.Color565Model
|
||||
}
|
||||
|
||||
func (d *Device) configure(config Config) (err error) {
|
||||
if config.Width > 0 {
|
||||
d.width = int16(config.Width)
|
||||
} else {
|
||||
d.width = 240
|
||||
}
|
||||
if config.Height > 0 {
|
||||
d.height = int16(config.Height)
|
||||
} else {
|
||||
d.height = 240
|
||||
}
|
||||
|
||||
var supportedResolution bool
|
||||
for _, res := range supportedResolutions {
|
||||
if supportedResolution = d.width == res[0] && d.height == res[1]; supportedResolution {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !supportedResolution {
|
||||
return fmt.Errorf("gc9a01: unsupported resolution %dx%d", d.width, d.height)
|
||||
}
|
||||
|
||||
d.image = pixel.NewImage565(image.Rect(0, 0, int(d.width), int(d.height)))
|
||||
d.orientation = config.Orientation
|
||||
d.rowOffsetCfg = int16(config.RowOffset)
|
||||
d.columnOffsetCfg = int16(config.ColumnOffset)
|
||||
d.batchLength = d.width
|
||||
|
||||
if config.VSyncLines >= 2 && config.VSyncLines <= 254 {
|
||||
d.vSyncLines = int16(config.VSyncLines)
|
||||
} else {
|
||||
d.vSyncLines = 2
|
||||
}
|
||||
d.batchLength += d.batchLength & 1
|
||||
d.batchData = make([]uint8, d.batchLength*2)
|
||||
|
||||
if err := d.Reset(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := d.setOrientation(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
return d.Backlight(true)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package gc9a01
|
||||
|
||||
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
|
||||
)
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"periph.io/x/conn/v3"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
type MonochromeDisplayInfo struct {
|
||||
DC gpio.PinOut
|
||||
Reset gpio.PinOut
|
||||
ResetPulseWidth time.Duration
|
||||
ResetWait time.Duration
|
||||
PreChipEnableWait time.Duration
|
||||
PostChipEnableWait time.Duration
|
||||
DataSetupTime time.Duration
|
||||
WritePulseWidth time.Duration
|
||||
Width uint16
|
||||
Height uint16
|
||||
XOffset uint16
|
||||
YOffset uint16
|
||||
Speed physic.Frequency
|
||||
}
|
||||
|
||||
// MonochromeDisplay is the hardware abstraction layer for monochrome displays.
|
||||
type MonochromeDisplay interface {
|
||||
// Init initializes the display.
|
||||
Init() error
|
||||
|
||||
// Halt the display.
|
||||
Halt() error
|
||||
|
||||
// StartTransfer starts a data transfer.
|
||||
StartTransfer() error
|
||||
|
||||
// EndTransfer ends a data transfer.
|
||||
EndTransfer() error
|
||||
|
||||
// Reset the display.
|
||||
Reset(on bool) error
|
||||
|
||||
// SendCommand sends a command to the display.
|
||||
SendCommand([]byte) error
|
||||
|
||||
// SendData sends data to the display.
|
||||
SendData([]byte) error
|
||||
}
|
||||
|
||||
type ssd13xxDisplay struct {
|
||||
conn conn.Conn
|
||||
info MonochromeDisplayInfo
|
||||
}
|
||||
|
||||
func NewSSD13xxDisplay(conn conn.Conn, info MonochromeDisplayInfo) *ssd13xxDisplay {
|
||||
return &ssd13xxDisplay{
|
||||
conn: conn,
|
||||
info: info,
|
||||
}
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) Init() (err error) {
|
||||
if err = d.Reset(true); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(d.info.ResetPulseWidth)
|
||||
if err = d.Reset(false); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(d.info.ResetPulseWidth)
|
||||
if err = d.Reset(true); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(d.info.ResetWait)
|
||||
return
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) Halt() error {
|
||||
if c, ok := d.conn.(io.Closer); ok {
|
||||
return c.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) Reset(on bool) error {
|
||||
if d.info.Reset == nil {
|
||||
// No reset pin.
|
||||
return nil
|
||||
}
|
||||
level := gpio.Low
|
||||
if on {
|
||||
level = gpio.High
|
||||
}
|
||||
return d.info.Reset.Out(level)
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) StartTransfer() error {
|
||||
switch d.conn.(type) {
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) EndTransfer() error {
|
||||
switch d.conn.(type) {
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) SendCommand(data []byte) error {
|
||||
return d.conn.Tx(append([]byte{0x00}, data...), nil)
|
||||
}
|
||||
|
||||
func (d *ssd13xxDisplay) SendData(data []byte) error {
|
||||
return d.conn.Tx(append([]byte{0x40}, data...), nil)
|
||||
}
|
||||
|
||||
func LookupPinOut(name string) (gpio.PinOut, error) {
|
||||
pin := gpioreg.ByName(name)
|
||||
if pin == nil || pin == gpio.INVALID {
|
||||
return nil, fmt.Errorf("invalid GPIO pin %q: not found", name)
|
||||
}
|
||||
return pin, nil
|
||||
}
|
||||
|
||||
// Interface check.
|
||||
var (
|
||||
_ MonochromeDisplay = &ssd13xxDisplay{}
|
||||
)
|
||||
@@ -0,0 +1,195 @@
|
||||
// Package oled contains common routines for driving OLEDs.
|
||||
package oled
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/i2c"
|
||||
"periph.io/x/conn/v3/i2c/i2creg"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
"periph.io/x/conn/v3/spi/spireg"
|
||||
)
|
||||
|
||||
type Bus interface {
|
||||
// Halt the bus.
|
||||
Halt() error
|
||||
|
||||
// Tx transfers bytes.
|
||||
Tx(data []byte, isCommand bool) error
|
||||
|
||||
String() string
|
||||
}
|
||||
|
||||
func NewBus(config *config.Display) (Bus, error) {
|
||||
if config.Bus == "" || strings.HasPrefix(config.Bus, "i2c") {
|
||||
return newI2C(config)
|
||||
}
|
||||
return newSPI(config)
|
||||
}
|
||||
|
||||
type I2C struct {
|
||||
bus i2c.BusCloser
|
||||
conn *i2c.Dev
|
||||
}
|
||||
|
||||
func newI2C(config *config.Display) (Bus, error) {
|
||||
addr, err := display.ParseI2CAddress(config.Address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid I2C address %q: %w", config.Address, err)
|
||||
}
|
||||
|
||||
bus, err := i2creg.Open(config.Bus)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error opening I2C bus %q: %w", config.Bus, err)
|
||||
}
|
||||
|
||||
return &I2C{
|
||||
bus: bus,
|
||||
conn: &i2c.Dev{Bus: bus, Addr: addr},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (bus *I2C) Halt() error {
|
||||
return bus.bus.Close()
|
||||
}
|
||||
|
||||
func (bus *I2C) Tx(data []byte, isCommand bool) error {
|
||||
if isCommand {
|
||||
return bus.conn.Tx(append([]byte{0x00}, data...), nil)
|
||||
}
|
||||
return bus.conn.Tx(append([]byte{0x40}, data...), nil)
|
||||
}
|
||||
|
||||
func (bus *I2C) String() string {
|
||||
return "I²C"
|
||||
}
|
||||
|
||||
type SPI struct {
|
||||
Reset gpio.PinOut
|
||||
DC gpio.PinOut
|
||||
CS gpio.PinOut
|
||||
port spi.PortCloser
|
||||
conn spi.Conn
|
||||
}
|
||||
|
||||
func newSPI(config *config.Display) (Bus, error) {
|
||||
var (
|
||||
freq physic.Frequency = 800 * physic.KiloHertz
|
||||
reset, dc, cs gpio.PinOut
|
||||
err error
|
||||
)
|
||||
if config.Freq != "" {
|
||||
if err = freq.Set(config.Freq); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if reset, err = display.LookupPinOut(config.Reset); err != nil {
|
||||
return nil, fmt.Errorf("invalid reset pin %q: %w", config.Reset, err)
|
||||
}
|
||||
if dc, err = display.LookupPinOut(config.DC); err != nil {
|
||||
return nil, fmt.Errorf("invalid dc pin %q: %w", config.DC, err)
|
||||
}
|
||||
if cs, err = display.LookupPinOut(config.CS); err != nil {
|
||||
return nil, fmt.Errorf("invalid cs pin %q: %w", config.CS, err)
|
||||
}
|
||||
|
||||
port, err := spireg.Open(config.Port)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening SPI port %q failed: %w", config.Port, err)
|
||||
}
|
||||
|
||||
conn, err := port.Connect(freq, spi.Mode0, 8)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connecting on SPI port %q failed: %w", config.Port, err)
|
||||
}
|
||||
|
||||
bus := &SPI{
|
||||
Reset: reset,
|
||||
DC: dc,
|
||||
CS: cs,
|
||||
port: port,
|
||||
conn: conn,
|
||||
}
|
||||
if err = bus.reset(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bus, nil
|
||||
}
|
||||
|
||||
func (bus *SPI) Halt() error {
|
||||
return bus.port.Close()
|
||||
}
|
||||
|
||||
func (bus *SPI) reset() (err error) {
|
||||
if err = bus.CS.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.DC.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.Reset.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = bus.Reset.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
if err = bus.Reset.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if err = bus.Reset.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bus *SPI) Tx(data []byte, isCommand bool) (err error) {
|
||||
if isCommand {
|
||||
if err = bus.CS.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
if err = bus.DC.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.CS.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.conn.Tx(data, nil); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.CS.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err = bus.CS.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
if err = bus.DC.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.CS.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.conn.Tx(data, nil); err != nil {
|
||||
return
|
||||
}
|
||||
if err = bus.CS.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bus *SPI) String() string {
|
||||
return "SPI"
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
)
|
||||
|
||||
// NotFound is an error.
|
||||
type NotFound struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
func (err NotFound) Error() string {
|
||||
return fmt.Sprintf("display %q is not available", err.Name)
|
||||
}
|
||||
|
||||
var (
|
||||
drivers = new(sync.Map)
|
||||
instances = new(sync.Map)
|
||||
)
|
||||
|
||||
// Factory creates a new display driver.
|
||||
type Factory func(config *config.Display) (Display, error)
|
||||
|
||||
// Register a new display driver.
|
||||
func Register(driver string, f Factory) {
|
||||
if _, loaded := drivers.LoadOrStore(driver, f); loaded {
|
||||
panic(fmt.Sprintf("display driver %q already registered", driver))
|
||||
}
|
||||
}
|
||||
|
||||
// New display driver.
|
||||
func New(config *config.Display) (Display, error) {
|
||||
f, ok := drivers.Load(config.Type)
|
||||
if ok {
|
||||
d, err := f.(Factory)(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
instances.Store(config.Name, d)
|
||||
return d, nil
|
||||
}
|
||||
return nil, NotFound{Name: config.Type}
|
||||
}
|
||||
|
||||
// Lookup a previously instantiated display driver by name.
|
||||
func Lookup(name string) (Display, error) {
|
||||
d, ok := instances.Load(name)
|
||||
if ok {
|
||||
return d.(Display), nil
|
||||
}
|
||||
return nil, NotFound{Name: name}
|
||||
}
|
||||
|
||||
// List returns all registered drivers.
|
||||
func List() []string {
|
||||
var s []string
|
||||
drivers.Range(func(k, v any) bool {
|
||||
s = append(s, k.(string))
|
||||
return true
|
||||
})
|
||||
sort.Strings(s)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package sh1106
|
||||
|
||||
// Registers
|
||||
const (
|
||||
Address = 0x3C
|
||||
|
||||
SETCONTRAST = 0x81
|
||||
DISPLAYALLON_RESUME = 0xA4
|
||||
DISPLAYALLON = 0xA5
|
||||
NORMALDISPLAY = 0xA6
|
||||
INVERTDISPLAY = 0xA7
|
||||
DISPLAYOFF = 0xAE
|
||||
DISPLAYON = 0xAF
|
||||
SETDISPLAYOFFSET = 0xD3
|
||||
SETCOMPINS = 0xDA
|
||||
SETVCOMDETECT = 0xDB
|
||||
SETDISPLAYCLOCKDIV = 0xD5
|
||||
SETPRECHARGE = 0xD9
|
||||
SETMULTIPLEX = 0xA8
|
||||
SETLOWCOLUMN = 0x00
|
||||
SETHIGHCOLUMN = 0x10
|
||||
SETSTARTLINE = 0x40
|
||||
MEMORYMODE = 0x20
|
||||
COLUMNADDR = 0x21
|
||||
PAGEADDR = 0x22
|
||||
COMSCANINC = 0xC0
|
||||
COMSCANDEC = 0xC8
|
||||
SEGREMAP = 0xA0
|
||||
CHARGEPUMP = 0x8D
|
||||
ACTIVATE_SCROLL = 0x2F
|
||||
DEACTIVATE_SCROLL = 0x2E
|
||||
SET_VERTICAL_SCROLL_AREA = 0xA3
|
||||
RIGHT_HORIZONTAL_SCROLL = 0x26
|
||||
LEFT_HORIZONTAL_SCROLL = 0x27
|
||||
VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29
|
||||
VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A
|
||||
|
||||
EXTERNALVCC VccMode = 0x1
|
||||
SWITCHCAPVCC VccMode = 0x2
|
||||
)
|
||||
@@ -0,0 +1,278 @@
|
||||
package sh1106
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"time"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/display/oled"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("sh1106", newDevice)
|
||||
}
|
||||
|
||||
func newDevice(config *config.Display) (display.Display, error) {
|
||||
width, height, err := display.ParseSize(config.Size, 128, 0)
|
||||
if err != nil || height == 0 {
|
||||
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||
}
|
||||
|
||||
/*
|
||||
rotation, err := display.ParseRotation(config.Rotate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*/
|
||||
|
||||
bus, err := oled.NewBus(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dev := &Device{
|
||||
bus: bus,
|
||||
}
|
||||
if err = dev.Configure(Config{
|
||||
Width: int16(width),
|
||||
Height: int16(height),
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dev, nil
|
||||
}
|
||||
|
||||
// Device wraps an SPI connection.
|
||||
type Device struct {
|
||||
bus oled.Bus
|
||||
buffer pixel.Image[pixel.Monochrome]
|
||||
width int16
|
||||
height int16
|
||||
bufferSize int16
|
||||
vccState VccMode
|
||||
}
|
||||
|
||||
// Config is the configuration for the display
|
||||
type Config struct {
|
||||
Width int16
|
||||
Height int16
|
||||
VccState VccMode
|
||||
}
|
||||
|
||||
type VccMode uint8
|
||||
|
||||
// Configure initializes the display with default configuration
|
||||
func (d *Device) Configure(cfg Config) error {
|
||||
if cfg.Width != 0 {
|
||||
d.width = cfg.Width
|
||||
} else {
|
||||
d.width = 128
|
||||
}
|
||||
if cfg.Height != 0 {
|
||||
d.height = cfg.Height
|
||||
} else {
|
||||
d.height = 64
|
||||
}
|
||||
if cfg.VccState != 0 {
|
||||
d.vccState = cfg.VccState
|
||||
} else {
|
||||
d.vccState = SWITCHCAPVCC
|
||||
}
|
||||
d.bufferSize = d.width * d.height / 8
|
||||
d.buffer = pixel.NewImage[pixel.Monochrome](int(d.width), int(d.height)) //make([]byte, d.bufferSize)
|
||||
|
||||
time.Sleep(100 * time.Nanosecond)
|
||||
d.Command(DISPLAYOFF)
|
||||
d.Command(SETDISPLAYCLOCKDIV)
|
||||
d.Command(0x80)
|
||||
d.Command(SETMULTIPLEX)
|
||||
d.Command(uint8(d.height - 1))
|
||||
d.Command(SETDISPLAYOFFSET)
|
||||
d.Command(0x0)
|
||||
d.Command(SETSTARTLINE | 0x0)
|
||||
d.Command(CHARGEPUMP)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x10)
|
||||
} else {
|
||||
d.Command(0x14)
|
||||
}
|
||||
d.Command(MEMORYMODE)
|
||||
d.Command(0x00)
|
||||
d.Command(SEGREMAP | 0x1)
|
||||
d.Command(COMSCANDEC)
|
||||
|
||||
if (d.width == 128 && d.height == 64) || (d.width == 64 && d.height == 48) { // 128x64 or 64x48
|
||||
d.Command(SETCOMPINS)
|
||||
d.Command(0x12)
|
||||
d.Command(SETCONTRAST)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x9F)
|
||||
} else {
|
||||
d.Command(0xCF)
|
||||
}
|
||||
} else if d.width == 128 && d.height == 32 { // 128x32
|
||||
d.Command(SETCOMPINS)
|
||||
d.Command(0x02)
|
||||
d.Command(SETCONTRAST)
|
||||
d.Command(0x8F)
|
||||
} else if d.width == 96 && d.height == 16 { // 96x16
|
||||
d.Command(SETCOMPINS)
|
||||
d.Command(0x2)
|
||||
d.Command(SETCONTRAST)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x10)
|
||||
} else {
|
||||
d.Command(0xAF)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("sh1106: no configuration for %dx%d", d.width, d.height)
|
||||
}
|
||||
|
||||
d.Command(SETPRECHARGE)
|
||||
if d.vccState == EXTERNALVCC {
|
||||
d.Command(0x22)
|
||||
} else {
|
||||
d.Command(0xF1)
|
||||
}
|
||||
d.Command(SETVCOMDETECT)
|
||||
d.Command(0x40)
|
||||
d.Command(DISPLAYALLON_RESUME)
|
||||
d.Command(NORMALDISPLAY)
|
||||
d.Command(DEACTIVATE_SCROLL)
|
||||
d.Command(DISPLAYON)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearBuffer clears the image buffer
|
||||
func (d *Device) ClearBuffer() {
|
||||
d.buffer.Clear()
|
||||
}
|
||||
|
||||
// ClearDisplay clears the image buffer and clear the display
|
||||
func (d *Device) ClearDisplay() {
|
||||
d.buffer.Clear()
|
||||
d.Refresh()
|
||||
}
|
||||
|
||||
// Refresh sends the whole buffer to the screen
|
||||
func (d *Device) Refresh() error {
|
||||
// In the 128x64 (SPI) screen resetting to 0x0 after 128 times corrupt the buffer
|
||||
// Since we're printing the whole buffer, avoid resetting it
|
||||
if d.width != 128 || d.height != 64 {
|
||||
d.Command(COLUMNADDR)
|
||||
d.Command(0)
|
||||
d.Command(uint8(d.width - 1))
|
||||
d.Command(PAGEADDR)
|
||||
d.Command(0)
|
||||
d.Command(uint8(d.height/8) - 1)
|
||||
}
|
||||
|
||||
raw := d.buffer.RawBuffer()
|
||||
for pg := uint8(0); pg < uint8(d.height/8); pg++ {
|
||||
d.Command(0xB0 | (pg & 0x07)) // SET_PAGE_ADDR
|
||||
d.Command(SETLOWCOLUMN | 2)
|
||||
d.Command(SETHIGHCOLUMN | 0)
|
||||
d.Tx(raw[uint16(pg)*0x80:uint16(pg+1)*0x80], false)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetPixel enables or disables a pixel in the buffer
|
||||
// color.RGBA{0, 0, 0, 255} is consider transparent, anything else
|
||||
// with enable a pixel on the screen
|
||||
func (d *Device) SetPixel(x int16, y int16, c color.Color) {
|
||||
/*
|
||||
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||
return
|
||||
}
|
||||
byteIndex := x + (y/8)*d.width
|
||||
if c.R != 0 || c.G != 0 || c.B != 0 {
|
||||
d.buffer[byteIndex] |= 1 << uint8(y%8)
|
||||
} else {
|
||||
d.buffer[byteIndex] &^= 1 << uint8(y%8)
|
||||
}
|
||||
*/
|
||||
c = pixel.MonochromeModel.Convert(c)
|
||||
d.buffer.SetPixel(int(x), int(y), c.(pixel.Monochrome))
|
||||
}
|
||||
|
||||
// GetPixel returns if the specified pixel is on (true) or off (false)
|
||||
func (d *Device) GetPixel(x int16, y int16) color.Color {
|
||||
/*
|
||||
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||
return pixel.Off
|
||||
}
|
||||
byteIndex := x + (y/8)*d.width
|
||||
return (d.buffer[byteIndex] >> uint8(y%8) & 0x1) == 1
|
||||
*/
|
||||
return d.buffer.GetPixel(int(x), int(y))
|
||||
}
|
||||
|
||||
/*
|
||||
// SetBuffer changes the whole buffer at once
|
||||
func (d *Device) SetBuffer(buffer []byte) error {
|
||||
if int16(len(buffer)) != d.bufferSize {
|
||||
//return ErrBuffer
|
||||
return errors.New("wrong size buffer")
|
||||
}
|
||||
for i := int16(0); i < d.bufferSize; i++ {
|
||||
d.buffer[i] = buffer[i]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
*/
|
||||
|
||||
// Command sends a command to the display
|
||||
func (d *Device) Command(command uint8) error {
|
||||
return d.bus.Tx([]byte{command}, true)
|
||||
}
|
||||
|
||||
// Tx sends data to the display
|
||||
func (d *Device) Tx(data []byte, isCommand bool) error {
|
||||
return d.bus.Tx(data, isCommand)
|
||||
}
|
||||
|
||||
/* display.Image interface methods */
|
||||
|
||||
func (d *Device) At(x, y int) color.Color {
|
||||
return d.buffer.At(x, y)
|
||||
}
|
||||
|
||||
func (d *Device) Bounds() image.Rectangle {
|
||||
return d.buffer.Bounds()
|
||||
}
|
||||
|
||||
func (Device) ColorModel() color.Model {
|
||||
return pixel.MonochromeModel
|
||||
}
|
||||
|
||||
func (d *Device) Halt() error {
|
||||
return d.bus.Halt()
|
||||
}
|
||||
|
||||
func (d *Device) Set(x, y int, c color.Color) {
|
||||
d.buffer.Set(x, y, c)
|
||||
}
|
||||
|
||||
// Size returns the current size of the display.
|
||||
func (d *Device) Size() image.Point {
|
||||
return image.Pt(int(d.width), int(d.height))
|
||||
}
|
||||
|
||||
func (d *Device) String() string {
|
||||
return "sh1106@" + d.bus.String()
|
||||
}
|
||||
|
||||
/* display.imageDrawer interface methods */
|
||||
|
||||
func (d *Device) DrawImage(img image.Image) error {
|
||||
draw.Draw(d.buffer, d.buffer.Bounds(), img, image.Point{}, draw.Src)
|
||||
return d.Refresh()
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// Package ssd1305 provides a driver for the SSD1305 OLED controller.
|
||||
package ssd1305
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"time"
|
||||
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/i2c"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
var defaultInfo = display.MonochromeDisplayInfo{
|
||||
ResetPulseWidth: 100 * time.Millisecond,
|
||||
ResetWait: 100 * time.Millisecond,
|
||||
PreChipEnableWait: 10 * time.Nanosecond,
|
||||
PostChipEnableWait: 20 * time.Nanosecond,
|
||||
DataSetupTime: 40 * time.Nanosecond,
|
||||
WritePulseWidth: 150 * time.Nanosecond,
|
||||
Width: 128,
|
||||
Height: 32,
|
||||
}
|
||||
|
||||
const (
|
||||
spiMode spi.Mode = spi.Mode0
|
||||
spiSpeed physic.Frequency = 4 * 1000 * 1000
|
||||
maxPixels = 256 * 32
|
||||
)
|
||||
|
||||
var emptyBuf [maxPixels >> 3]byte
|
||||
|
||||
type Device struct {
|
||||
hal display.MonochromeDisplay
|
||||
info display.MonochromeDisplayInfo
|
||||
buf pixel.Image[pixel.Monochrome]
|
||||
}
|
||||
|
||||
func NewI2C(bus i2c.Bus, addr uint16, width, height int) (*Device, error) {
|
||||
if addr == 0 {
|
||||
addr = 0x3c
|
||||
}
|
||||
|
||||
if width <= 0 {
|
||||
width = int(defaultInfo.Width)
|
||||
}
|
||||
if height <= 0 {
|
||||
height = int(defaultInfo.Height)
|
||||
}
|
||||
|
||||
var info = new(display.MonochromeDisplayInfo)
|
||||
*info = defaultInfo
|
||||
info.Width = uint16(width)
|
||||
info.Height = uint16(height)
|
||||
|
||||
c := &i2c.Dev{Bus: bus, Addr: addr}
|
||||
d := &Device{
|
||||
hal: display.NewSSD13xxDisplay(c, *info),
|
||||
info: *info,
|
||||
buf: pixel.NewImage[pixel.Monochrome](width, height),
|
||||
}
|
||||
if err := d.configure(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func NewSPI(port spi.Port, reset gpio.PinOut, width, height uint8) (*Device, error) {
|
||||
var info = new(display.MonochromeDisplayInfo)
|
||||
*info = defaultInfo
|
||||
info.Reset = reset
|
||||
|
||||
c, err := port.Connect(spiSpeed, spiMode, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := &Device{
|
||||
hal: display.NewSSD13xxDisplay(c, *info),
|
||||
}
|
||||
if err := d.configure(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *Device) configure() (err error) {
|
||||
if err = d.hal.Init(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = d.hal.StartTransfer(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = d.hal.SendCommand([]byte{
|
||||
0xae, // Set display off
|
||||
0xd5, 0x80, // Set display clock divide ratio/oscillator frequency
|
||||
0xa8, 0x3f, // Set multiplex ratio
|
||||
0xd3, uint8(d.info.Width), // Set display offset
|
||||
0x40, // Set display start line to 0
|
||||
0x20, 0x00, // Set horizontal addressing mode
|
||||
0xa1, // Set segment remap a0/a1
|
||||
0xc8, // Set scan direction (c0: normal, c8: reverse,
|
||||
0xda, 0x12, // Set com pins hardware configuration
|
||||
0x81, 0xcf, // Set contrast control
|
||||
0xd9, 0xf1, // Set pre-charge period
|
||||
0xdb, 0x40, // Set VCOMH deselect level
|
||||
0x2e, // Deactivate scroll
|
||||
0xa4, // Set display output RAM to display
|
||||
0xa6, // Set normal display mode
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return d.hal.EndTransfer()
|
||||
}
|
||||
|
||||
func (d *Device) Clear() error {
|
||||
d.buf.FillSolidColor(pixel.Off)
|
||||
return d.Refresh()
|
||||
}
|
||||
|
||||
func (d *Device) Refresh() (err error) {
|
||||
_ = d.hal.SendCommand([]byte{0x15, 0, byte(defaultInfo.Width) - 1}) // Set column address
|
||||
_ = d.hal.SendCommand([]byte{0x75, 0, byte(defaultInfo.Height) - 1}) // Set row address
|
||||
buf := d.buf.RawBuffer()
|
||||
for i := 0; i < len(buf); i += 16 {
|
||||
if err = d.hal.SendData(buf[i : i+16]); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (d *Device) Size() (width, height int) {
|
||||
return d.buf.Bounds().Dx(), d.buf.Bounds().Dy()
|
||||
}
|
||||
|
||||
func (d *Device) Bounds() image.Rectangle {
|
||||
return d.buf.Bounds()
|
||||
}
|
||||
|
||||
func (d *Device) ColorModel() color.Model {
|
||||
return pixel.MonochromeModel
|
||||
}
|
||||
|
||||
func (d *Device) At(x, y int) color.Color {
|
||||
return d.buf.At(x, y)
|
||||
}
|
||||
|
||||
func (d *Device) Set(x, y int, c color.Color) {
|
||||
d.buf.Set(x, y, c)
|
||||
}
|
||||
|
||||
// Interface check
|
||||
var (
|
||||
// _ display.Display = &Device{}
|
||||
// _ display.Image = &Device{}
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
package ssd1306
|
||||
|
||||
const (
|
||||
_CHARGEPUMP = 0x8D
|
||||
_COLUMNADDR = 0x21
|
||||
_COMSCANDEC = 0xC8
|
||||
_COMSCANINC = 0xC0
|
||||
_DISPLAYALLON = 0xA5
|
||||
_DISPLAYALLON_RESUME = 0xA4
|
||||
_DISPLAYOFF = 0xAE
|
||||
_DISPLAYON = 0xAF
|
||||
_EXTERNALVCC = 0x1
|
||||
_INVERTDISPLAY = 0xA7
|
||||
_MEMORYMODE = 0x20
|
||||
_NORMALDISPLAY = 0xA6
|
||||
_PAGEADDR = 0x22
|
||||
_PAGESTARTADDRESS = 0xB0
|
||||
_SEGREMAP = 0xA0
|
||||
_SETCOMPINS = 0xDA
|
||||
_SETCONTRAST = 0x81
|
||||
_SETDISPLAYCLOCKDIV = 0xD5
|
||||
_SETDISPLAYOFFSET = 0xD3
|
||||
_SETHIGHCOLUMN = 0x10
|
||||
_SETLOWCOLUMN = 0x00
|
||||
_SETMULTIPLEX = 0xA8
|
||||
_SETPRECHARGE = 0xD9
|
||||
_SETSEGMENTREMAP = 0xA1
|
||||
_SETSTARTLINE = 0x40
|
||||
_SETVCOMDETECT = 0xDB
|
||||
_SWITCHCAPVCC = 0x2
|
||||
)
|
||||
|
||||
// FrameRate determines scrolling speed.
|
||||
type FrameRate byte
|
||||
|
||||
// Possible frame rates. The value determines the number of refreshes between
|
||||
// movement. The lower value, the higher speed.
|
||||
const (
|
||||
FrameRate2 FrameRate = 7
|
||||
FrameRate3 FrameRate = 4
|
||||
FrameRate4 FrameRate = 5
|
||||
FrameRate5 FrameRate = 0
|
||||
FrameRate25 FrameRate = 6
|
||||
FrameRate64 FrameRate = 1
|
||||
FrameRate128 FrameRate = 2
|
||||
FrameRate256 FrameRate = 3
|
||||
)
|
||||
|
||||
// Orientation is used for scrolling.
|
||||
type Orientation byte
|
||||
|
||||
// Possible orientations for scrolling.
|
||||
const (
|
||||
Left Orientation = 0x27
|
||||
Right Orientation = 0x26
|
||||
UpRight Orientation = 0x29
|
||||
UpLeft Orientation = 0x2A
|
||||
)
|
||||
@@ -0,0 +1,562 @@
|
||||
package ssd1306
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/conn/v3"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||
"periph.io/x/conn/v3/i2c"
|
||||
"periph.io/x/conn/v3/i2c/i2creg"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
"periph.io/x/conn/v3/spi/spireg"
|
||||
"periph.io/x/devices/v3/ssd1306/image1bit"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("ssd1306", newDevice)
|
||||
}
|
||||
|
||||
// DefaultOpts is the recommended default options.
|
||||
var DefaultOpts = Opts{
|
||||
W: 128,
|
||||
H: 64,
|
||||
Addr: 0x3c,
|
||||
Rotated: false,
|
||||
MirrorVertical: false,
|
||||
MirrorHorizontal: false,
|
||||
Sequential: false,
|
||||
SwapTopBottom: false,
|
||||
}
|
||||
|
||||
// Opts defines the options for the device.
|
||||
type Opts struct {
|
||||
W int
|
||||
H int
|
||||
|
||||
// Addr is the I2C address.
|
||||
Addr uint16
|
||||
|
||||
// Rotated determines if the display is rotated by 180°.
|
||||
//
|
||||
// Deprecated: Use MirrorVertical and MirrorHorizontal instead.
|
||||
Rotated bool
|
||||
|
||||
// Sequential corresponds to the Sequential/Alternative COM pin configuration
|
||||
// in the OLED panel hardware. Try toggling this if half the rows appear to be
|
||||
// missing on your display.
|
||||
Sequential bool
|
||||
|
||||
// MirrorVertical corresponds to the COM remap configuration in the OLED panel
|
||||
// hardware. Try toggling this if the display is flipped vertically.
|
||||
// Overwrites Rotated.
|
||||
MirrorVertical bool
|
||||
|
||||
// MirrorHorizontal corresponds to the SEG remap configuration in the OLED panel
|
||||
// hardware. Try toggling this if the display is flipped horizontally.
|
||||
// Overwrites Rotated.
|
||||
MirrorHorizontal bool
|
||||
|
||||
// SwapTopBottom corresponds to the Left/Right remap COM pin configuration in
|
||||
// the OLED panel hardware. Try toggling this if the top and bottom halves of
|
||||
// your display are swapped.
|
||||
SwapTopBottom bool
|
||||
}
|
||||
|
||||
type Dev struct {
|
||||
// Communication
|
||||
c conn.Conn
|
||||
dc gpio.PinOut
|
||||
spi bool
|
||||
|
||||
// Display size controlled by the SSD1306.
|
||||
rect image.Rectangle
|
||||
|
||||
// Mutable
|
||||
// See page 25 for the GDDRAM pages structure.
|
||||
// Narrow screen will waste the end of each page.
|
||||
// Short screen will ignore the lower pages.
|
||||
// There is 8 pages, each covering an horizontal band of 8 pixels high (1
|
||||
// byte) for 128 bytes.
|
||||
// 8*128 = 1024 bytes total for 128x64 display.
|
||||
buffer []byte
|
||||
// next is lazy initialized on first Draw(). Write() skips this buffer.
|
||||
next *image1bit.VerticalLSB
|
||||
startPage, endPage int
|
||||
startCol, endCol int
|
||||
scrolled bool
|
||||
halted bool
|
||||
}
|
||||
|
||||
func newDevice(config *config.Display) (display.Display, error) {
|
||||
width, height, err := display.ParseSize(config.Size, DefaultOpts.W, DefaultOpts.H)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||
}
|
||||
|
||||
opts := new(Opts)
|
||||
*opts = DefaultOpts
|
||||
opts.W = width
|
||||
opts.H = height
|
||||
|
||||
if config.Bus == "" || strings.HasPrefix(config.Bus, "i2c") {
|
||||
return newI2C(config, opts)
|
||||
}
|
||||
return newSPI(config, opts)
|
||||
}
|
||||
|
||||
func newI2C(config *config.Display, opts *Opts) (display.Display, error) {
|
||||
addr, err := display.ParseI2CAddress(config.Address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid I2C address %q: %w", config.Address, err)
|
||||
}
|
||||
|
||||
log := logrus.WithFields(logrus.Fields{
|
||||
"type": "ssd1306",
|
||||
"size": fmt.Sprintf("%dx%d", opts.W, opts.H),
|
||||
"mode": "i2c",
|
||||
})
|
||||
log.WithField("bus", config.Bus).Debug("opening I2C bus")
|
||||
|
||||
bus, err := i2creg.Open(config.Bus)
|
||||
if err != nil {
|
||||
log.WithField("bus", config.Bus).WithError(err).Warn("opening I2C bus failed")
|
||||
return nil, fmt.Errorf("error opening I2C bus %q: %w", config.Bus, err)
|
||||
}
|
||||
|
||||
log = log.WithFields(logrus.Fields{
|
||||
"i2c_bus": bus.String(),
|
||||
"i2c_addr": fmt.Sprintf("%#02x", addr),
|
||||
})
|
||||
log.Debug("starting display")
|
||||
return newDev(&i2c.Dev{Bus: bus, Addr: addr}, opts, false, nil)
|
||||
}
|
||||
|
||||
func newSPI(config *config.Display, opts *Opts) (display.Display, error) {
|
||||
var (
|
||||
dc gpio.PinOut
|
||||
bits = 9
|
||||
)
|
||||
if config.DC != "" {
|
||||
if dc = gpioreg.ByName(config.DC); dc == gpio.INVALID {
|
||||
return nil, fmt.Errorf("invalid dc pin %q", config.DC)
|
||||
}
|
||||
bits = 8
|
||||
}
|
||||
|
||||
port, err := spireg.Open(config.Port)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening SPI port %q failed: %w", config.Port, err)
|
||||
}
|
||||
|
||||
c, err := port.Connect(3300*physic.KiloHertz, spi.Mode0, bits)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connecting on SPI port %q failed: %w", config.Port, err)
|
||||
}
|
||||
|
||||
return newDev(c, opts, true, dc)
|
||||
}
|
||||
|
||||
func (d *Dev) String() string {
|
||||
if d.spi {
|
||||
return fmt.Sprintf("ssd1360.Dev{%s, %s, %s}", d.c, d.dc, d.rect.Max)
|
||||
}
|
||||
return fmt.Sprintf("ssd1360.Dev{%s, %s}", d.c, d.rect.Max)
|
||||
}
|
||||
|
||||
// ColorModel implements display.Drawer.
|
||||
//
|
||||
// It is a one bit color model, as implemented by image1bit.Bit.
|
||||
func (d *Dev) ColorModel() color.Model {
|
||||
return image1bit.BitModel
|
||||
}
|
||||
|
||||
// Bounds implements display.Drawer. Min is guaranteed to be {0, 0}.
|
||||
func (d *Dev) Bounds() image.Rectangle {
|
||||
return d.rect
|
||||
}
|
||||
|
||||
// Draw implements display.Drawer.
|
||||
//
|
||||
// It draws synchronously, once this function returns, the display is updated.
|
||||
// It means that on slow bus (I²C), it may be preferable to defer Draw() calls
|
||||
// to a background goroutine.
|
||||
func (d *Dev) Draw(r image.Rectangle, src image.Image, sp image.Point) error {
|
||||
var next []byte
|
||||
if img, ok := src.(*image1bit.VerticalLSB); ok && r == d.rect && img.Rect == d.rect && sp.X == 0 && sp.Y == 0 {
|
||||
// Exact size, full frame, image1bit encoding: fast path!
|
||||
next = img.Pix
|
||||
} else {
|
||||
// Double buffering.
|
||||
if d.next == nil {
|
||||
d.next = image1bit.NewVerticalLSB(d.rect)
|
||||
}
|
||||
next = d.next.Pix
|
||||
draw.Src.Draw(d.next, r, src, sp)
|
||||
}
|
||||
return d.drawInternal(next)
|
||||
}
|
||||
|
||||
// DrawImage implements display.imageDrawer.
|
||||
func (d *Dev) DrawImage(src image.Image) error {
|
||||
return d.Draw(d.Bounds(), src, image.Point{})
|
||||
}
|
||||
|
||||
// Write writes a buffer of pixels to the display.
|
||||
//
|
||||
// The format is unsual as each byte represent 8 vertical pixels at a time. The
|
||||
// format is horizontal bands of 8 pixels high.
|
||||
//
|
||||
// This function accepts the content of image1bit.VerticalLSB.Pix.
|
||||
func (d *Dev) Write(pixels []byte) (int, error) {
|
||||
if len(pixels) != len(d.buffer) {
|
||||
return 0, fmt.Errorf("ssd1306: invalid pixel stream length; expected %d bytes, got %d bytes", len(d.buffer), len(pixels))
|
||||
}
|
||||
// Write() skips d.next so it saves 1kb of RAM.
|
||||
if err := d.drawInternal(pixels); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(pixels), nil
|
||||
}
|
||||
|
||||
// Scroll scrolls an horizontal band.
|
||||
//
|
||||
// Only one scrolling operation can happen at a time.
|
||||
//
|
||||
// Both startLine and endLine must be multiples of 8.
|
||||
//
|
||||
// Use -1 for endLine to extend to the bottom of the display.
|
||||
func (d *Dev) Scroll(o Orientation, rate FrameRate, startLine, endLine int) error {
|
||||
h := d.rect.Dy()
|
||||
if endLine == -1 {
|
||||
endLine = h
|
||||
}
|
||||
if startLine >= endLine {
|
||||
return fmt.Errorf("startLine (%d) must be lower than endLine (%d)", startLine, endLine)
|
||||
}
|
||||
if startLine&7 != 0 || startLine < 0 || startLine >= h {
|
||||
return fmt.Errorf("invalid startLine %d", startLine)
|
||||
}
|
||||
if endLine&7 != 0 || endLine < 0 || endLine > h {
|
||||
return fmt.Errorf("invalid endLine %d", endLine)
|
||||
}
|
||||
|
||||
startPage := uint8(startLine / 8)
|
||||
endPage := uint8(endLine / 8)
|
||||
d.scrolled = true
|
||||
if o == Left || o == Right {
|
||||
// page 28
|
||||
// <op>, dummy, <start page>, <rate>, <end page>, <dummy>, <dummy>, <ENABLE>
|
||||
return d.sendCommand([]byte{byte(o), 0x00, startPage, byte(rate), endPage - 1, 0x00, 0xFF, 0x2F})
|
||||
}
|
||||
// page 29
|
||||
// <op>, dummy, <start page>, <rate>, <end page>, <offset>, <ENABLE>
|
||||
// page 30: 0xA3 permits to set rows for scroll area.
|
||||
return d.sendCommand([]byte{byte(o), 0x00, startPage, byte(rate), endPage - 1, 0x01, 0x2F})
|
||||
}
|
||||
|
||||
// StopScroll stops any scrolling previously set and resets the screen.
|
||||
func (d *Dev) StopScroll() error {
|
||||
return d.sendCommand([]byte{0x2E})
|
||||
}
|
||||
|
||||
// SetContrast changes the screen contrast.
|
||||
//
|
||||
// Note: values other than 0xff do not seem useful...
|
||||
func (d *Dev) SetContrast(level byte) error {
|
||||
return d.sendCommand([]byte{0x81, level})
|
||||
}
|
||||
|
||||
// SetDisplayStartLine causes the display to start from startLine, effectively
|
||||
// scrolling the screen to that position.
|
||||
//
|
||||
// startLine must be between 0 and 63.
|
||||
func (d *Dev) SetDisplayStartLine(startLine byte) error {
|
||||
if startLine > 63 {
|
||||
return fmt.Errorf("ssd1306: invalid startLine %d", startLine)
|
||||
}
|
||||
return d.sendCommand([]byte{_SETSTARTLINE | startLine})
|
||||
}
|
||||
|
||||
// Halt turns off the display.
|
||||
//
|
||||
// Sending any other command afterward reenables the display.
|
||||
func (d *Dev) Halt() error {
|
||||
d.halted = false
|
||||
err := d.sendCommand([]byte{0xAE})
|
||||
if err == nil {
|
||||
d.halted = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Invert the display (black on white vs white on black).
|
||||
func (d *Dev) Invert(blackOnWhite bool) error {
|
||||
b := []byte{0xA6}
|
||||
if blackOnWhite {
|
||||
b[0] = 0xA7
|
||||
}
|
||||
return d.sendCommand(b)
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
// newDev is the common initialization code that is independent of the
|
||||
// communication protocol (I²C or SPI) being used.
|
||||
func newDev(c conn.Conn, opts *Opts, usingSPI bool, dc gpio.PinOut) (*Dev, error) {
|
||||
if opts.W < 8 || opts.W > 128 || opts.W&7 != 0 {
|
||||
return nil, fmt.Errorf("ssd1306: invalid width %d", opts.W)
|
||||
}
|
||||
if opts.H < 8 || opts.H > 64 || opts.H&7 != 0 {
|
||||
return nil, fmt.Errorf("ssd1306: invalid height %d", opts.H)
|
||||
}
|
||||
|
||||
nbPages := opts.H / 8
|
||||
pageSize := opts.W
|
||||
d := &Dev{
|
||||
c: c,
|
||||
spi: usingSPI,
|
||||
dc: dc,
|
||||
rect: image.Rect(0, 0, opts.W, opts.H),
|
||||
buffer: make([]byte, nbPages*pageSize),
|
||||
startPage: 0,
|
||||
endPage: nbPages,
|
||||
startCol: 0,
|
||||
endCol: opts.W,
|
||||
// Signal that the screen must be redrawn on first draw().
|
||||
scrolled: true,
|
||||
}
|
||||
if err := d.sendCommand(getInitCmd(opts)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func getInitCmd(opts *Opts) []byte {
|
||||
// Set COM output scan direction; C0 means normal; C8 means reversed
|
||||
comScan := byte(0xC8)
|
||||
// See page 40.
|
||||
columnAddr := byte(0xA1)
|
||||
if opts.Rotated {
|
||||
// Change order both horizontally and vertically.
|
||||
comScan = 0xC0
|
||||
columnAddr = byte(0xA0)
|
||||
}
|
||||
if opts.MirrorVertical {
|
||||
comScan = byte(0xC0)
|
||||
}
|
||||
if opts.MirrorHorizontal {
|
||||
columnAddr = byte(0xA0)
|
||||
}
|
||||
// See page 40.
|
||||
hwLayout := byte(0x02)
|
||||
if !opts.Sequential {
|
||||
hwLayout |= 0x10
|
||||
}
|
||||
if opts.SwapTopBottom {
|
||||
hwLayout |= 0x20
|
||||
}
|
||||
// Set the max frequency. The problem with I²C is that it creates visible
|
||||
// tear down. On SPI at high speed this is not visible. Page 23 pictures how
|
||||
// to avoid tear down. For now default to max frequency.
|
||||
freq := byte(0xF0)
|
||||
|
||||
// Initialize the device by fully resetting all values.
|
||||
// Page 64 has the full recommended flow.
|
||||
// Page 28 lists all the commands.
|
||||
return []byte{
|
||||
0xAE, // Display off
|
||||
0xD3, 0x00, // Set display offset; 0
|
||||
0x40, // Start display start line; 0
|
||||
columnAddr, // Set segment remap; RESET is column 127.
|
||||
comScan, //
|
||||
0xDA, hwLayout, // Set COM pins hardware configuration; see page 40
|
||||
0x81, 0xFF, // Set max contrast
|
||||
0xA4, // Set display to use GDDRAM content
|
||||
0xA6, // Set normal display (0xA7 for inverted 0=lit, 1=dark)
|
||||
0xD5, freq, // Set osc frequency and divide ratio; power on reset value is 0x80.
|
||||
0x8D, 0x14, // Enable charge pump regulator; page 62
|
||||
0xD9, 0xF1, // Set pre-charge period; from adafruit driver
|
||||
0xDB, 0x40, // Set Vcomh deselect level; page 32
|
||||
0x2E, // Deactivate scroll
|
||||
0xA8, byte(opts.H - 1), // Set multiplex ratio (number of lines to display)
|
||||
0x20, 0x00, // Set memory addressing mode to horizontal
|
||||
0x21, 0, uint8(opts.W - 1), // Set column address (Width)
|
||||
0x22, 0, uint8(opts.H/8 - 1), // Set page address (Pages)
|
||||
0xAF, // Display on
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dev) calculateSubset(next []byte) (int, int, int, int, bool) {
|
||||
w := d.rect.Dx()
|
||||
h := d.rect.Dy()
|
||||
startPage := 0
|
||||
endPage := h / 8
|
||||
startCol := 0
|
||||
endCol := w
|
||||
if d.scrolled {
|
||||
// Painting disable scrolling but if scrolling was enabled, this requires a
|
||||
// full screen redraw.
|
||||
d.scrolled = false
|
||||
} else {
|
||||
// Calculate the smallest square that need to be sent.
|
||||
pageSize := w
|
||||
|
||||
// Top.
|
||||
for ; startPage < endPage; startPage++ {
|
||||
x := pageSize * startPage
|
||||
y := pageSize * (startPage + 1)
|
||||
if !bytes.Equal(d.buffer[x:y], next[x:y]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Bottom.
|
||||
for ; endPage > startPage; endPage-- {
|
||||
x := pageSize * (endPage - 1)
|
||||
y := pageSize * endPage
|
||||
if !bytes.Equal(d.buffer[x:y], next[x:y]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if startPage == endPage {
|
||||
// Early exit, the image is exactly the same.
|
||||
return 0, 0, 0, 0, true
|
||||
}
|
||||
|
||||
// Left.
|
||||
for ; startCol < endCol; startCol++ {
|
||||
for i := startPage; i < endPage; i++ {
|
||||
x := i*pageSize + startCol
|
||||
if d.buffer[x] != next[x] {
|
||||
goto breakLeft
|
||||
}
|
||||
}
|
||||
}
|
||||
breakLeft:
|
||||
|
||||
// Right.
|
||||
for ; endCol > startCol; endCol-- {
|
||||
for i := startPage; i < endPage; i++ {
|
||||
x := i*pageSize + endCol - 1
|
||||
if d.buffer[x] != next[x] {
|
||||
goto breakRight
|
||||
}
|
||||
}
|
||||
}
|
||||
breakRight:
|
||||
}
|
||||
return startPage, endPage, startCol, endCol, false
|
||||
}
|
||||
|
||||
// drawInternal sends image data to the controller.
|
||||
func (d *Dev) drawInternal(next []byte) error {
|
||||
startPage, endPage, startCol, endCol, skip := d.calculateSubset(next)
|
||||
if skip {
|
||||
return nil
|
||||
}
|
||||
copy(d.buffer, next)
|
||||
|
||||
if d.startPage != startPage || d.endPage != endPage || d.startCol != startCol || d.endCol != endCol {
|
||||
d.startPage = startPage
|
||||
d.endPage = endPage
|
||||
d.startCol = startCol
|
||||
d.endCol = endCol
|
||||
}
|
||||
|
||||
pageSize := d.rect.Dx()
|
||||
for page := d.startPage; page < d.endPage; page++ {
|
||||
err := d.sendCommand([]byte{
|
||||
_PAGESTARTADDRESS | byte(page),
|
||||
_SETLOWCOLUMN | (byte(d.startCol) & 0x0F),
|
||||
_SETHIGHCOLUMN | (byte(d.startCol) >> 4),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pageStart := page * pageSize
|
||||
err = d.sendData(d.buffer[pageStart+d.startCol : pageStart+d.endCol])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dev) sendData(c []byte) error {
|
||||
if d.halted {
|
||||
// Transparently enable the display.
|
||||
if err := d.sendCommand(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if d.spi {
|
||||
// 4-wire SPI.
|
||||
if err := d.dc.Out(gpio.High); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.c.Tx(c, nil)
|
||||
}
|
||||
return d.c.Tx(append([]byte{i2cData}, c...), nil)
|
||||
}
|
||||
|
||||
func (d *Dev) sendCommand(c []byte) error {
|
||||
if d.halted {
|
||||
// Transparently enable the display.
|
||||
c = append([]byte{0xAF}, c...)
|
||||
d.halted = false
|
||||
}
|
||||
if d.spi {
|
||||
if d.dc == nil {
|
||||
// 3-wire SPI.
|
||||
return errors.New("ssd1306: 3-wire SPI mode is not yet implemented")
|
||||
}
|
||||
// 4-wire SPI.
|
||||
if err := d.dc.Out(gpio.Low); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.c.Tx(c, nil)
|
||||
}
|
||||
return d.c.Tx(append([]byte{i2cCmd}, c...), nil)
|
||||
}
|
||||
|
||||
func (d *Dev) At(x, y int) color.Color {
|
||||
if d.next == nil {
|
||||
return pixel.Off
|
||||
}
|
||||
return d.next.At(x, y)
|
||||
}
|
||||
|
||||
func (d *Dev) Set(x, y int, c color.Color) {
|
||||
if d.next == nil {
|
||||
d.next = image1bit.NewVerticalLSB(d.rect)
|
||||
}
|
||||
d.next.Set(x, y, c)
|
||||
}
|
||||
|
||||
func (d *Dev) Refresh() error {
|
||||
if d.next == nil {
|
||||
return nil
|
||||
}
|
||||
return d.drawInternal(d.next.Pix)
|
||||
}
|
||||
|
||||
func (d *Dev) Size() image.Point {
|
||||
return d.rect.Max
|
||||
}
|
||||
|
||||
const (
|
||||
i2cCmd = 0x00 // I²C transaction has stream of command bytes
|
||||
i2cData = 0x40 // I²C transaction has stream of data bytes
|
||||
)
|
||||
@@ -0,0 +1,227 @@
|
||||
// Package ssd1326 provides a driver for the SSD1326 OLED controller.
|
||||
package ssd1326
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/conn/v3"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/i2c"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/display/ssd1xxx"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("ssd1326", New)
|
||||
}
|
||||
|
||||
var defaultInfo = display.MonochromeDisplayInfo{
|
||||
ResetPulseWidth: 100 * time.Millisecond,
|
||||
ResetWait: 100 * time.Millisecond,
|
||||
PreChipEnableWait: 15 * time.Nanosecond,
|
||||
PostChipEnableWait: 20 * time.Nanosecond,
|
||||
DataSetupTime: 40 * time.Nanosecond,
|
||||
WritePulseWidth: 60 * time.Nanosecond,
|
||||
Width: 256,
|
||||
Height: 32,
|
||||
}
|
||||
|
||||
const (
|
||||
spiMode spi.Mode = spi.Mode0
|
||||
spiSpeed physic.Frequency = 4 * 1000 * 1000
|
||||
maxPixels = 256 * 32
|
||||
)
|
||||
|
||||
var emptyBuf [maxPixels >> 3]byte
|
||||
|
||||
type Device struct {
|
||||
name string
|
||||
hal display.MonochromeDisplay
|
||||
buf pixel.Image[pixel.Monochrome]
|
||||
info display.MonochromeDisplayInfo
|
||||
config *config.Display
|
||||
}
|
||||
|
||||
func New(config *config.Display) (display.Display, error) {
|
||||
log := logrus.WithFields(logrus.Fields{
|
||||
"type": "ssd1306",
|
||||
"name": config.Name,
|
||||
})
|
||||
|
||||
bus, err := ssd1xxx.NewBus(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.WithField("connection", conn.String()).Debug("opening display connection")
|
||||
return newDevice(config, conn, log)
|
||||
}
|
||||
|
||||
func newDevice(config *config.Display, conn conn.Conn, log *logrus.Entry) (d *Device, err error) {
|
||||
var info = new(display.MonochromeDisplayInfo)
|
||||
*info = defaultInfo
|
||||
|
||||
d = &Device{
|
||||
hal: display.NewSSD13xxDisplay(conn, *info),
|
||||
info: *info,
|
||||
config: config,
|
||||
}
|
||||
|
||||
switch conn := conn.(type) {
|
||||
case i2c.Bus:
|
||||
d.name = "SSD1306 I²C@" + conn.String()
|
||||
case i2c.BusCloser:
|
||||
d.name = "SSD1306 I²C@" + conn.String()
|
||||
case spi.Conn:
|
||||
d.name = "SSD1306 SPI@" + conn.String()
|
||||
default:
|
||||
d.name = "SSD1306"
|
||||
}
|
||||
|
||||
log.Trace("configuring display")
|
||||
if err := d.configure(); err != nil {
|
||||
return nil, fmt.Errorf("ssd1306: initial configuration failed: %w", err)
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func NewI2C(bus i2c.Bus, addr uint16) (*Device, error) {
|
||||
if addr == 0 {
|
||||
addr = 0x3c
|
||||
}
|
||||
|
||||
c := &i2c.Dev{Bus: bus, Addr: addr}
|
||||
d := &Device{
|
||||
hal: display.NewSSD13xxDisplay(c, defaultInfo),
|
||||
buf: pixel.NewImage[pixel.Monochrome](int(defaultInfo.Width), int(defaultInfo.Height)),
|
||||
}
|
||||
if err := d.configure(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func NewSPI(port spi.Port, reset gpio.PinOut) (*Device, error) {
|
||||
var info = new(display.MonochromeDisplayInfo)
|
||||
*info = defaultInfo
|
||||
info.Reset = reset
|
||||
|
||||
c, err := port.Connect(spiSpeed, spiMode, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := &Device{
|
||||
hal: display.NewSSD13xxDisplay(c, *info),
|
||||
}
|
||||
if err := d.configure(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *Device) configure() (err error) {
|
||||
if err = d.hal.Init(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = d.hal.StartTransfer(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
0xa0 command: 0x0a0 ***abcde
|
||||
a: 1: mono mode
|
||||
b: 0: horizontal (1: vertical) address increment
|
||||
c: 1: enable bit remap
|
||||
d: 1: COM remap
|
||||
e: 1: Column remap
|
||||
*/
|
||||
|
||||
if err = d.hal.SendCommand([]byte{
|
||||
0xfd, 0x12, // Unlock OLED driver IC MCU interface from entering command. i.e: Accept commands
|
||||
0xae, // Set display off
|
||||
0xa8, 0x1f, // Set multiplex ratio(1 to 64)
|
||||
0xa1, 0x00, // Set display start line
|
||||
0xa2, 0x00, // Set display offset, shift mapping RAM counter
|
||||
0xad, 0x02, // Set master configuration: disable embedded DC-DC, enable internal VCOMH
|
||||
0xa0, 0x06, // Set remap and data format
|
||||
0x86, 0x00, // Set current range
|
||||
0xb7, // Set default gray scale table
|
||||
0x81, 0x27, // Contrast, brightness 0..128
|
||||
0xb1, 0x71, // Phase length
|
||||
0xb3, 0xf0, // Set display clock divide ratio/oscillator frequency (set clock as 135 frames/sec)
|
||||
0xbb, 0x35, 0xff, // Set pre-charge
|
||||
0xbc, 0x1f, // Pre-charge voltage level
|
||||
0xbe, 0x0f, // VCOMH voltage
|
||||
0xbf, 0x02 | 0x0d, // VSL voltage level
|
||||
0xa4, // Normal display mode
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return d.hal.EndTransfer()
|
||||
}
|
||||
|
||||
func (d *Device) String() string {
|
||||
return d.name
|
||||
}
|
||||
|
||||
func (d *Device) Halt() error {
|
||||
return d.hal.Halt()
|
||||
}
|
||||
|
||||
func (d *Device) Clear() error {
|
||||
d.buf.FillSolidColor(pixel.Off)
|
||||
//copy(d.buf.Pix[:], emptyBuf[:])
|
||||
return d.Refresh()
|
||||
}
|
||||
|
||||
func (d *Device) Refresh() (err error) {
|
||||
_ = d.hal.SendCommand([]byte{0x15, 0, byte(defaultInfo.Width) - 1}) // Set column address
|
||||
_ = d.hal.SendCommand([]byte{0x75, 0, byte(defaultInfo.Height) - 1}) // Set row address
|
||||
buf := d.buf.RawBuffer()
|
||||
for i := 0; i < len(buf); i += 16 {
|
||||
if err = d.hal.SendData(buf[i : i+16]); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (d *Device) Size() image.Point {
|
||||
return d.buf.Bounds().Size()
|
||||
}
|
||||
|
||||
func (d *Device) Bounds() image.Rectangle {
|
||||
return d.buf.Bounds()
|
||||
}
|
||||
|
||||
func (Device) ColorModel() color.Model {
|
||||
return pixel.MonochromeModel
|
||||
}
|
||||
|
||||
func (d *Device) At(x, y int) color.Color {
|
||||
return d.buf.At(x, y)
|
||||
}
|
||||
|
||||
func (d *Device) Set(x, y int, c color.Color) {
|
||||
d.buf.Set(x, y, c)
|
||||
}
|
||||
|
||||
// Interface check
|
||||
var (
|
||||
// _ display.Display = &Device{}
|
||||
// _ display.Image = &Device{}
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
package st7789
|
||||
|
||||
import (
|
||||
"git.maze.io/go/harmon/display"
|
||||
)
|
||||
|
||||
// Registers
|
||||
const (
|
||||
NOP = 0x00
|
||||
SWRESET = 0x01
|
||||
RDDID = 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
|
||||
RAMRD = 0x2E
|
||||
PTLAR = 0x30
|
||||
COLMOD = 0x3A
|
||||
MADCTL = 0x36
|
||||
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
|
||||
RDID4 = 0xDD
|
||||
FRMCTR1 = 0xB1
|
||||
RGBCTRL = 0xB1
|
||||
FRMCTR2 = 0xB2
|
||||
PORCTRL = 0xB2
|
||||
FRMCTR3 = 0xB3
|
||||
INVCTR = 0xB4
|
||||
DISSET5 = 0xB6
|
||||
PWCTR1 = 0xC0
|
||||
PWCTR2 = 0xC1
|
||||
PWCTR3 = 0xC2
|
||||
PWCTR4 = 0xC3
|
||||
PWCTR5 = 0xC4
|
||||
VMCTR1 = 0xC5
|
||||
FRCTRL2 = 0xC6
|
||||
PWCTR6 = 0xFC
|
||||
GMCTRP1 = 0xE0
|
||||
GMCTRN1 = 0xE1
|
||||
GSCAN = 0x45
|
||||
VSCRDEF = 0x33
|
||||
VSCRSADD = 0x37
|
||||
|
||||
ColorRGB444 ColorFormat = 0b011
|
||||
ColorRGB565 ColorFormat = 0b101
|
||||
ColorRGB666 ColorFormat = 0b111
|
||||
|
||||
NO_ROTATION = display.NoRotation
|
||||
ROTATION_90 = display.Rotate90 // 90 degrees clock-wise rotation
|
||||
ROTATION_180 = display.Rotate180
|
||||
ROTATION_270 = display.Rotate270
|
||||
|
||||
// Allowable frame rate codes for FRCTRL2 (Identifier is in Hz)
|
||||
FRAMERATE_111 FrameRate = 0x01
|
||||
FRAMERATE_105 FrameRate = 0x02
|
||||
FRAMERATE_99 FrameRate = 0x03
|
||||
FRAMERATE_94 FrameRate = 0x04
|
||||
FRAMERATE_90 FrameRate = 0x05
|
||||
FRAMERATE_86 FrameRate = 0x06
|
||||
FRAMERATE_82 FrameRate = 0x07
|
||||
FRAMERATE_78 FrameRate = 0x08
|
||||
FRAMERATE_75 FrameRate = 0x09
|
||||
FRAMERATE_72 FrameRate = 0x0A
|
||||
FRAMERATE_69 FrameRate = 0x0B
|
||||
FRAMERATE_67 FrameRate = 0x0C
|
||||
FRAMERATE_64 FrameRate = 0x0D
|
||||
FRAMERATE_62 FrameRate = 0x0E
|
||||
FRAMERATE_60 FrameRate = 0x0F // 60 is default
|
||||
FRAMERATE_58 FrameRate = 0x10
|
||||
FRAMERATE_57 FrameRate = 0x11
|
||||
FRAMERATE_55 FrameRate = 0x12
|
||||
FRAMERATE_53 FrameRate = 0x13
|
||||
FRAMERATE_52 FrameRate = 0x14
|
||||
FRAMERATE_50 FrameRate = 0x15
|
||||
FRAMERATE_49 FrameRate = 0x16
|
||||
FRAMERATE_48 FrameRate = 0x17
|
||||
FRAMERATE_46 FrameRate = 0x18
|
||||
FRAMERATE_45 FrameRate = 0x19
|
||||
FRAMERATE_44 FrameRate = 0x1A
|
||||
FRAMERATE_43 FrameRate = 0x1B
|
||||
FRAMERATE_42 FrameRate = 0x1C
|
||||
FRAMERATE_41 FrameRate = 0x1D
|
||||
FRAMERATE_40 FrameRate = 0x1E
|
||||
FRAMERATE_39 FrameRate = 0x1F
|
||||
|
||||
MAX_VSYNC_SCANLINES = 254
|
||||
)
|
||||
@@ -0,0 +1,888 @@
|
||||
// Package st7789 implements a driver for the ST7789 TFT displays, it comes in various screen sizes.
|
||||
//
|
||||
// Datasheets: https://cdn-shop.adafruit.com/product-files/3787/3787_tft_QT154H2201__________20190228182902.pdf
|
||||
//
|
||||
// http://www.newhavendisplay.com/appnotes/datasheets/LCDs/ST7789V.pdf
|
||||
package st7789
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
"periph.io/x/conn/v3/spi"
|
||||
"periph.io/x/conn/v3/spi/spireg"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/hardware"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
// Rotation controls the rotation used by the display.
|
||||
//
|
||||
// Deprecated: use drivers.Rotation instead.
|
||||
type Rotation = display.Rotation
|
||||
|
||||
// The color format used on the display, like RGB565, RGB666, and RGB444.
|
||||
type ColorFormat uint8
|
||||
|
||||
// Pixel formats supported by the st7789 driver.
|
||||
type Color interface {
|
||||
pixel.RGB444BE | pixel.RGB565BE
|
||||
|
||||
pixel.BaseColor
|
||||
}
|
||||
|
||||
// FrameRate controls the frame rate used by the display.
|
||||
type FrameRate uint8
|
||||
|
||||
var (
|
||||
errOutOfBounds = errors.New("rectangle coordinates outside display area")
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("st7789", func(config *config.Display) (display.Display, error) {
|
||||
log := logrus.WithFields(logrus.Fields{
|
||||
"type": "st7789",
|
||||
"name": config.Name,
|
||||
})
|
||||
|
||||
width, height, err := display.ParseSize(config.Size, 240, 320)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rotation, err := display.ParseRotation(config.Rotate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.WithField("port", config.Port).Trace("opening SPI port")
|
||||
port, err := spireg.Open(config.Port)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
bits = 8
|
||||
reset gpio.PinOut
|
||||
dc gpio.PinOut
|
||||
cs gpio.PinOut
|
||||
bl gpio.PinOut
|
||||
)
|
||||
if dc, err = hardware.LookupPinOut(config.DC); err != nil {
|
||||
if !hardware.IsNotFound(err) {
|
||||
return nil, fmt.Errorf("invalid dc pin: %w", err)
|
||||
}
|
||||
bits = 9 // no DC pin
|
||||
}
|
||||
if reset, err = hardware.LookupPinOut(config.Reset); err != nil {
|
||||
return nil, fmt.Errorf("invalid reset pin: %w", err)
|
||||
}
|
||||
if cs, err = hardware.LookupPinOut(config.CS); err != nil && !hardware.IsNotFound(err) {
|
||||
return nil, fmt.Errorf("invalid cs pin: %w", err)
|
||||
} else {
|
||||
cs = gpio.INVALID
|
||||
}
|
||||
if bl, err = hardware.LookupPinOut(config.BL); err != nil {
|
||||
return nil, fmt.Errorf("invalid bl pin: %w", err)
|
||||
}
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"mode": spi.Mode0,
|
||||
"bits": bits,
|
||||
"pin_reset": reset,
|
||||
"pin_dc": dc,
|
||||
"pin_cs": cs,
|
||||
"pin_bl": bl,
|
||||
}).Debug("connecting on SPI port")
|
||||
conn, err := port.Connect(75*physic.MegaHertz, spi.Mode0, bits)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := New[pixel.RGB565BE](conn, reset, dc, cs, bl)
|
||||
d.log = log
|
||||
|
||||
if err = d.Configure(Config{
|
||||
Width: int16(width),
|
||||
Height: int16(height),
|
||||
Rotation: rotation,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d, nil
|
||||
})
|
||||
}
|
||||
|
||||
// Device wraps an SPI connection.
|
||||
type Device = DeviceOf[pixel.RGB565BE]
|
||||
|
||||
// DeviceOf is a generic version of Device. It supports multiple different pixel
|
||||
// formats.
|
||||
type DeviceOf[T Color] struct {
|
||||
log *logrus.Entry
|
||||
bus spi.Conn
|
||||
dcPin gpio.PinOut
|
||||
resetPin gpio.PinOut
|
||||
csPin gpio.PinOut
|
||||
blPin gpio.PinOut
|
||||
width int16
|
||||
height int16
|
||||
columnOffsetCfg int16
|
||||
rowOffsetCfg int16
|
||||
columnOffset int16
|
||||
rowOffset int16
|
||||
rotation display.Rotation
|
||||
frameRate FrameRate
|
||||
batchLength int32
|
||||
batchData pixel.Image[T] // "image" with (width, height) of (batchLength, 1)
|
||||
isBGR bool
|
||||
vSyncLines int16
|
||||
cmdBuf [1]byte
|
||||
buf [6]byte
|
||||
}
|
||||
|
||||
// Config is the configuration for the display
|
||||
type Config struct {
|
||||
Width int16
|
||||
Height int16
|
||||
Rotation display.Rotation
|
||||
RowOffset int16
|
||||
ColumnOffset int16
|
||||
FrameRate FrameRate
|
||||
VSyncLines int16
|
||||
|
||||
// Gamma control. Look in the LCD panel datasheet or provided example code
|
||||
// to find these values. If not set, the defaults will be used.
|
||||
PVGAMCTRL []uint8 // Positive voltage gamma control (14 bytes)
|
||||
NVGAMCTRL []uint8 // Negative voltage gamma control (14 bytes)
|
||||
}
|
||||
|
||||
// New creates a new ST7789 connection. The SPI wire must already be configured.
|
||||
//func New(bus spi.Conn, resetPin, dcPin, csPin, blPin gpio.PinOut) *Device {
|
||||
// return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin)
|
||||
//}
|
||||
|
||||
// NewOf creates a new ST7789 connection with a particular pixel format. The SPI
|
||||
// wire must already be configured.
|
||||
func New[T Color](bus spi.Conn, reset, dc, cs, bl gpio.PinOut) *DeviceOf[T] {
|
||||
return &DeviceOf[T]{
|
||||
log: logrus.WithFields(logrus.Fields{
|
||||
"display": "st7789",
|
||||
"pin_reset": reset,
|
||||
"pin_dc": dc,
|
||||
"pin_cs": cs,
|
||||
"pin_bl": bl,
|
||||
}),
|
||||
bus: bus,
|
||||
dcPin: dc,
|
||||
resetPin: reset,
|
||||
csPin: cs,
|
||||
blPin: bl,
|
||||
}
|
||||
}
|
||||
|
||||
// Configure initializes the display with default configuration
|
||||
func (d *DeviceOf[T]) Configure(cfg Config) (err error) {
|
||||
start := time.Now()
|
||||
d.log.Trace("start display configuration")
|
||||
defer func() {
|
||||
ago := time.Since(start)
|
||||
d.log.WithField("duration", ago).Trace("ended display configuration")
|
||||
}()
|
||||
|
||||
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.rotation = cfg.Rotation
|
||||
d.rowOffsetCfg = cfg.RowOffset
|
||||
d.columnOffsetCfg = cfg.ColumnOffset
|
||||
|
||||
if cfg.FrameRate != 0 {
|
||||
d.frameRate = cfg.FrameRate
|
||||
} else {
|
||||
d.frameRate = FRAMERATE_60
|
||||
}
|
||||
d.log.Tracef("%d frame rate", d.frameRate)
|
||||
|
||||
if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 {
|
||||
d.vSyncLines = cfg.VSyncLines
|
||||
} else {
|
||||
d.vSyncLines = 16
|
||||
}
|
||||
d.log.Tracef("%d vsync lines", d.vSyncLines)
|
||||
|
||||
d.batchLength = int32(d.width)
|
||||
if d.height > d.width {
|
||||
d.batchLength = int32(d.height)
|
||||
}
|
||||
d.batchLength += d.batchLength & 1
|
||||
d.log.Tracef("%d batch length", d.batchLength)
|
||||
|
||||
// Reset the device
|
||||
d.log.Debug("reset device")
|
||||
if err = d.resetPin.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if err = d.resetPin.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if err = d.resetPin.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Common initialization
|
||||
d.startWrite()
|
||||
d.sendCommand(SWRESET, nil) // Soft reset
|
||||
d.endWrite()
|
||||
time.Sleep(150 * time.Millisecond) //
|
||||
d.startWrite()
|
||||
|
||||
d.sendCommand(SLPOUT, nil) // Exit sleep mode
|
||||
|
||||
// Memory initialization
|
||||
var zeroColor T
|
||||
switch any(zeroColor).(type) {
|
||||
case pixel.RGB444BE:
|
||||
d.setColorFormat(ColorRGB444) // 12 bits per pixel
|
||||
default:
|
||||
// Use default RGB565 color format.
|
||||
d.setColorFormat(ColorRGB565) // 16 bits per pixel
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
d.setRotation(d.rotation) // Memory orientation
|
||||
|
||||
d.setWindow(0, 0, d.width, d.height) // Full draw window
|
||||
var black T
|
||||
d.fillScreen(black) // Clear screen
|
||||
|
||||
// Framerate
|
||||
d.sendCommand(FRCTRL2, []byte{byte(d.frameRate)}) // Frame rate for normal mode (default 60Hz)
|
||||
|
||||
// Frame vertical sync and "porch"
|
||||
//
|
||||
// Front and back porch controls vertical scanline sync time before and after
|
||||
// a frame, where memory can be safely written without tearing.
|
||||
//
|
||||
fp := uint8(d.vSyncLines / 2) // Split the desired pause half and half
|
||||
bp := uint8(d.vSyncLines - int16(fp)) // between front and back porch.
|
||||
|
||||
d.sendCommand(PORCTRL, []byte{
|
||||
bp, // Back porch 5bit (0x7F max 0x08 default)
|
||||
fp, // Front porch 5bit (0x7F max 0x08 default)
|
||||
0x00, // Seprarate porch (TODO: what is this?)
|
||||
0x22, // Idle mode porch (4bit-back 4bit-front 0x22 default)
|
||||
0x22, // Partial mode porch (4bit-back 4bit-front 0x22 default)
|
||||
})
|
||||
|
||||
// Ready to display
|
||||
d.sendCommand(INVON, nil) // Inversion ON
|
||||
time.Sleep(10 * time.Millisecond) //
|
||||
|
||||
// Set gamma tables, if configured.
|
||||
if len(cfg.PVGAMCTRL) == 14 {
|
||||
d.sendCommand(GMCTRP1, cfg.PVGAMCTRL) // PVGAMCTRL: Positive Voltage Gamma Control
|
||||
}
|
||||
if len(cfg.NVGAMCTRL) == 14 {
|
||||
d.sendCommand(GMCTRN1, cfg.NVGAMCTRL) // NVGAMCTRL: Negative Voltage Gamma Control
|
||||
}
|
||||
|
||||
// Normal mode ON
|
||||
if err = d.sendCommand(NORON, nil); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Screen ON
|
||||
if err = d.sendCommand(DISPON, nil); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
if err = d.endWrite(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Backlight ON
|
||||
if err = d.blPin.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Send a command with data to the display. It does not change the chip select
|
||||
// pin (it must be low when calling). The DC pin is left high after return,
|
||||
// meaning that data can be sent right away.
|
||||
func (d *DeviceOf[T]) sendCommand(command uint8, data []byte) (err error) {
|
||||
//d.log.WithFields(logrus.Fields{"command": command, "data": data}).Trace("send command")
|
||||
d.cmdBuf[0] = command
|
||||
if hardware.IsValidPinOut(d.dcPin) {
|
||||
if err = d.dcPin.Out(gpio.Low); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = d.bus.Tx(d.cmdBuf[:1], nil); err != nil {
|
||||
return
|
||||
}
|
||||
if hardware.IsValidPinOut(d.dcPin) {
|
||||
if err = d.dcPin.Out(gpio.High); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(data) != 0 {
|
||||
err = d.bus.Tx(data, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// startWrite must be called at the beginning of all exported methods to set the
|
||||
// chip select pin low.
|
||||
func (d *DeviceOf[T]) startWrite() error {
|
||||
if hardware.IsValidPinOut(d.csPin) {
|
||||
return d.csPin.Out(gpio.Low)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// endWrite must be called at the end of all exported methods to set the chip
|
||||
// select pin high.
|
||||
func (d *DeviceOf[T]) endWrite() error {
|
||||
if hardware.IsValidPinOut(d.csPin) {
|
||||
return d.csPin.Out(gpio.High)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getBuffer returns the image buffer, that's always d.batchLength wide and 1
|
||||
// pixel high. It can be used as a temporary buffer to transmit image data.
|
||||
func (d *DeviceOf[T]) getBuffer() pixel.Image[T] {
|
||||
if d.batchData.Len() == 0 {
|
||||
d.batchData = pixel.NewImage[T](int(d.batchLength), 1)
|
||||
}
|
||||
return d.batchData
|
||||
}
|
||||
|
||||
// Sync waits for the display to hit the next VSYNC pause
|
||||
func (d *DeviceOf[T]) Sync() {
|
||||
d.SyncToScanLine(0)
|
||||
}
|
||||
|
||||
// SyncToScanLine waits for the display to hit a specific scanline
|
||||
//
|
||||
// A scanline value of 0 will forward to the beginning of the next VSYNC,
|
||||
// even if the display is currently in a VSYNC pause.
|
||||
//
|
||||
// Syncline values appear to increment once for every two vertical
|
||||
// lines on the display.
|
||||
//
|
||||
// NOTE: Use GetHighestScanLine and GetLowestScanLine to obtain the highest
|
||||
// and lowest useful values. Values are affected by front and back porch
|
||||
// vsync settings (derived from VSyncLines configuration option).
|
||||
func (d *DeviceOf[T]) SyncToScanLine(scanline uint16) {
|
||||
scan := d.GetScanLine()
|
||||
|
||||
// Sometimes GetScanLine returns erroneous 0 on first call after draw, so double check
|
||||
if scan == 0 {
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
|
||||
if scanline == 0 {
|
||||
// we dont know where we are in an ongoing vsync so go around
|
||||
for scan < 1 {
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
for scan > 0 {
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
} else {
|
||||
// go around unless we're very close to the target
|
||||
for scan > scanline+4 {
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
for scan < scanline {
|
||||
scan = d.GetScanLine()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetScanLine reads the current scanline value from the display
|
||||
func (d *DeviceOf[T]) GetScanLine() uint16 {
|
||||
d.startWrite()
|
||||
data := []uint8{0x00, 0x00}
|
||||
if hardware.IsValidPinOut(d.dcPin) {
|
||||
d.dcPin.Out(gpio.Low)
|
||||
}
|
||||
//d.bus.Transfer(GSCAN)
|
||||
d.bus.Tx([]byte{GSCAN}, nil)
|
||||
if hardware.IsValidPinOut(d.dcPin) {
|
||||
d.dcPin.Out(gpio.High)
|
||||
}
|
||||
/*
|
||||
for i := range data {
|
||||
data[i], _ = d.bus.Transfer(0xFF)
|
||||
}
|
||||
*/
|
||||
d.bus.Tx(data, data)
|
||||
scanline := uint16(data[0])<<8 + uint16(data[1])
|
||||
d.endWrite()
|
||||
return scanline
|
||||
}
|
||||
|
||||
// GetHighestScanLine calculates the last scanline id in the frame before VSYNC pause
|
||||
func (d *DeviceOf[T]) GetHighestScanLine() uint16 {
|
||||
// Last scanline id appears to be backporch/2 + 320/2
|
||||
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 160
|
||||
}
|
||||
|
||||
// GetLowestScanLine calculate the first scanline id to appear after VSYNC pause
|
||||
func (d *DeviceOf[T]) GetLowestScanLine() uint16 {
|
||||
// First scanline id appears to be backporch/2 + 1
|
||||
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 1
|
||||
}
|
||||
|
||||
// Display does nothing, there's no buffer as it might be too big for some boards
|
||||
func (d *DeviceOf[T]) Display() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetPixel sets a pixel in the screen
|
||||
// func (d *DeviceOf[T]) SetPixel(x int16, y int16, c color.RGBA) {
|
||||
func (d *DeviceOf[T]) SetPixel(x int16, y int16, c T) {
|
||||
if x < 0 || y < 0 ||
|
||||
(((d.rotation == display.NoRotation || d.rotation == display.Rotate180) && (x >= d.width || y >= d.height)) ||
|
||||
((d.rotation == display.Rotate90 || d.rotation == display.Rotate270) && (x >= d.height || y >= d.width))) {
|
||||
return
|
||||
}
|
||||
d.FillRectangle(x, y, 1, 1, c)
|
||||
}
|
||||
|
||||
// setWindow prepares the screen to be modified at a given rectangle
|
||||
func (d *DeviceOf[T]) setWindow(x, y, w, h int16) {
|
||||
//d.log.WithFields(logrus.Fields{"x": x, "y": y, "w": w, "h": h}).Debug("updating drawing window")
|
||||
x += d.columnOffset
|
||||
y += d.rowOffset
|
||||
copy(d.buf[:4], []uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)})
|
||||
d.sendCommand(CASET, d.buf[:4])
|
||||
copy(d.buf[:4], []uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)})
|
||||
d.sendCommand(RASET, d.buf[:4])
|
||||
d.sendCommand(RAMWR, nil)
|
||||
}
|
||||
|
||||
// FillRectangle fills a rectangle at a given coordinates with a color
|
||||
// func (d *DeviceOf[T]) FillRectangle(x, y, width, height int16, c color.RGBA) error {
|
||||
func (d *DeviceOf[T]) FillRectangle(x, y, width, height int16, c T) error {
|
||||
d.startWrite()
|
||||
err := d.fillRectangle(x, y, width, height, c)
|
||||
d.endWrite()
|
||||
return err
|
||||
}
|
||||
|
||||
// func (d *DeviceOf[T]) fillRectangle(x, y, width, height int16, c color.RGBA) error {
|
||||
func (d *DeviceOf[T]) fillRectangle(x, y, width, height int16, c T) error {
|
||||
k, i := d.Size16()
|
||||
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||
x >= k || (x+width) > k || y >= i || (y+height) > i {
|
||||
return errors.New("rectangle coordinates outside display area")
|
||||
}
|
||||
d.setWindow(x, y, width, height)
|
||||
|
||||
image := d.getBuffer()
|
||||
image.FillSolidColor(c)
|
||||
//image.FillSolidColor(pixel.NewColor[T](c.R, c.G, c.B))
|
||||
j := int(width) * int(height)
|
||||
for j > 0 {
|
||||
// The DC pin is already set to data in the setWindow call, so we can
|
||||
// just write bytes on the SPI bus.
|
||||
if j >= image.Len() {
|
||||
d.bus.Tx(image.RawBuffer(), nil)
|
||||
} else {
|
||||
d.bus.Tx(image.Rescale(j, 1).RawBuffer(), nil)
|
||||
}
|
||||
j -= image.Len()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DrawRGBBitmap8 copies an RGB bitmap to the internal buffer at given coordinates
|
||||
//
|
||||
// Deprecated: use DrawBitmap instead.
|
||||
func (d *DeviceOf[T]) DrawRGBBitmap8(x, y int16, data []uint8, w, h int16) error {
|
||||
k, i := d.Size16()
|
||||
if x < 0 || y < 0 || w <= 0 || h <= 0 ||
|
||||
x >= k || (x+w) > k || y >= i || (y+h) > i {
|
||||
return errOutOfBounds
|
||||
}
|
||||
d.startWrite()
|
||||
d.setWindow(x, y, w, h)
|
||||
d.bus.Tx(data, nil)
|
||||
d.endWrite()
|
||||
return nil
|
||||
}
|
||||
|
||||
// DrawBitmap copies the bitmap to the internal buffer on the screen at the
|
||||
// given coordinates. It returns once the image data has been sent completely.
|
||||
func (d *DeviceOf[T]) DrawBitmap(x, y int16, bitmap pixel.Image[T]) error {
|
||||
width, height := bitmap.Size()
|
||||
return d.DrawRGBBitmap8(x, y, bitmap.RawBuffer(), int16(width), int16(height))
|
||||
}
|
||||
|
||||
// FillRectangleWithBuffer fills buffer with a rectangle at a given coordinates.
|
||||
func (d *DeviceOf[T]) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {
|
||||
i, j := d.Size16()
|
||||
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||
x >= i || (x+width) > i || y >= j || (y+height) > j {
|
||||
return errors.New("rectangle coordinates outside display area")
|
||||
}
|
||||
if int32(width)*int32(height) != int32(len(buffer)) {
|
||||
return errors.New("buffer length does not match with rectangle size")
|
||||
}
|
||||
d.startWrite()
|
||||
d.setWindow(x, y, width, height)
|
||||
|
||||
k := int(width) * int(height)
|
||||
image := d.getBuffer()
|
||||
offset := 0
|
||||
for k > 0 {
|
||||
for i := 0; i < image.Len(); i++ {
|
||||
if offset+i < len(buffer) {
|
||||
c := buffer[offset+i]
|
||||
image.Set(i, 0, pixel.NewColor[T](c.R, c.G, c.B))
|
||||
}
|
||||
}
|
||||
// The DC pin is already set to data in the setWindow call, so we don't
|
||||
// have to set it here.
|
||||
if k >= image.Len() {
|
||||
d.bus.Tx(image.RawBuffer(), nil)
|
||||
} else {
|
||||
d.bus.Tx(image.Rescale(k, 1).RawBuffer(), nil)
|
||||
}
|
||||
k -= image.Len()
|
||||
offset += image.Len()
|
||||
}
|
||||
d.endWrite()
|
||||
return nil
|
||||
}
|
||||
|
||||
// DrawFastVLine draws a vertical line faster than using SetPixel
|
||||
func (d *DeviceOf[T]) DrawFastVLine(x, y0, y1 int16, c T) {
|
||||
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 *DeviceOf[T]) DrawFastHLine(x0, x1, y int16, c T) {
|
||||
if x0 > x1 {
|
||||
x0, x1 = x1, x0
|
||||
}
|
||||
d.FillRectangle(x0, y, x1-x0+1, 1, c)
|
||||
}
|
||||
|
||||
// FillScreen fills the screen with a given color
|
||||
func (d *DeviceOf[T]) FillScreen(c T) {
|
||||
d.startWrite()
|
||||
d.fillScreen(c)
|
||||
d.endWrite()
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) fillScreen(c T) {
|
||||
if d.rotation == NO_ROTATION || d.rotation == ROTATION_180 {
|
||||
d.fillRectangle(0, 0, d.width, d.height, c)
|
||||
} else {
|
||||
d.fillRectangle(0, 0, d.height, d.width, c)
|
||||
}
|
||||
}
|
||||
|
||||
// Control the color format that is used when writing to the screen.
|
||||
// The default is RGB565, setting it to any other value will break functions
|
||||
// like SetPixel, FillRectangle, etc. Instead, you can write color data in the
|
||||
// specified color format using DrawRGBBitmap8.
|
||||
func (d *DeviceOf[T]) SetColorFormat(format ColorFormat) {
|
||||
d.startWrite()
|
||||
d.setColorFormat(format)
|
||||
d.endWrite()
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) setColorFormat(format ColorFormat) {
|
||||
// Lower 4 bits set the color format used in SPI.
|
||||
// Upper 4 bits set the color format used in the direct RGB interface.
|
||||
// The RGB interface is not currently supported, so it is left at a
|
||||
// reasonable default. Also, the RGB interface doesn't support RGB444.
|
||||
colmod := byte(format) | 0x50
|
||||
d.sendCommand(COLMOD, []byte{colmod})
|
||||
}
|
||||
|
||||
// Rotation returns the current rotation of the device.
|
||||
func (d *DeviceOf[T]) Rotation() display.Rotation {
|
||||
return d.rotation
|
||||
}
|
||||
|
||||
// SetRotation changes the rotation of the device (clock-wise)
|
||||
func (d *DeviceOf[T]) SetRotation(rotation Rotation) error {
|
||||
d.rotation = rotation
|
||||
d.startWrite()
|
||||
err := d.setRotation(rotation)
|
||||
d.endWrite()
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) setRotation(rotation Rotation) error {
|
||||
madctl := uint8(0)
|
||||
switch rotation % 4 {
|
||||
case display.NoRotation:
|
||||
d.rowOffset = 0
|
||||
d.columnOffset = 0
|
||||
case display.Rotate90:
|
||||
madctl = MADCTL_MX | MADCTL_MV
|
||||
d.rowOffset = 0
|
||||
d.columnOffset = 0
|
||||
case display.Rotate180:
|
||||
madctl = MADCTL_MX | MADCTL_MY
|
||||
d.rowOffset = d.rowOffsetCfg
|
||||
d.columnOffset = d.columnOffsetCfg
|
||||
case display.Rotate270:
|
||||
madctl = MADCTL_MY | MADCTL_MV
|
||||
d.rowOffset = d.columnOffsetCfg
|
||||
d.columnOffset = d.rowOffsetCfg
|
||||
}
|
||||
if d.isBGR {
|
||||
madctl |= MADCTL_BGR
|
||||
}
|
||||
return d.sendCommand(MADCTL, []byte{madctl})
|
||||
}
|
||||
|
||||
// Size returns the current size of the display.
|
||||
func (d *DeviceOf[T]) Size() image.Point {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
return image.Pt(int(d.width), int(d.height))
|
||||
}
|
||||
return image.Pt(int(d.height), int(d.width))
|
||||
}
|
||||
|
||||
// Sizes returns the current size of the display.
|
||||
func (d *DeviceOf[T]) Size16() (int16, int16) {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
return d.width, d.height
|
||||
}
|
||||
return d.height, d.width
|
||||
}
|
||||
|
||||
// EnableBacklight enables or disables the backlight
|
||||
func (d *DeviceOf[T]) EnableBacklight(enable bool) {
|
||||
if enable {
|
||||
d.blPin.Out(gpio.High)
|
||||
} else {
|
||||
d.blPin.Out(gpio.Low)
|
||||
}
|
||||
}
|
||||
|
||||
// Set the sleep mode for this LCD panel. When sleeping, the panel uses a lot
|
||||
// less power. The LCD won't display an image anymore, but the memory contents
|
||||
// will be kept.
|
||||
func (d *DeviceOf[T]) Sleep(sleepEnabled bool) error {
|
||||
if sleepEnabled {
|
||||
d.startWrite()
|
||||
d.sendCommand(SLPIN, nil)
|
||||
d.endWrite()
|
||||
time.Sleep(5 * time.Millisecond) // 5ms required by the datasheet
|
||||
} else {
|
||||
// Turn the LCD panel back on.
|
||||
d.startWrite()
|
||||
d.sendCommand(SLPOUT, nil)
|
||||
d.endWrite()
|
||||
// Note: the st7789 documentation says that it is needed to wait at
|
||||
// least 120ms before going to sleep again. Sleeping here would not be
|
||||
// practical (delays turning on the screen too much), so just hope the
|
||||
// screen won't need to sleep again for at least 120ms.
|
||||
// In practice, it's unlikely the user will set the display to sleep
|
||||
// again within 120ms.
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InvertColors inverts the colors of the screen
|
||||
func (d *DeviceOf[T]) InvertColors(invert bool) {
|
||||
d.startWrite()
|
||||
if invert {
|
||||
d.sendCommand(INVON, nil)
|
||||
} else {
|
||||
d.sendCommand(INVOFF, nil)
|
||||
}
|
||||
d.endWrite()
|
||||
}
|
||||
|
||||
// IsBGR changes the color mode (RGB/BGR)
|
||||
func (d *DeviceOf[T]) IsBGR(bgr bool) {
|
||||
d.isBGR = bgr
|
||||
}
|
||||
|
||||
// SetScrollArea sets an area to scroll with fixed top and bottom parts of the display.
|
||||
func (d *DeviceOf[T]) SetScrollArea(topFixedArea, bottomFixedArea int16) {
|
||||
if d.height < 320 {
|
||||
// The screen doesn't use the full 320 pixel height.
|
||||
// Enlarge the bottom fixed area to fill the 320 pixel height, so that
|
||||
// bottomFixedArea starts from the visible bottom of the screen.
|
||||
topFixedArea += d.rowOffset
|
||||
bottomFixedArea += (320 - d.height) - d.rowOffset
|
||||
}
|
||||
if d.rotation == display.Rotate180 {
|
||||
// The screen is rotated by 180°, so we have to switch the top and
|
||||
// bottom fixed area.
|
||||
topFixedArea, bottomFixedArea = bottomFixedArea, topFixedArea
|
||||
}
|
||||
verticalScrollArea := 320 - topFixedArea - bottomFixedArea
|
||||
copy(d.buf[:6], []uint8{
|
||||
uint8(topFixedArea >> 8), uint8(topFixedArea),
|
||||
uint8(verticalScrollArea >> 8), uint8(verticalScrollArea),
|
||||
uint8(bottomFixedArea >> 8), uint8(bottomFixedArea)})
|
||||
d.startWrite()
|
||||
d.sendCommand(VSCRDEF, d.buf[:6])
|
||||
d.endWrite()
|
||||
}
|
||||
|
||||
// SetScroll sets the vertical scroll address of the display.
|
||||
func (d *DeviceOf[T]) SetScroll(line int16) {
|
||||
if d.rotation == display.Rotate180 {
|
||||
// The screen is rotated by 180°, so we have to invert the scroll line
|
||||
// (taking care of the RowOffset).
|
||||
line = (319 - d.rowOffset) - line
|
||||
}
|
||||
d.buf[0] = uint8(line >> 8)
|
||||
d.buf[1] = uint8(line)
|
||||
d.startWrite()
|
||||
d.sendCommand(VSCRSADD, d.buf[:2])
|
||||
d.endWrite()
|
||||
}
|
||||
|
||||
// StopScroll returns the display to its normal state.
|
||||
func (d *DeviceOf[T]) StopScroll() {
|
||||
d.startWrite()
|
||||
d.sendCommand(NORON, nil)
|
||||
d.endWrite()
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) At(x, y int) color.Color {
|
||||
return color.Black
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) Bounds() image.Rectangle {
|
||||
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||
}
|
||||
return image.Rect(0, 0, int(d.height), int(d.width))
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) ColorModel() color.Model {
|
||||
return color.RGBAModel
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) Set(x, y int, c color.Color) {
|
||||
c = pixel.FromColor[T](c)
|
||||
d.FillRectangle(int16(x), int16(y), 1, 1, c.(T))
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) Halt() error {
|
||||
// Backlight off
|
||||
return d.blPin.Out(gpio.Low)
|
||||
}
|
||||
|
||||
func (DeviceOf[T]) Refresh() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (DeviceOf[T]) String() string {
|
||||
return "st7789"
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) DrawImage(img image.Image) error {
|
||||
d.setWindow(0, 0, d.width, d.height)
|
||||
|
||||
var np []uint8
|
||||
for y := 0; y < int(d.height); y++ {
|
||||
for x := 0; x < int(d.width); x++ {
|
||||
r, g, b, _ := img.At(x, y).RGBA()
|
||||
c := uint16((b & 0xF800) + ((g & 0xFC00) >> 5) + ((r & 0xF800) >> 11))
|
||||
np = append(np, uint8(c), uint8(c>>8))
|
||||
}
|
||||
}
|
||||
|
||||
// DC is active from setWindow call
|
||||
stride := int(d.batchLength) << 1
|
||||
for i := 0; i < len(np); i += stride {
|
||||
if err := d.bus.Tx(np[i:i+stride], nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DeviceOf[T]) DrawImageAt(x, y int, img image.Image) error {
|
||||
var (
|
||||
rect = img.Bounds()
|
||||
size = rect.Size()
|
||||
orig = image.Pt(x, y)
|
||||
view = image.Rectangle{
|
||||
Min: orig,
|
||||
Max: orig.Add(size),
|
||||
}
|
||||
)
|
||||
|
||||
//view = view.Intersect()
|
||||
|
||||
if view.Max.X > int(d.width) {
|
||||
view.Max.X = int(d.width)
|
||||
}
|
||||
if view.Max.X <= view.Min.X {
|
||||
return nil // nothing to do here
|
||||
}
|
||||
if view.Max.Y > int(d.height) {
|
||||
view.Max.Y = int(d.height)
|
||||
}
|
||||
|
||||
d.setWindow(int16(x), int16(y), int16(view.Dx()), int16(view.Dy()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// bgr565 converts a color to uint16
|
||||
func bgr565(c color.Color) uint16 {
|
||||
r, g, b, _ := c.RGBA()
|
||||
return uint16((b & 0xF800) +
|
||||
((g & 0xFC00) >> 5) +
|
||||
((r & 0xF800) >> 11))
|
||||
}
|
||||
|
||||
// rgbaTo565 converts a color.RGBA to uint16 used in the display (bits r:5, g:6, b:5)
|
||||
func rgbaTo565(c color.RGBA) uint16 {
|
||||
r, g, b, _ := c.RGBA()
|
||||
return uint16((r & 0xF800) +
|
||||
((g & 0xFC00) >> 5) +
|
||||
((b & 0xF800) >> 11))
|
||||
}
|
||||
|
||||
var _ display.Display = (*Device)(nil)
|
||||
@@ -0,0 +1,147 @@
|
||||
package virtual
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"strings"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
for _, name := range []string{
|
||||
"row",
|
||||
//"append",
|
||||
//"horizontal",
|
||||
"col",
|
||||
"column",
|
||||
//"stack",
|
||||
//"vertical",
|
||||
} {
|
||||
display.Register(name, newRowOrColumn)
|
||||
}
|
||||
}
|
||||
|
||||
func newRowOrColumn(config *config.Display) (display.Display, error) {
|
||||
if config.Address == "" {
|
||||
return nil, fmt.Errorf("virtual display %q missing required addr", config.Name)
|
||||
}
|
||||
|
||||
var (
|
||||
displays []display.Display
|
||||
err error
|
||||
)
|
||||
for i, name := range strings.Split(config.Address, ",") {
|
||||
var d display.Display
|
||||
if d, err = display.Lookup(name); err != nil {
|
||||
return nil, fmt.Errorf("virtual display %q error loading %q: %w", config.Name, name, err)
|
||||
}
|
||||
displays = append(displays, d)
|
||||
|
||||
if i > 1 && !displays[i].Size().Eq(displays[i-1].Size()) {
|
||||
return nil, fmt.Errorf("virtual display %q requires displays with the same dimensions")
|
||||
}
|
||||
}
|
||||
if len(displays) == 1 {
|
||||
return displays[0], nil
|
||||
}
|
||||
|
||||
switch config.Type {
|
||||
case "row", "append", "horizontal":
|
||||
// row of displays
|
||||
return newList(displays, false), nil
|
||||
case "col", "column", "stack", "vertical":
|
||||
// column of displays
|
||||
return newList(displays, true), nil
|
||||
default:
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
// list is a virtual row or column of one or more displays.
|
||||
type list struct {
|
||||
displays []display.Display
|
||||
size image.Point // size of one display
|
||||
rect image.Rectangle // rect is the union of all displays
|
||||
vertical bool
|
||||
}
|
||||
|
||||
func newList(displays []display.Display, vertical bool) display.Display {
|
||||
var (
|
||||
rect image.Rectangle
|
||||
size image.Point
|
||||
)
|
||||
for i, display := range displays {
|
||||
if i == 0 {
|
||||
size = display.Size()
|
||||
rect = image.Rectangle{Max: size}
|
||||
} else if vertical {
|
||||
rect.Max.Y += size.Y
|
||||
} else {
|
||||
rect.Max.X += size.X
|
||||
}
|
||||
}
|
||||
return &list{
|
||||
displays: displays,
|
||||
size: size,
|
||||
rect: rect,
|
||||
vertical: vertical,
|
||||
}
|
||||
}
|
||||
|
||||
func (d *list) String() string {
|
||||
if d.vertical {
|
||||
return "column"
|
||||
}
|
||||
return "row"
|
||||
}
|
||||
|
||||
func (d *list) ColorModel() color.Model { return d.displays[0].ColorModel() }
|
||||
func (d *list) Bounds() image.Rectangle { return d.rect }
|
||||
func (d *list) Halt() error { return nil }
|
||||
|
||||
func (d *list) displayAt(x, y int) (int, int, display.Display) {
|
||||
for _, display := range d.displays {
|
||||
if image.Pt(x, y).In(display.Bounds()) {
|
||||
return x, y, display
|
||||
}
|
||||
if d.vertical {
|
||||
y -= d.size.Y
|
||||
} else {
|
||||
x -= d.size.X
|
||||
}
|
||||
}
|
||||
return -1, -1, nil
|
||||
}
|
||||
|
||||
func (d *list) At(x, y int) color.Color {
|
||||
var display display.Display
|
||||
if x, y, display = d.displayAt(x, y); display != nil {
|
||||
return display.At(x, y)
|
||||
}
|
||||
return pixel.Off
|
||||
}
|
||||
|
||||
func (d *list) Set(x, y int, c color.Color) {
|
||||
var display display.Display
|
||||
if x, y, display = d.displayAt(x, y); display != nil {
|
||||
display.Set(x, y, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (d *list) Refresh() error {
|
||||
for _, display := range d.displays {
|
||||
if err := display.Refresh(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *list) Size() image.Point {
|
||||
return d.rect.Size()
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package virtual
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
"git.maze.io/go/harmon/internal/pixel"
|
||||
)
|
||||
|
||||
func init() {
|
||||
display.Register("split", NewSplit)
|
||||
}
|
||||
|
||||
// Split is a view on another display.
|
||||
type Split struct {
|
||||
display display.Display
|
||||
bbox image.Rectangle // b are the normalized bounds
|
||||
rect image.Rectangle // r are the absolute bounds in d
|
||||
}
|
||||
|
||||
func NewSplit(config *config.Display) (display.Display, error) {
|
||||
if config.Address == "" {
|
||||
return nil, fmt.Errorf("virtual display %q missing required addr", config.Name)
|
||||
}
|
||||
|
||||
r, err := parseRect(config.Port)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("virtual display %q invalid port %q: %w", config.Name, config.Port, err)
|
||||
}
|
||||
|
||||
d, err := display.Lookup(config.Address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("virtual display %q error loading %q: %w", config.Name, config.Address, err)
|
||||
}
|
||||
|
||||
return &Split{
|
||||
display: d,
|
||||
bbox: r.Sub(r.Min),
|
||||
rect: r,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Split) String() string { return "split:" + d.display.String() }
|
||||
|
||||
func (d *Split) At(x, y int) color.Color {
|
||||
p := image.Pt(x, y).Add(d.rect.Min)
|
||||
if !p.In(d.rect) {
|
||||
return pixel.Off
|
||||
}
|
||||
return d.display.At(p.X, p.Y)
|
||||
}
|
||||
|
||||
func (d *Split) Set(x, y int, c color.Color) {
|
||||
p := image.Pt(x, y).Add(d.rect.Min)
|
||||
if !p.In(d.rect) {
|
||||
return
|
||||
}
|
||||
d.display.Set(p.X, p.Y, c)
|
||||
}
|
||||
|
||||
func (d *Split) Bounds() image.Rectangle { return d.bbox }
|
||||
func (d *Split) ColorModel() color.Model { return d.display.ColorModel() }
|
||||
func (d *Split) Halt() error { return nil }
|
||||
func (d *Split) Refresh() error { return d.display.Refresh() }
|
||||
func (d *Split) Size() image.Point { return d.rect.Size() }
|
||||
|
||||
func parseRect(s string) (image.Rectangle, error) {
|
||||
var r image.Rectangle
|
||||
if _, err := fmt.Sscanf(s, "%d,%d,%d,%d", &r.Min.X, &r.Min.Y, &r.Max.X, &r.Max.Y); err != nil {
|
||||
return r, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
Reference in new issue
Block a user