Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:29:41 +01:00
1 parent b8a493b93d
commit 85a9ec684c
54 files changed
+6855 -526

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
package calc
import "math"
// Complex is a constraint that permits any complex numeric type.
type Complex interface {
~complex64 | ~complex128
}
// Float is a constraint that permits any floating-point type.
type Float interface {
~float32 | ~float64
}
// Integer is a constraint that permits any integer type.
type Integer interface {
Signed | Unsigned
}
// Signed is a constraint that permits any signed integer type.
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
// Unsigned is a constraint that permits any unsigned integer type.
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
// Number are real valued number types.
type Number interface {
Integer | Float
}
// Sum of values.
func Sum[T Number](data []T) T {
if len(data) == 0 {
return 0
}
var sum T
for _, v := range data {
sum += v
}
return sum
}
// Mean of values.
func Mean[T Number](data []T) float64 {
if len(data) == 0 {
return 0
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, v := range data {
var (
x = float64(v)
i int
)
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(data))
}
// MeanOffset is the mean of values every offset starting at start.
func MeanOffset[T Number](data []T, start, offset int) float64 {
if len(data)/offset == 0 {
return 0
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for j, l := start, len(data); j < l; j += offset {
var (
x = float64(data[j])
i int
)
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(data))
}
// RMS is the root mean square of values.
func RMS[T Number](data []T) float64 {
if len(data) == 0 {
return 0
}
var squares float64
for _, v := range data {
squares += float64(v) * float64(v)
}
return math.Sqrt(squares / float64(len(data)))
}
// RMSOffset is the root mean square of values every offset.
func RMSOffset[T Number](data []T, start, offset int) float64 {
if len(data)/offset == 0 {
return 0
}
var squares float64
for i, l := start, len(data); i < l; i += offset {
squares += float64(data[i]) * float64(data[i])
}
return math.Sqrt(squares / float64(len(data)/offset))
}
func Eq(a, b, epsilon float32) bool {
return math.Abs(float64(a-b)) < float64(epsilon)
}
func AlmostEq(a, b float32) bool {
return Eq(a, b, 1e-20)
}
+46
View File
@@ -0,0 +1,46 @@
package calc_test
import (
"math"
"testing"
"go.maze.io/harmon/internal/calc"
)
func TestMean(t *testing.T) {
testCases := []struct {
Test []float32
Want float64
}{
{nil, 0},
{[]float32{3, 1, 4, 1, 5, 9}, 3.8333333333333335},
{[]float32{1e20, 3, 1, 4, 1, 5, 9, -1e20}, 2.875},
{[]float32{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11}, 3.674},
{[]float32{10, 20, 30, 40, 50, -100, 4.7, -11e2}, -130.66250002384186},
}
for _, test := range testCases {
if v := calc.Mean(test.Test); !almostEq(v, test.Want) {
t.Errorf("expected Mean(%v) to return %g, got %g", test.Test, test.Want, v)
}
}
}
func TestRMS(t *testing.T) {
testCases := []struct {
Test []float32
Want float64
}{
{[]float32{3, 1, 4, 1, 5, 9}, 4.708148963941845},
{[]float32{1e20, 3, 1, 4, 1, 5, 9, -1e20}, 5.000000100204387e+19},
{[]float32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 6.2048368229954285},
}
for _, test := range testCases {
if v := calc.RMS(test.Test); !almostEq(v, test.Want) {
t.Errorf("expected RMS(%v) to return %g, got %g", test.Test, test.Want, v)
}
}
}
func almostEq(a, b float64) bool {
return math.Abs(a-b) < 1e-5
}
+171 -8
View File
@@ -2,9 +2,54 @@ package pixel
import "image/color"
var (
MonochromeModel color.Model = color.ModelFunc(monochromeModel)
)
// Pixel with a particular color, matching the underlying hardware of a
// particular display. Each pixel is at least 1 byte in size.
// The color format is sRGB (or close to it) in all cases except for 1-bit.
type Color interface {
Monochrome | RGB444 | RGB565
BaseColor
}
// BaseColor contains all the methods needed in a color format. This can be used
// in display drivers that want to define their own Color type with just the
// pixel formats the display supports.
type BaseColor interface {
color.Color
// The number of bits when stored.
// This means for example that RGB555 (which is still stored as a 16-bit
// integer) returns 16, while RGB444 returns 12.
BitsPerPixel() int
// Return the given color in color.RGBA format, which is always sRGB. The
// alpha channel is always 255.
RGBAColor() color.RGBA
}
// NewColor returns the given color based on the RGB values passed in the
// parameters. The input value is assumed to be in sRGB color space.
func NewColor[T Color](r, g, b uint8) T {
// Ugly cast from color.RGBA to T. The type switch and interface casts are
// trivially optimized away after instantiation.
var value T
switch any(value).(type) {
case Monochrome:
return any(NewMonochrome(r, g, b)).(T)
case RGB444:
return any(NewRGB444(r, g, b)).(T)
case RGB565:
return any(NewRGB565(r, g, b)).(T)
/*
case RGB555:
return any(NewRGB555(r, g, b)).(T)
case RGB888:
return any(NewRGB888(r, g, b)).(T)
*/
default:
panic("unknown color format")
}
}
// ToGrayBits converts a color to a n-bit grayscale color.
func ToGrayBits(c color.Color, n uint8) uint16 {
@@ -39,6 +84,13 @@ const (
On
)
func NewMonochrome(r, g, b uint8) Monochrome {
if ToGrayBits(color.RGBA{r, g, b, 0xff}, 1) == 1 {
return On
}
return Off
}
func (c Monochrome) RGBA() (r, g, b, a uint32) {
if c == 0 {
return 0, 0, 0, 0
@@ -46,13 +98,124 @@ func (c Monochrome) RGBA() (r, g, b, a uint32) {
return 0xffff, 0xffff, 0xffff, 0xffff
}
func monochromeModel(c color.Color) color.Color {
func IsOn(c color.Color) bool {
if _, ok := c.(Monochrome); ok {
return c
return c == On
}
return ToGrayBits(c, 1) == 1
}
if ToGrayBits(c, 1) == 0 {
return Off
// Color format that is supported by the ST7789 for example.
// It may be a bit faster to use than RGB565BE on very slow SPI buses.
//
// The color format is native endian as a uint16 (0000rrrr_ggggbbbb), not big
// endian which you might expect. I tried swapping the bytes, but it didn't have
// much of a performance impact and made the code harder to read. It is stored
// as a 12-bit big endian value in Image[RGB444] though.
type RGB444 uint16
func NewRGB444(r, g, b uint8) RGB444 {
return RGB444(r>>4)<<8 | RGB444(g>>4)<<4 | RGB444(b>>4)
}
func (c RGB444) BitsPerPixel() int {
return 12
}
func (c RGB444) RGBA() (r, g, b, a uint32) {
r = uint32(c>>8) & 0x0f
r |= (r << 4) | (r << 8) | (r << 12)
g = uint32(c>>4) & 0x0f
g |= (g << 4) | (g << 8) | (g << 12)
b = uint32(c>>0) & 0x0f
b |= (b << 4) | (b << 8) | (b << 12)
a |= 0xffff
return
}
func (c RGB444) RGBAColor() color.RGBA {
color := color.RGBA{
R: uint8(c>>8) << 4,
G: uint8(c>>4) << 4,
B: uint8(c>>0) << 4,
A: 255,
}
// Correct color rounding, so that 0xff roundtrips back to 0xff.
color.R |= color.R >> 4
color.G |= color.G >> 4
color.B |= color.B >> 4
return color
}
// RGB565 color.
type RGB565 uint16
func NewRGB565(r, g, b uint8) RGB565 {
val := uint16(r&0xF8)<<8 +
uint16(g&0xFC)<<3 +
uint16(b&0xF8)>>3
// Swap endianness (make big endian).
// This is done using a single instruction on ARM (rev16).
// TODO: this should only be done on little endian systems, but TinyGo
// doesn't currently (2023) support big endian systems so it's difficult to
// test. Also, big endian systems don't seem fasionable these days.
//val = bits.ReverseBytes16(val)
return RGB565(val)
}
// FromColor retusn the given color.
func FromColor[T Color](c color.Color) T {
var value T
switch any(value).(type) {
case Monochrome:
return monochromeModel(c).(T)
case RGB444:
return rgb444Model(c).(T)
case RGB565:
return rgb565Model(c).(T)
/*
case RGB555:
return rgb555Model(c).(T)
case RGB888:
return rgb888Model(c).(T)
*/
default:
panic("unknown color format")
}
}
func (c RGB565) BitsPerPixel() int {
return 16
}
func (c RGB565) RGBA() (r, g, b, a uint32) {
r = uint32(uint8(c>>12) << 3)
r |= (r >> 5)
r |= (r << 8)
g = uint32(uint8(c>>5) << 2)
g |= (g >> 6)
g |= (g << 8)
b = uint32(uint8(c>>0) << 3)
b |= (b >> 5)
b |= (b << 8)
a = 0xffff
return
}
func (c RGB565) RGBAColor() color.RGBA {
// Note: on ARM, the compiler uses a rev instruction instead of a rev16
// instruction. I wonder whether this can be optimized further to use rev16
// instead?
c = c<<8 | c>>8
color := color.RGBA{
R: uint8(c>>11) << 3,
G: uint8(c>>5) << 2,
B: uint8(c) << 3,
A: 255,
}
return On
// Correct color rounding, so that 0xff roundtrips back to 0xff.
color.R |= color.R >> 5
color.G |= color.G >> 6
color.B |= color.B >> 5
return color
}
+368
View File
@@ -3,8 +3,376 @@ package pixel
import (
"image"
"image/color"
"image/draw"
"unsafe"
)
// Image buffer, used for working with the native image format of various
// displays. It works a lot like a slice: it can be rescaled while reusing the
// underlying buffer and should be passed around by value.
type Image[T Color] struct {
width int16
height int16
data unsafe.Pointer
}
// NewImage creates a new image of the given size.
func NewImage[T Color](width, height int) Image[T] {
if width < 0 || height < 0 || int(int16(width)) != width || int(int16(height)) != height {
// The width/height are stored as 16-bit integers and should never be
// negative.
panic("NewImage: width/height out of bounds")
}
var zeroColor T
var data unsafe.Pointer
switch {
case zeroColor.BitsPerPixel()%8 == 0:
// Typical formats like RGB888 and RGB565.
// Each color starts at a whole byte offset from the start.
buf := make([]T, width*height)
data = unsafe.Pointer(&buf[0])
default:
// Formats like RGB444 that have 12 bits per pixel.
// We access these as bytes, so allocate the buffer as a byte slice.
bufBits := width * height * zeroColor.BitsPerPixel()
bufBytes := (bufBits + 7) / 8
buf := make([]byte, bufBytes)
data = unsafe.Pointer(&buf[0])
}
return Image[T]{
width: int16(width),
height: int16(height),
data: data,
}
}
// NewImageFromBytes creates a new image of the given size using an existing data slice of bytes.
func NewImageFromBytes[T Color](width, height int, buf []byte) Image[T] {
if width < 0 || height < 0 || int(int16(width)) != width || int(int16(height)) != height {
// The width/height are stored as 16-bit integers and should never be
// negative.
panic("NewImageFromBytes: width/height out of bounds")
}
var zeroColor T
var data unsafe.Pointer
switch {
case zeroColor.BitsPerPixel()%8 == 0:
// Typical formats like RGB888 and RGB565.
// Each color starts at a whole byte offset from the start.
if len(buf) != width*height*int(unsafe.Sizeof(zeroColor)) {
panic("NewImageFromBytes: data slice size mismatch")
}
data = unsafe.Pointer(&buf[0])
default:
// Formats like RGB444 that have 12 bits per pixel.
// We access these as bytes, so allocate the buffer as a byte slice.
bufBits := width * height * zeroColor.BitsPerPixel()
bufBytes := (bufBits + 7) / 8
if len(buf) != bufBytes {
panic("NewImageFromBytes: data slice size mismatch")
}
data = unsafe.Pointer(&buf[0])
}
return Image[T]{
width: int16(width),
height: int16(height),
data: data,
}
}
// NewImageFromImage creates a new image from the provided image.
func NewImageFromImage[T Color](src image.Image) Image[T] {
var (
r = src.Bounds()
width = r.Dx()
height = r.Dy()
dst = NewImage[T](width, height)
)
draw.Draw(dst, r, src, image.Point{}, draw.Src)
return dst
}
// Rescale returns a new Image buffer based on the img buffer.
// The contents is undefined after the Rescale operation, and any modification
// to the returned image will overwrite the underlying image buffer in undefined
// ways. It will panic if width*height is larger than img.Len().
func (img Image[T]) Rescale(width, height int) Image[T] {
if width*height > img.Len() {
panic("Image.Rescale size out of bounds")
}
return Image[T]{
width: int16(width),
height: int16(height),
data: img.data,
}
}
// LimitHeight returns a subimage with the bottom part cut off, as specified by
// height.
func (img Image[T]) LimitHeight(height int) Image[T] {
if height < 0 || height > int(img.height) {
panic("Image.LimitHeight: out of bounds")
}
return Image[T]{
width: img.width,
height: int16(height),
data: img.data,
}
}
// Len returns the number of pixels in this image buffer.
func (img Image[T]) Len() int {
return int(img.width) * int(img.height)
}
// RawBuffer returns a byte slice that can be written directly to the screen
// using DrawRGBBitmap8.
func (img Image[T]) RawBuffer() []uint8 {
var zeroColor T
var numBytes int
switch {
case zeroColor.BitsPerPixel()%8 == 0:
// Each color starts at a whole byte offset.
numBytes = int(unsafe.Sizeof(zeroColor)) * int(img.width) * int(img.height)
default:
// Formats like RGB444 that aren't a whole number of bytes.
numBits := zeroColor.BitsPerPixel() * int(img.width) * int(img.height)
numBytes = (numBits + 7) / 8 // round up (see NewImage)
}
return unsafe.Slice((*byte)(img.data), numBytes)
}
// Size returns the image size.
func (img Image[T]) Size() (int, int) {
return int(img.width), int(img.height)
}
func (img Image[T]) setPixel(index int, c T) {
var zeroColor T
switch {
case zeroColor.BitsPerPixel() == 1:
// Monochrome.
offset := index / 8
bits := index % 8
ptr := (*byte)(unsafe.Add(img.data, offset))
if c != zeroColor {
*((*byte)(ptr)) |= (1 << (7 - uint8(bits)))
} else {
*((*byte)(ptr)) &^= (1 << (7 - uint8(bits)))
}
return
case zeroColor.BitsPerPixel()%8 == 0:
// Each color starts at a whole byte offset.
// This is the easy case.
offset := index * int(unsafe.Sizeof(zeroColor))
ptr := unsafe.Add(img.data, offset)
*((*T)(ptr)) = c
return
}
if c, ok := any(c).(RGB444); ok {
// Special case for RGB444.
bitIndex := index * zeroColor.BitsPerPixel()
if bitIndex%8 == 0 {
byteOffset := bitIndex / 8
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
ptr[0] = uint8(c >> 4)
ptr[1] = ptr[1]&0x0f | uint8(c)<<4 // change top bits
} else {
byteOffset := bitIndex / 8
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
ptr[0] = ptr[0]&0xf0 | uint8(c>>8) // change bottom bits
ptr[1] = uint8(c)
}
return
}
// TODO: the code for RGB444 should be generalized to support any bit size.
panic("todo: setPixel for odd bits per pixel")
}
// Set sets the pixel at x, y to the given color.
// Use FillSolidColor to efficiently fill the entire image buffer.
func (img Image[T]) SetPixel(x, y int, c T) {
if uint(x) >= uint(int(img.width)) || uint(y) >= uint(int(img.height)) {
return
}
index := y*int(img.width) + x
img.setPixel(index, c)
}
// Get returns the color at the given index.
func (img Image[T]) GetPixel(x, y int) T {
var zeroColor T
if uint(x) >= uint(int(img.width)) || uint(y) >= uint(int(img.height)) {
return zeroColor
}
index := y*int(img.width) + x // index into img.data
switch {
case zeroColor.BitsPerPixel() == 1:
// Monochrome.
var c Monochrome
offset := index / 8
bits := index % 8
ptr := (*byte)(unsafe.Add(img.data, offset))
c = Monochrome((*ptr >> (7 - uint8(bits))) & 0x1)
return any(c).(T)
case zeroColor.BitsPerPixel()%8 == 0:
// Colors like RGB565, RGB888, etc.
offset := index * int(unsafe.Sizeof(zeroColor))
ptr := unsafe.Add(img.data, offset)
return *((*T)(ptr))
}
if _, ok := any(zeroColor).(RGB444); ok {
// Special case for RGB444 that isn't stored in a neat byte multiple.
bitIndex := index * zeroColor.BitsPerPixel()
var c RGB444
if bitIndex%8 == 0 {
byteOffset := bitIndex / 8
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
c |= RGB444(ptr[0]) << 4
c |= RGB444(ptr[1] >> 4) // load top bits
} else {
byteOffset := bitIndex / 8
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
c |= RGB444(ptr[0]&0x0f) << 8 // load bottom bits
c |= RGB444(ptr[1])
}
return any(c).(T)
}
// TODO: generalize the above code.
panic("todo: Image.Get for odd bits per pixel")
}
// FillSolidColor fills the entire image with the given color.
// This may be faster than setting individual pixels.
func (img Image[T]) FillSolidColor(color T) {
var zeroColor T
switch {
case zeroColor.BitsPerPixel() == 1:
// Monochrome.
var colorByte uint8
if color != zeroColor {
colorByte = 0xff
}
numBytes := int(img.width) * int(img.height) / 8
for i := 0; i < numBytes; i++ {
// TODO: this can be optimized a lot.
// - The store can be done as a 32-bit integer, after checking for
// alignment.
// - Perhaps the loop can be unrolled to improve copy performance.
ptr := (*byte)(unsafe.Add(img.data, i))
*((*byte)(ptr)) = colorByte
}
return
case zeroColor.BitsPerPixel()%8 == 0:
// Fast pass for colors of 8, 16, 24, etc bytes in size.
ptr := img.data
for i := 0; i < img.Len(); i++ {
// TODO: this can be optimized a lot.
// - The store can be done as a 32-bit integer, after checking for
// alignment.
// - Perhaps the loop can be unrolled to improve copy performance.
*(*T)(ptr) = color
ptr = unsafe.Add(ptr, unsafe.Sizeof(zeroColor))
}
return
}
// Special case for RGB444.
if c, ok := any(color).(RGB444); ok {
// RGB444 can be stored in a more optimized way, by storing two colors
// at a time instead of setting each color individually. This avoids
// loading and masking the old color bits for the half-bytes.
var buf [3]uint8
buf[0] = uint8(c >> 4)
buf[1] = uint8(c)<<4 | uint8(c>>8)
buf[2] = uint8(c)
rawBuf := unsafe.Slice((*[3]byte)(img.data), img.Len()/2)
for i := 0; i < len(rawBuf); i++ {
rawBuf[i] = buf
}
if img.Len()%2 != 0 {
// The image contains an uneven number of pixels.
// This is uncommon, but it can happen and we have to handle it.
img.setPixel(img.Len()-1, color)
}
return
}
// Fallback for other color formats.
for i := 0; i < img.Len(); i++ {
img.setPixel(i, color)
}
}
// At implements the draw.Image interface.
func (img Image[T]) At(x, y int) color.Color {
return img.GetPixel(x, y)
}
// Set implements the draw.Image interface.
func (img Image[T]) Set(x, y int, c color.Color) {
var value T
switch any(value).(type) {
case Monochrome:
img.SetPixel(x, y, monochromeModel(c).(T))
case RGB444:
img.SetPixel(x, y, rgb444Model(c).(T))
case RGB565:
img.SetPixel(x, y, rgb565Model(c).(T))
/*
case RGB888:
img.SetPixel(x, y, rgb888Model(c).(T))
case RGB555:
img.SetPixel(x, y, rgb555Model(c).(T))
*/
default:
}
}
// Bounds returns the image bounding box.
func (img Image[T]) Bounds() image.Rectangle {
return image.Rect(0, 0, int(img.width), int(img.height))
}
// ColorModel returns the image color model.
func (img Image[T]) ColorModel() color.Model {
// Ugly cast from color.RGBA to T. The type switch and interface casts are
// trivially optimized away after instantiation.
var value T
switch any(value).(type) {
case Monochrome:
return MonochromeModel
case RGB444:
return RGB444Model
case RGB565:
return RGB565Model
/*
case RGB888:
return RGB888Model
case RGB555:
return RGB555Model
*/
default:
panic("unknown color format")
}
}
// Clear the image buffer.
func (img *Image[T]) Clear() {
var zeroColor T
img.FillSolidColor(zeroColor)
}
// VerticalLSB is a 1 bit (black and white) image.
//
// Each byte is 8 vertical pixels. Each stride is a horizontal band of 8
+33
View File
@@ -0,0 +1,33 @@
package pixel
import "image/color"
var (
MonochromeModel color.Model = color.ModelFunc(monochromeModel)
RGB444Model color.Model = color.ModelFunc(rgb444Model)
RGB565Model color.Model = color.ModelFunc(rgb565Model)
)
func monochromeModel(c color.Color) color.Color {
if _, ok := c.(Monochrome); ok {
return c
}
r, g, b, _ := c.RGBA()
return NewMonochrome(uint8(r>>8), uint8(g>>8), uint8(b>>8))
}
func rgb444Model(c color.Color) color.Color {
if _, ok := c.(RGB444); ok {
return c
}
r, g, b, _ := c.RGBA()
return RGB444(r>>12)<<8 | RGB444(g>>12)<<4 | RGB444(b>>12)
}
func rgb565Model(c color.Color) color.Color {
if _, ok := c.(RGB565); ok {
return c
}
r, g, b, _ := c.RGBA()
return RGB565(uint16((r>>8)&0xF8)<<8 + uint16((g>>8)&0xFC)<<3 + uint16((b>>8)&0xF8)>>3)
}
+348
View File
@@ -0,0 +1,348 @@
// Copyright 2021 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package spidev wraps the Linux spidev driver and performs low-level SPI
// operations.
package spidev
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"os"
"runtime"
"unsafe"
"golang.org/x/sys/unix"
)
// See Linux "include/uapi/linux/spi/spidev.h" and
// "Documentation/spi/spidev.rst"
// Various ioctl numbers.
const (
iocRdMode = 0x80016b01
iocWrMode = 0x40016b01
iocRdLSBFirst = 0x80016b02
iocWrLSBFirst = 0x40016b02
iocRdBitsPerWord = 0x80016b03
iocWrBitsPerWord = 0x40016b03
iocRdMaxSpeedHz = 0x80046b04
iocWrMaxSpeedHz = 0x40046b04
iocRdMode32 = 0x80046b05
iocWrMode32 = 0x40046b05
)
// Constants used by iocMessage function.
const (
// iocMessage0 is the length of a message of 0 length. Use the
// iocMessage(n) function for an iocMessage of length n.
iocMessage0 = 0x40006b00
sizeBits = 14
sizeShift = 16
sizeMask = ((1 << sizeBits) - 1) << sizeShift
)
// maxTransferSize is the maximum size of a transfer. This is limited by the
// `length uint32` in the iocTransfer struct.
var maxTransferSize = math.MaxInt32
// iocMessage is an ioctl number for n Transfers. Since the ioctl number
// contains the size of the message, it is not a constant.
func iocMessage(n int) uint32 {
size := uint32(n * binary.Size(iocTransfer{}))
if n < 0 || size > (1<<sizeBits) {
return iocMessage(0)
}
return iocMessage0 | (size << sizeShift)
}
// Mode is a bitset of the current SPI mode bits.
type Mode uint32
const (
// CPHA determines clock phase sampling (1=trailing edge).
CPHA Mode = 1 << iota
// CPOL determines clock polarity (1=idle high).
CPOL
// CS_HIGH determines chip select polarity (1=idle high).
CS_HIGH
// LSB_FIRST determines whether least significant bit comes first in a
// word (1=LSB first).
LSB_FIRST
// THREE_WIRE determines whether the bus operates in three wire mode
// (1=three wire).
THREE_WIRE
// LOOP determines whether the device should loop (1=loop enabled).
LOOP
// NO_CS determines whether to disable chip select (1=no chip select).
NO_CS
// READY determins ready mode bit.
READY
// TX_DUAL determines whether to transmit in dual mode.
TX_DUAL
// TX_QUAD determines whether to transmit in quad mode.
TX_QUAD
// RX_DUAL determines whether to receive in dual mode.
RX_DUAL
// RX_QUAD determines whether to receive in quad mode.
RX_QUAD
)
// iocTransfer is the data type used by the iocMessage ioctl. Multiple such
// transfers may be chained together in a single ioctl call.
type iocTransfer struct {
// txBuf contains the userspace address of data to send. If this is 0,
// then zeros are shifted onto the SPI bus.
txBuf uint64
// rxBuf contains the userspace address of data to receive. If this is
// 0, data received is ignored.
rxBuf uint64
// length is the length of max{transfer, txBuf, rxBuf} in bytes.
length uint32
speedHz uint32
delayUSecs uint16
bitsPerWord uint8
csChange uint8
txNBits uint8
rxNBits uint8
wordDelayUSecs uint8
pad uint8
}
// Transfer is the data and options for a single SPI transfer. Note that a SPI
// transfer is full-duplex meaning data is shifted out of Tx and shifted into
// Rx on the same clock cycle.
type Transfer struct {
// Tx contains a slice sent over the SPI bus.
Tx []byte
// Rx contains a slice received from the SPI bus.
Rx []byte
// The following temporarily override the SPI mode. They only apply to
// the current transfer.
// SpeedHz sets speed in Hz (optional).
SpeedHz uint32
// DelayUSecs is how long to delay before the next transfer (optional).
DelayUSecs uint16
// BitsPerWord is the device's wordsize (optional).
BitsPerWord uint8
// CSChange controls whether the CS (Chip Select) signal will be
// de-asserted at the end of the transfer.
CSChange bool
// TxNbits controls single, dual or quad mode (optional).
TxNBits uint8
// RxNbits controls single, dual or quad mode (optional).
RxNBits uint8
// WordDelayUSecs is the delay between words (optional).
WordDelayUSecs uint8
}
func (t *Transfer) String() string {
var x [8]byte
n, _ := io.ReadAtLeast(bytes.NewBuffer(t.Tx), x[:], len(x))
return fmt.Sprintf("%#02x...[:%d](%#02x)", x[:n], len(t.Tx), x[0])
}
// ErrTxOverflow is returned if the Transfer buffer is too large.
type ErrTxOverflow struct {
TxLen, TxMax int
}
// Error implements the error interface.
func (e ErrTxOverflow) Error() string {
return fmt.Sprintf("SPI tx buffer overflow (%d > %d)", e.TxLen, e.TxMax)
}
// ErrRxOverflow is returned if the Transfer buffer is too large.
type ErrRxOverflow struct {
RxLen, RxMax int
}
// Error implements the error interface.
func (e ErrRxOverflow) Error() string {
return fmt.Sprintf("SPI rx buffer overflow (%d > %d)", e.RxLen, e.RxMax)
}
// ErrBufferMismatch is returned if the rx and tx buffers do not have equal
// length.
type ErrBufferMismatch struct {
TxLen, RxLen int
}
// Error implements the error interface.
func (e ErrBufferMismatch) Error() string {
return fmt.Sprintf("SPI tx and rx buffers of unequal length (%d != %d)", e.TxLen, e.RxLen)
}
// SPI wraps the Linux device driver and provides low-level SPI operations.
type SPI struct {
f *os.File
// Used for mocking.
syscall func(trap, a1, a2 uintptr, a3 unsafe.Pointer) (r1, r2 uintptr, err unix.Errno)
// logger allows logging
logger func(string, ...any)
}
type opt func(s *SPI) error
// WithLogger returns an opt which can be used in Open to add
// a logger. A common usage would be:
// spidev.Open("/dev/spidev0.0", WithLogger(log.Printf))
func WithLogger(l func(string, ...any)) opt {
return func(s *SPI) error {
s.logger = l
return nil
}
}
// safe tries to set "safe" settings for initial SPI operation.
// However, settings may not succeed, for $REASONS$.
// Hardware is highly variable.
// If there is an error, log it, and continue.
func (s *SPI) safe() {
if err := s.SetSpeedHz(500000); err != nil {
s.logger("warning only: set speed to %d HZ err %v", 500000, err)
}
}
// Open opens a new SPI device. dev is a filename such as "/dev/spidev0.0".
// Remember to call Close() once done.
func Open(dev string, opts ...opt) (*SPI, error) {
f, err := os.OpenFile(dev, os.O_RDWR, 0)
if err != nil {
return nil, err
}
s := &SPI{
f: f,
logger: func(string, ...any) {}, // log.Printf,
//logger: log.Printf,
// a3 must be an unsafe.Pointer instead of a uintptr, otherwise
// we cannot mock out in the test without creating a race
// condition. See `go doc unsafe.Pointer`.
syscall: func(trap, a1, a2 uintptr, a3 unsafe.Pointer) (r1, r2 uintptr, err unix.Errno) {
return unix.Syscall(trap, a1, a2, uintptr(a3))
},
}
for _, o := range opts {
if err := o(s); err != nil {
return nil, err
}
}
s.safe()
return s, nil
}
// Close closes the SPI device.
func (s *SPI) Close() error {
return s.f.Close()
}
// Transfer performs multiple SPI reads and/or writes in a single function.
// See the Transfer struct for details.
func (s *SPI) Transfer(transfers []Transfer) error {
// Convert []Transfer to []iocTransfer.
it := make([]iocTransfer, len(transfers))
for i, t := range transfers {
s.logger("%d:%s", i, t.String())
it[i] = iocTransfer{
speedHz: t.SpeedHz,
delayUSecs: t.DelayUSecs,
bitsPerWord: t.BitsPerWord,
txNBits: t.TxNBits,
rxNBits: t.RxNBits,
wordDelayUSecs: t.WordDelayUSecs,
}
if len(t.Tx) > maxTransferSize {
return ErrTxOverflow{len(t.Tx), maxTransferSize}
}
if len(t.Rx) > maxTransferSize {
return ErrRxOverflow{len(t.Rx), maxTransferSize}
}
if len(t.Tx) != 0 && len(t.Rx) != 0 && len(t.Tx) != len(t.Rx) {
return ErrBufferMismatch{len(t.Tx), len(t.Rx)}
}
if len(t.Tx) != 0 {
txBuf := &transfers[i].Tx[0]
it[i].txBuf = uint64(uintptr(unsafe.Pointer(txBuf)))
it[i].length = uint32(len(t.Tx))
// Defer garbage collection until after the syscall.
defer runtime.KeepAlive(txBuf)
}
if len(t.Rx) != 0 {
rxBuf := &transfers[i].Rx[0]
it[i].rxBuf = uint64(uintptr(unsafe.Pointer(rxBuf)))
it[i].length = uint32(len(t.Rx))
// Defer garbage collection until after the syscall.
defer runtime.KeepAlive(rxBuf)
}
if transfers[i].CSChange {
it[i].csChange = 1
}
}
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), uintptr(iocMessage(len(transfers))), unsafe.Pointer(&it[0])); err != 0 {
return os.NewSyscallError("ioctl(SPI_IOC_MESSAGE)", err)
}
return nil
}
// Mode returns the Mode bitset.
func (s *SPI) Mode() (Mode, error) {
var m Mode
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), iocRdMode32, unsafe.Pointer(&m)); err != 0 {
return 0, os.NewSyscallError("ioctl(SPI_IOC_RD_MODE32)", err)
}
return m, nil
}
// SetMode sets the Mode bitset.
func (s *SPI) SetMode(m Mode) error {
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), iocWrMode32, unsafe.Pointer(&m)); err != 0 {
return os.NewSyscallError("ioctl(SPI_IOC_WR_MODE32)", err)
}
return nil
}
// BitsPerWord sets the number of bits per word. Myy understanding is this is
// only useful if there is a word delay.
func (s *SPI) BitsPerWord() (uint8, error) {
var bpw uint8
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), iocRdBitsPerWord, unsafe.Pointer(&bpw)); err != 0 {
return bpw, os.NewSyscallError("ioctl(SPI_IOC_RD_BITS_PER_WORD)", err)
}
return bpw, nil
}
// SetBitsPerWord sets the number of bits per word.
func (s *SPI) SetBitsPerWord(bpw uint8) error {
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), iocWrBitsPerWord, unsafe.Pointer(&bpw)); err != 0 {
return os.NewSyscallError("ioctl(SPI_IOC_WR_BITS_PER_WORD)", err)
}
return nil
}
// SpeedHz gets the transfer speed.
func (s *SPI) SpeedHz() (uint32, error) {
var hz uint32
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), iocRdMaxSpeedHz, unsafe.Pointer(&hz)); err != 0 {
return hz, os.NewSyscallError("ioctl(SPI_IOC_RD_MAX_SPEED_HZ)", err)
}
return hz, nil
}
// SetSpeedHz sets the transfer speed.
func (s *SPI) SetSpeedHz(hz uint32) error {
if _, _, err := s.syscall(unix.SYS_IOCTL, s.f.Fd(), iocWrMaxSpeedHz, unsafe.Pointer(&hz)); err != 0 {
return os.NewSyscallError("ioctl(SPI_IOC_WR_MAX_SPEED_HZ)", err)
}
return nil
}