Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:29:41 +01:00
1 parent 0295eb1ad2
commit b8a493b93d
138 files changed
+1898 -57607

No files matched your search

-62
View File
@@ -1,62 +0,0 @@
package hardware
import (
"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"
)
type I2CConfig struct {
// Bus name.
Bus string
// Reset is the reset pin.
Reset gpio.PinOut
// BL is the backlight pin.
BL gpio.PinOut
// Address is the I2C address.
Address uint16
// Frequency is the I2C bus frequency.
Frequency physic.Frequency
}
// Open the configured bus.
func (c I2CConfig) Open() (i2c.BusCloser, error) {
b, err := i2creg.Open(c.Bus)
if err != nil {
return nil, err
}
if c.Frequency != 0 {
if err := b.SetSpeed(c.Frequency); err != nil {
_ = b.Close()
return nil, err
}
}
return b, nil
}
type SPIConfig struct {
// Port is the SPI port name.
Port string
// Reset is the reset pin.
Reset gpio.PinOut
// CS is the chip select pin.
CS gpio.PinOut
// DC is the data/command pin.
DC gpio.PinOut
// BL is the backlight pin.
BL gpio.PinOut
// Frequency is the SPI bus frequency.
Frequency physic.Frequency
}
+26
View File
@@ -0,0 +1,26 @@
package hardware
import (
"image"
"image/color"
"image/draw"
)
// Display driver.
type Display interface {
Driver
// Draw an image on the display.
Draw(r image.Rectangle, src image.Image, sp image.Point) error
// Size of the display.
Size() image.Point
// Fill with one color.
Fill(color.Color) error
// Refresh the display.
Refresh() error
draw.Image
}
+6
View File
@@ -0,0 +1,6 @@
// Package all loads all display drivers.
package all
import (
_ "go.maze.io/harmon/hardware/display/ssd1306" // SSD1306
)
+273
View File
@@ -0,0 +1,273 @@
package display
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"go.maze.io/harmon/config"
"go.maze.io/harmon/hardware"
"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"
)
// Rotation is how much a display has been rotated. Displays can be rotated, and
// sometimes also mirrored.
type Rotation uint8
// Clockwise rotation of the screen.
const (
NoRotation Rotation = iota
Rotate90
Rotate180
Rotate270
)
func (r Rotation) String() string {
switch r {
case NoRotation:
return "none"
case Rotate90:
return "90°"
case Rotate180:
return "180°"
case Rotate270:
return "270°"
default:
return "invalid"
}
}
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)
}
}
// Options for most displays.
type Options struct {
W int // Width
H int // Height
Rotate Rotation // Rotate screen
Flip bool // Flip screen vertically
Mirror bool // Mirror screen horizontally
Backlight gpio.PinOut // Backlight pin
Sequential bool // Sequential mode
SwapTopBottom bool //
}
// Common display options.
func ParseOptions(config config.DisplayConfig, defaultWidth, defaultHeight int) (*Options, error) {
w, h, err := ParseSize(config.Size, defaultWidth, defaultHeight)
if err != nil {
return nil, err
}
rotate, err := ParseRotation(config.Rotate)
if err != nil {
return nil, err
}
var bl gpio.PinOut
if config.BL != "" {
if bl, err = hardware.LookupPin(config.BL); err != nil {
return nil, err
}
}
return &Options{
W: w,
H: h,
Rotate: rotate,
Flip: config.Flip,
Mirror: config.Mirror,
Backlight: bl,
}, nil
}
// ParserAddr parses an I2C address.
func ParseAddr(addr string) (uint16, error) {
var (
addr64 uint64
err error
)
if strings.HasPrefix(strings.ToLower(addr), "0x") {
addr64, err = strconv.ParseUint(addr[2:], 16, 16)
} else {
addr64, err = strconv.ParseUint(addr, 16, 16)
}
if err != nil {
return math.MaxUint16, InvalidAddr(addr, err)
}
return uint16(addr64), nil
}
// ParseSize parses a display size.
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("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
}
// InvalidAddr indicates an invalid address.
func InvalidAddr(addr string, err error) error {
if err != nil {
return fmt.Errorf("invalid address %q: %w", addr, err)
}
return fmt.Errorf("invalid address %q", addr)
}
// InvalidMode indicates an unknown mode.
func InvalidMode(mode string) error {
return fmt.Errorf("invalid display mode %q", mode)
}
// Conn is a display hardware connection (backed by I²C, SPI, etc.).
type Conn interface {
// Tx transfers data over the bus.
Tx(data []byte, isCommand bool) error
}
type i2cConn struct {
dev *i2c.Dev
}
func (c i2cConn) Tx(data []byte, isCommand bool) error {
if isCommand {
return c.dev.Tx(append([]byte{0x00}, data...), nil)
} else {
return c.dev.Tx(append([]byte{0x40}, data...), nil)
}
}
// OpenI2C opens the named I²C bus and connects to the device at addr.
func OpenI2C(name, addr string) (Conn, error) {
log := logrus.WithFields(logrus.Fields{
"name": name,
"addr": addr,
})
log.Debug("configure I²C bus")
add, err := ParseAddr(addr)
if err != nil {
return nil, err
}
log.Trace("opening I²C bus")
bus, err := i2creg.Open(name)
if err != nil {
return nil, fmt.Errorf("invalid I²C bus %q: %w", name, err)
}
log.Tracef("opened I²C bus %q", bus)
return i2cConn{&i2c.Dev{
Bus: bus,
Addr: add,
}}, nil
}
type spiConn struct {
conn spi.Conn
reset gpio.PinOut
dc gpio.PinOut
}
func (c spiConn) Tx(data []byte, isCommand bool) (err error) {
if c.dc == nil {
return errors.New("3-wire SPI mode is not implemented")
}
level := gpio.High
if isCommand {
level = gpio.Low
}
if err = c.dc.Out(level); err != nil {
return
}
return c.conn.Tx(data, nil)
}
// OpenSPI opens the named SPI port and connects to the device.
func OpenSPI(name, resetPin, dcPin string) (Conn, error) {
log := logrus.WithFields(logrus.Fields{
"name": name,
"pin_reset": resetPin,
"pin_dc": dcPin,
})
log.Debug("configure SPI bus")
var (
reset = gpioreg.ByName(resetPin)
dc = gpioreg.ByName(dcPin)
bits = 8
)
if !hardware.IsValidPin(reset) {
return nil, hardware.PinNotFound{"reset", resetPin}
}
if dcPin == "" {
bits = 9
} else if !hardware.IsValidPin(dc) {
return nil, hardware.PinNotFound{"dc", dcPin}
}
log.Trace("opening SPI port")
port, err := spireg.Open(name)
if err != nil {
return nil, fmt.Errorf("invalid SPI port %q: %w", name, err)
}
log.Tracef("opened SPI port %q", port)
log.Trace("connecting to SPI port")
conn, err := port.Connect(100*physic.MegaHertz, spi.Mode0, bits)
if err != nil {
_ = port.Close()
return nil, fmt.Errorf("error connecting to SPI port %q: %w", name, err)
}
return spiConn{
conn: conn,
reset: reset,
dc: dc,
}, nil
}
+24
View File
@@ -0,0 +1,24 @@
package display
import (
"image"
"image/draw"
"go.maze.io/harmon/internal/pixel"
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
)
func DrawText(d draw.Image, x, y int, text string) {
var (
point = fixed.Point26_6{fixed.Int26_6(x * 64), fixed.Int26_6(y * 64)}
drawer = &font.Drawer{
Dst: d,
Src: &image.Uniform{pixel.On},
Face: basicfont.Face7x13,
Dot: point,
}
)
drawer.DrawString(text)
}
+32
View File
@@ -0,0 +1,32 @@
package display
import (
"fmt"
"github.com/sirupsen/logrus"
"go.maze.io/harmon/config"
"go.maze.io/harmon/hardware"
)
var drivers = make(map[string]Opener)
// Opener can open a display driver.
type Opener func(config.DisplayConfig) (hardware.Display, error)
// Register a display driver.
func Register(kind string, opener Opener) {
logrus.WithField("type", kind).Trace("register display driver")
if _, dupe := drivers[kind]; dupe {
panic("driver " + kind + " is already registered")
}
drivers[kind] = opener
}
// Load a display driver.
func Load(config config.DisplayConfig) (hardware.Display, error) {
logrus.WithField("type", config.Type).Debug("load display driver")
if opener, ok := drivers[config.Type]; ok {
return opener(config)
}
return nil, fmt.Errorf("display driver %q is unknown", config.Type)
}
+11
View File
@@ -0,0 +1,11 @@
package display
import (
"image/color"
"go.maze.io/harmon/hardware"
)
func DrawSprite(display hardware.Display, x, y int, sprite []byte, c color.Color) error {
return nil
}
+42
View File
@@ -0,0 +1,42 @@
package ssd1306
type VCCMode uint8
// Registers
const (
setcontrast = 0x81
displayAllOnResume = 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
activateScroll = 0x2F
deactivateScroll = 0x2E
setVerticalScrollArea = 0xA3
rightHorizontalScroll = 0x26
leftHorizontalScroll = 0x27
verticalAndRightHorizontalScroll = 0x29
verticalAndLeftHorizontalScroll = 0x2A
)
const (
ExternalVCC VCCMode = iota + 0x1
SwitchCapVCC
)
+360
View File
@@ -0,0 +1,360 @@
// Package ssd1306 implements SSD1306 (monochrome) OLED displays.
package ssd1306
import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
"periph.io/x/conn/v3/gpio"
"go.maze.io/harmon/config"
"go.maze.io/harmon/hardware"
"go.maze.io/harmon/hardware/display"
"go.maze.io/harmon/internal/pixel"
)
const (
defaultWidth = 128
defaultHeight = 64
)
func init() {
display.Register("ssd1306", newDriver)
}
type Display struct {
conn display.Conn
rect image.Rectangle
rotate display.Rotation
bl gpio.PinOut
buffer []byte
next *pixel.VerticalLSB
startPage, endPage int
startCol, endCol int
scrolled bool
halted bool
}
func (Display) Type() string { return "ssd1306" }
func newDriver(config config.DisplayConfig) (hardware.Display, error) {
var (
opts *display.Options
conn display.Conn
err error
)
if opts, err = display.ParseOptions(config, defaultWidth, defaultHeight); err != nil {
return nil, err
}
if opts.Rotate == display.Rotate180 {
// Let the hardware handle this rotation.
opts.Flip = true
opts.Mirror = true
}
switch config.Mode {
case "", "i2c":
conn, err = display.OpenI2C(config.Bus, config.Address)
case "spi":
conn, err = display.OpenSPI(config.Port, config.Reset, config.DC)
default:
return nil, display.InvalidMode(config.Mode)
}
if err != nil {
return nil, err
}
return newDisplay(conn, opts)
}
func newDisplay(conn display.Conn, opts *display.Options) (*Display, error) {
if opts.W < 8 || opts.W > 128 || opts.W&7 != 0 {
return nil, fmt.Errorf("invalid width %d", opts.W)
}
if opts.H < 8 || opts.H > 64 || opts.H&7 != 0 {
return nil, fmt.Errorf("invalid height %d", opts.H)
}
nbPages := opts.H / 8
pageSize := opts.W
d := &Display{
conn: conn,
bl: opts.Backlight,
rect: image.Rect(0, 0, opts.W, opts.H),
rotate: opts.Rotate,
buffer: make([]byte, nbPages*pageSize),
startPage: 0,
endPage: nbPages,
startCol: 0,
endCol: opts.W,
scrolled: true, // Signal that the screen must be redrawn on first draw().
}
if err := d.sendCommand(getInitCmd(opts)); err != nil {
return nil, err
}
return d, nil
}
func (d *Display) sendData(data []byte) error {
if d.halted {
// Transparently enable the display.
if err := d.sendCommand(nil); err != nil {
return err
}
}
return d.conn.Tx(data, false)
}
func (d *Display) sendCommand(data []byte) error {
if d.halted {
// Transparently enable the display.
data = append([]byte{0xAF}, data...)
d.halted = false
}
return d.conn.Tx(data, true)
}
func (d *Display) 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 *Display) 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{
pageAddr | 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
}
// Halt turns off the display.
//
// Sending any other command afterward reenables the display.
func (d *Display) Halt() error {
d.halted = false
err := d.sendCommand([]byte{0xAE})
if err == nil {
d.halted = true
}
return err
}
// Size of the display.
func (d *Display) Size() image.Point {
if d.rotate == display.Rotate90 || d.rotate == display.Rotate270 {
return image.Pt(d.rect.Max.Y, d.rect.Max.X)
}
return d.rect.Max
}
// 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 *Display) Draw(r image.Rectangle, src image.Image, sp image.Point) error {
var next []byte
if img, ok := src.(*pixel.VerticalLSB); ok && r.Eq(d.rect) && img.Rect.Eq(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 = pixel.NewVerticalLSB(d.rect)
}
next = d.next.Pix
draw.Src.Draw(d.next, r, src, sp)
}
return d.drawInternal(next)
}
func getInitCmd(opts *display.Options) []byte {
// Set COM output scan direction; C0 means normal; C8 means reversed
comScan := byte(0xC8)
// See page 40.
columnAddr := byte(0xA1)
if opts.Rotate == display.Rotate180 {
// Change order both horizontally and vertically.
comScan = 0xC0
columnAddr = byte(0xA0)
}
if opts.Flip {
comScan = byte(0xC0)
}
if opts.Mirror {
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 *Display) Invert(on bool) error {
if on {
return d.sendCommand([]byte{0xA7})
}
return d.sendCommand([]byte{0xA6})
}
/* hardware.Display interface methods */
func (d *Display) Fill(c color.Color) error {
//return d.Draw(d.rect, &image.Uniform{c}, image.Point{})
return d.sendCommand([]byte{0xa7}) // invert :D
}
func (d *Display) Refresh() error {
if d.next == nil {
return nil
}
return d.drawInternal(d.next.Pix)
}
/* draw.Image interface methods */
func (d *Display) At(x, y int) color.Color {
if d.next == nil {
return pixel.Off
}
return d.next.At(x, y)
}
func (d *Display) Bounds() image.Rectangle {
return d.rect
}
func (d *Display) ColorModel() color.Model {
return pixel.MonochromeModel
}
func (d *Display) Set(x, y int, c color.Color) {
if d.next == nil {
d.next = pixel.NewVerticalLSB(d.rect)
}
d.next.Set(x, y, c)
}
+37 -9
View File
@@ -1,17 +1,45 @@
// Package hardware contains all hardware interface implementations.
package hardware
import "errors"
import (
"fmt"
// Resource is a basic resource (like an input) or a device.
type Resource interface {
// String returns the human readable name of the resource.
String() string
"periph.io/x/conn/v3/gpio"
"periph.io/x/conn/v3/gpio/gpioreg"
)
// Halt stops the resource.
// Driver is a piece of hardware that can be stopped.
type Driver interface {
// Type of the driver.
Type() string
// Halt shuts down the driver.
Halt() error
}
// IsNotFound for resources that return a NotFound error.
func IsNotFound(err error) bool {
return errors.Is(err, PinNotFound{})
// PinNotFound error indicating that the requested pin could not be found.
type PinNotFound struct {
Alias string
Name string
}
func (err PinNotFound) Error() string {
if err.Alias == "" {
return fmt.Sprintf("invalid pin %q", err.Name)
}
return fmt.Sprintf("invalid %s pin %q", err.Alias, err.Name)
}
// LookupPin returns a GPIO pin by name or number.
func LookupPin(name string) (gpio.PinIO, error) {
pin := gpioreg.ByName(name)
if !IsValidPin(pin) {
return nil, PinNotFound{Name: name}
}
return pin, nil
}
// IsValidPin checks if the provided GPIO pin can be used.
func IsValidPin(pin gpio.PinIO) bool {
return pin != nil && pin != gpio.INVALID
}
-48
View File
@@ -1,48 +0,0 @@
package hardware
import (
"fmt"
"periph.io/x/conn/v3/gpio"
"periph.io/x/conn/v3/gpio/gpioreg"
)
// PinNotFound error indicating that the requested pin could not be found.
type PinNotFound struct {
Name string
}
func (err PinNotFound) Error() string {
return fmt.Sprintf("invalid pin %q", err.Name)
}
// LookupPin returns a GPIO pin by name or number.
func LookupPin(name string) (gpio.PinIO, error) {
pin := gpioreg.ByName(name)
if !IsValidPin(pin) {
return nil, PinNotFound{name}
}
return pin, nil
}
// LookupPinIn returns a GPIO input pin by name or number.
func LookupPinIn(name string) (gpio.PinIn, error) {
return LookupPin(name)
}
// LookupPinOut returns a GPIO output pin by name or number.
func LookupPinOut(name string) (gpio.PinOut, error) {
return LookupPin(name)
}
func IsValidPin(pin gpio.PinIO) bool {
return pin != nil && pin != gpio.INVALID
}
func IsValidPinIn(pin gpio.PinIn) bool {
return pin != nil && pin != gpio.INVALID
}
func IsValidPinOut(pin gpio.PinOut) bool {
return pin != nil && pin != gpio.INVALID
}