Checkpoint
No files matched your search
@@ -0,0 +1,23 @@
|
||||
GO_BUILD := go build -ldflags="-w -s" \
|
||||
-gcflags=-trimpath=/Users/myuser/dev/go/src \
|
||||
-asmflags=-trimpath=/Users/myuser/dev/go/src \
|
||||
|
||||
SOURCES := $(wildcard *.go) \
|
||||
$(wildcard hardware/*.go) \
|
||||
$(wildcard hardware/display/*.go) \
|
||||
$(wildcard hardware/display/*/*.go) \
|
||||
$(wildcard config/*.go) \
|
||||
$(wildcard internal/*/*.go) \
|
||||
$(wildcard audio/*.go) \
|
||||
$(wildcard visual/*/*.go) \
|
||||
$(wildcard player/*.go) \
|
||||
$(wildcard player/*/*.go)
|
||||
|
||||
.PHONY:
|
||||
harmon: $(SOURCES)
|
||||
GOOS=linux GOARCH=arm $(GO_BUILD) -o $@ ./cmd/harmon
|
||||
|
||||
clean:
|
||||
$(RM) harmon
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
type Buffer struct {
|
||||
Buf []byte
|
||||
Ch int
|
||||
Format Format
|
||||
}
|
||||
|
||||
// NewBuffer returns a buffer of n samples and ch channels.
|
||||
func NewBuffer(n, ch int, f Format) *Buffer {
|
||||
if ch < 1 {
|
||||
ch = 1
|
||||
}
|
||||
return &Buffer{
|
||||
Buf: make([]byte, n*ch*f.BytesPerSample()),
|
||||
Ch: ch,
|
||||
Format: f,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) Decode(data any, order binary.ByteOrder) (n int, err error) {
|
||||
switch data := data.(type) {
|
||||
case []int8:
|
||||
var x byte
|
||||
for n, x = range b.Buf {
|
||||
data[n] = int8(x)
|
||||
}
|
||||
case []uint8:
|
||||
n = copy(data, b.Buf)
|
||||
case []int16:
|
||||
for n = range data {
|
||||
data[n] = int16(order.Uint16(b.Buf[n<<1:]))
|
||||
}
|
||||
case []int32:
|
||||
for n = range data {
|
||||
data[n] = int32(order.Uint32(b.Buf[n<<2:]))
|
||||
}
|
||||
case []float32:
|
||||
for n = range data {
|
||||
data[n] = math.Float32frombits(order.Uint32(b.Buf[n<<2:]))
|
||||
}
|
||||
case []float64:
|
||||
for n = range data {
|
||||
data[n] = math.Float64frombits(order.Uint64(b.Buf[n<<3:]))
|
||||
}
|
||||
default:
|
||||
return 0, fmt.Errorf("can't decode to %T", data)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package audio
|
||||
|
||||
// Complex128 represents a slice of 64-bit floating-point linear PCM encoded
|
||||
// audio samples, in the range of -1 to +1.
|
||||
type Complex128 []complex128
|
||||
|
||||
// Len implements the Slice interface.
|
||||
func (p Complex128) Len() int {
|
||||
return len(p)
|
||||
}
|
||||
|
||||
// Cap implements the Slice interface.
|
||||
func (p Complex128) Cap() int {
|
||||
return cap(p)
|
||||
}
|
||||
|
||||
// At implements the Slice interface.
|
||||
func (p Complex128) At(i int) float64 {
|
||||
return real(p[i])
|
||||
}
|
||||
|
||||
// Set implements the Slice interface.
|
||||
func (p Complex128) Set(i int, s float64) {
|
||||
p[i] = complex(s, 0)
|
||||
}
|
||||
|
||||
// Slice implements the Slice interface.
|
||||
func (p Complex128) Slice(low, high int) Slice {
|
||||
return p[low:high]
|
||||
}
|
||||
|
||||
// Make implements the Slice interface.
|
||||
func (p Complex128) Make(length, capacity int) Slice {
|
||||
return make(Float64, length, capacity)
|
||||
}
|
||||
|
||||
// CopyTo implements the Slice interface.
|
||||
func (p Complex128) CopyTo(dst Slice) int {
|
||||
d, ok := dst.(Complex128)
|
||||
if ok {
|
||||
return copy(d, p)
|
||||
}
|
||||
return sliceCopy(dst, p)
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package audio
|
||||
|
||||
// Float32 represents a slice of 32-bit floating-point linear PCM encoded
|
||||
// audio samples, in the range of -1 to +1.
|
||||
type Float32 []float32
|
||||
|
||||
// Len implements the Slice interface.
|
||||
func (p Float32) Len() int {
|
||||
return len(p)
|
||||
}
|
||||
|
||||
// Cap implements the Slice interface.
|
||||
func (p Float32) Cap() int {
|
||||
return cap(p)
|
||||
}
|
||||
|
||||
// At implements the Slice interface.
|
||||
func (p Float32) At(i int) float64 {
|
||||
return float64(p[i])
|
||||
}
|
||||
|
||||
// Set implements the Slice interface.
|
||||
func (p Float32) Set(i int, s float64) {
|
||||
p[i] = float32(s)
|
||||
}
|
||||
|
||||
// Slice implements the Slice interface.
|
||||
func (p Float32) Slice(low, high int) Slice {
|
||||
return p[low:high]
|
||||
}
|
||||
|
||||
// Make implements the Slice interface.
|
||||
func (p Float32) Make(length, capacity int) Slice {
|
||||
return make(Float32, length, capacity)
|
||||
}
|
||||
|
||||
// CopyTo implements the Slice interface.
|
||||
func (p Float32) CopyTo(dst Slice) int {
|
||||
d, ok := dst.(Float32)
|
||||
if ok {
|
||||
return copy(d, p)
|
||||
}
|
||||
return sliceCopy(dst, p)
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package audio
|
||||
|
||||
// Float64 represents a slice of 64-bit floating-point linear PCM encoded
|
||||
// audio samples, in the range of -1 to +1.
|
||||
type Float64 []float64
|
||||
|
||||
// Len implements the Slice interface.
|
||||
func (p Float64) Len() int {
|
||||
return len(p)
|
||||
}
|
||||
|
||||
// Cap implements the Slice interface.
|
||||
func (p Float64) Cap() int {
|
||||
return cap(p)
|
||||
}
|
||||
|
||||
// At implements the Slice interface.
|
||||
func (p Float64) At(i int) float64 {
|
||||
return p[i]
|
||||
}
|
||||
|
||||
// Set implements the Slice interface.
|
||||
func (p Float64) Set(i int, s float64) {
|
||||
p[i] = s
|
||||
}
|
||||
|
||||
// Slice implements the Slice interface.
|
||||
func (p Float64) Slice(low, high int) Slice {
|
||||
return p[low:high]
|
||||
}
|
||||
|
||||
// Make implements the Slice interface.
|
||||
func (p Float64) Make(length, capacity int) Slice {
|
||||
return make(Float64, length, capacity)
|
||||
}
|
||||
|
||||
// CopyTo implements the Slice interface.
|
||||
func (p Float64) CopyTo(dst Slice) int {
|
||||
d, ok := dst.(Float64)
|
||||
if ok {
|
||||
return copy(d, p)
|
||||
}
|
||||
return sliceCopy(dst, p)
|
||||
}
|
||||
|
||||
// ToFloat64 converts src to a Float64 slice.
|
||||
func ToFloat64(src Slice) Float64 {
|
||||
if s, ok := src.(Float64); ok {
|
||||
return s
|
||||
}
|
||||
|
||||
dst := make(Float64, src.Len())
|
||||
for i, l := 0, src.Len(); i < l; i++ {
|
||||
dst[i] = src.At(i)
|
||||
}
|
||||
return dst
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// Int16 represents a signed 16-bit linear PCM encoded audio sample.
|
||||
type Int16 []int16
|
||||
|
||||
// Int16ToFloat64 converts a Int16 encoded audio sample to Float64.
|
||||
func Int16ToFloat64(s int16) float64 {
|
||||
return float64(s) / float64(math.MaxInt16)
|
||||
}
|
||||
|
||||
// Float64ToInt16 converts a Float64 encoded audio sample to Int16.
|
||||
func Float64ToInt16(s float64) int16 {
|
||||
return int16(math.Floor((s * float64(math.MaxInt16)) + 0.5))
|
||||
}
|
||||
|
||||
// Len implements the Slice interface.
|
||||
func (p Int16) Len() int {
|
||||
return len(p)
|
||||
}
|
||||
|
||||
// Cap implements the Slice interface.
|
||||
func (p Int16) Cap() int {
|
||||
return cap(p)
|
||||
}
|
||||
|
||||
// At implements the Slice interface.
|
||||
func (p Int16) At(i int) float64 {
|
||||
return Int16ToFloat64(p[i])
|
||||
}
|
||||
|
||||
// Set implements the Slice interface.
|
||||
func (p Int16) Set(i int, s float64) {
|
||||
p[i] = Float64ToInt16(s)
|
||||
}
|
||||
|
||||
// Slice implements the Slice interface.
|
||||
func (p Int16) Slice(low, high int) Slice {
|
||||
return p[low:high]
|
||||
}
|
||||
|
||||
// Make implements the Slice interface.
|
||||
func (p Int16) Make(length, capacity int) Slice {
|
||||
return make(Int16, length, capacity)
|
||||
}
|
||||
|
||||
// CopyTo implements the Slice interface.
|
||||
func (p Int16) CopyTo(dst Slice) int {
|
||||
if d, ok := dst.(Int16); ok {
|
||||
return copy(d, p)
|
||||
}
|
||||
if d, ok := dst.(Int8); ok {
|
||||
for i, v := range p {
|
||||
d[i] = int8(v >> 8)
|
||||
}
|
||||
return p.Len()
|
||||
}
|
||||
return sliceCopy(dst, p)
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package audio
|
||||
|
||||
import "math"
|
||||
|
||||
// Int8 represents a signed 8-bit linear PCM encoded audio sample.
|
||||
type Int8 []int8
|
||||
|
||||
// Int8ToFloat64 converts a Int8 encoded audio sample to Float64.
|
||||
func Int8ToFloat64(s int8) float64 {
|
||||
return float64(s) / float64(math.MaxInt8)
|
||||
}
|
||||
|
||||
// Float64ToInt8 converts a Float64 encoded audio sample to Int8.
|
||||
func Float64ToInt8(s float64) int8 {
|
||||
return int8(math.Floor((s * float64(math.MaxInt8)) + 0.5))
|
||||
}
|
||||
|
||||
// Len implements the Slice interface.
|
||||
func (p Int8) Len() int {
|
||||
return len(p)
|
||||
}
|
||||
|
||||
// Cap implements the Slice interface.
|
||||
func (p Int8) Cap() int {
|
||||
return cap(p)
|
||||
}
|
||||
|
||||
// At implements the Slice interface.
|
||||
func (p Int8) At(i int) float64 {
|
||||
return Int8ToFloat64(p[i])
|
||||
}
|
||||
|
||||
// Set implements the Slice interface.
|
||||
func (p Int8) Set(i int, s float64) {
|
||||
p[i] = Float64ToInt8(s)
|
||||
}
|
||||
|
||||
// Slice implements the Slice interface.
|
||||
func (p Int8) Slice(low, high int) Slice {
|
||||
return p[low:high]
|
||||
}
|
||||
|
||||
// Make implements the Slice interface.
|
||||
func (p Int8) Make(length, capacity int) Slice {
|
||||
return make(Int8, length, capacity)
|
||||
}
|
||||
|
||||
// CopyTo implements the Slice interface.
|
||||
func (p Int8) CopyTo(dst Slice) int {
|
||||
if d, ok := dst.(Int8); ok {
|
||||
return copy(d, p)
|
||||
}
|
||||
if d, ok := dst.(Int16); ok {
|
||||
for i, v := range p {
|
||||
d[i] = int16(v) * 255
|
||||
}
|
||||
return p.Len()
|
||||
}
|
||||
return sliceCopy(dst, p)
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package audio
|
||||
|
||||
func Deinterleave[T any](dst [][]T, src []T) {
|
||||
if len(src) == 0 {
|
||||
return
|
||||
} else if len(dst) == 1 {
|
||||
copy(dst[0], src)
|
||||
return
|
||||
}
|
||||
|
||||
c := len(dst)
|
||||
for i, s := range src {
|
||||
dst[i%c][i/c] = s
|
||||
}
|
||||
}
|
||||
|
||||
func Interleave[T any](dst []T, src [][]T) {
|
||||
if len(src) == 0 {
|
||||
return
|
||||
} else if len(src) == 1 {
|
||||
copy(dst, src[0])
|
||||
return
|
||||
}
|
||||
|
||||
c := len(src)
|
||||
for i := range dst {
|
||||
dst[i] = src[i%c][i/c]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"go.maze.io/harmon/config"
|
||||
)
|
||||
|
||||
// NotFound signals the player type can not be found.
|
||||
type NotFound struct {
|
||||
Type string
|
||||
}
|
||||
|
||||
func (err NotFound) Error() string {
|
||||
return fmt.Sprintf("audio driver %q can not be found", err.Type)
|
||||
}
|
||||
|
||||
type Opener func(config config.Audio) (Stream, error)
|
||||
|
||||
var (
|
||||
protocols sync.Map
|
||||
)
|
||||
|
||||
func Register(name string, opener Opener) {
|
||||
logrus.WithField("type", name).Debug("register audio driver")
|
||||
if _, loaded := protocols.LoadOrStore(name, opener); loaded {
|
||||
panic(fmt.Sprintf("audio type %q already registered", name))
|
||||
}
|
||||
}
|
||||
|
||||
func New(config config.Audio) (Stream, error) {
|
||||
logrus.WithField("type", config.Type).Debug("load audio driver")
|
||||
|
||||
opener, ok := protocols.Load(config.Type)
|
||||
if ok {
|
||||
return opener.(Opener)(config)
|
||||
}
|
||||
return nil, NotFound{config.Type}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var ErrFormat = errors.New("invalid audio format")
|
||||
|
||||
type Format uint
|
||||
|
||||
// Audio format.
|
||||
const (
|
||||
ByteFormat Format = iota
|
||||
Int8Format
|
||||
Int16LEFormat
|
||||
Int16BEFormat
|
||||
Int32LEFormat
|
||||
Int32BEFormat
|
||||
invalidFormat
|
||||
)
|
||||
|
||||
func (f Format) Order() binary.ByteOrder {
|
||||
switch f {
|
||||
case Int16LEFormat, Int32LEFormat:
|
||||
return binary.LittleEndian
|
||||
case Int16BEFormat, Int32BEFormat:
|
||||
return binary.BigEndian
|
||||
default:
|
||||
return binary.NativeEndian
|
||||
}
|
||||
}
|
||||
|
||||
func (f Format) BytesPerSample() int {
|
||||
switch f {
|
||||
case ByteFormat, Int8Format:
|
||||
return 8
|
||||
case Int16LEFormat, Int16BEFormat:
|
||||
return 16
|
||||
case Int32LEFormat, Int32BEFormat:
|
||||
return 32
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"git.maze.io/go/bragi/internal/resample"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
// Slice is a generic audio slice, it can conceptually be thought of as a
|
||||
// slice of some audio encoding type.
|
||||
//
|
||||
// Conversion between two encoded audio slices is as simple as:
|
||||
//
|
||||
// dst, ok := src.(MuLaw)
|
||||
// if !ok {
|
||||
// // Create a new slice of the target encoding and copy the samples over
|
||||
// // because src is not MuLaw encoded.
|
||||
// dst = make(MuLaw, src.Len())
|
||||
// src.CopyTo(dst)
|
||||
// }
|
||||
type Slice interface {
|
||||
// Len returns the number of elements in the slice.
|
||||
//
|
||||
// Equivalent slice syntax:
|
||||
//
|
||||
// len(b)
|
||||
Len() int
|
||||
|
||||
// Cap returns the number of elements in the slice.
|
||||
//
|
||||
// Equivalent slice syntax:
|
||||
//
|
||||
// cap(b)
|
||||
Cap() int
|
||||
|
||||
// Set sets the specified index in the slice to the specified Float64
|
||||
// encoded audio sample, s.
|
||||
//
|
||||
// If the slice's audio samples are not stored in Float64 encoding, then
|
||||
// the sample should be converted to the slice's internal format and then
|
||||
// stored.
|
||||
//
|
||||
// Just like slices, slice indices must be non-negative; and no greater
|
||||
// than (Len() - 1), or else a panic may occur.
|
||||
//
|
||||
// Equivalent slice syntax:
|
||||
//
|
||||
// b[index] = s
|
||||
// -> b.Set(index, s)
|
||||
//
|
||||
Set(index int, s float64)
|
||||
|
||||
// At returns the Float64 encoded audio sample at the specified index in
|
||||
// the slice.
|
||||
//
|
||||
// If the slice's audio samples are not stored in Float64 encoding, then
|
||||
// the sample should be converted to Float64 encoding, and subsequently
|
||||
// returned.
|
||||
//
|
||||
// Just like slices, slice indices must be non-negative; and no greater
|
||||
// than (Len() - 1), or else a panic may occur.
|
||||
//
|
||||
// Equivalent slice syntax:
|
||||
//
|
||||
// b[index]
|
||||
// -> b.At(index)
|
||||
//
|
||||
At(index int) float64
|
||||
|
||||
// Slice returns a new slice of the slice, using the low and high
|
||||
// parameters.
|
||||
//
|
||||
// Equivalent slice syntax:
|
||||
//
|
||||
// b[low:high]
|
||||
// -> b.Slice(low, high)
|
||||
//
|
||||
// b[2:]
|
||||
// -> b.Slice(2, a.Len())
|
||||
//
|
||||
// b[:3]
|
||||
// -> b.Slice(0, 3)
|
||||
//
|
||||
// b[:]
|
||||
// -> b.Slice(0, a.Len())
|
||||
//
|
||||
Slice(low, high int) Slice
|
||||
|
||||
// Make creates and returns a new slice of this slices type. This allows
|
||||
// allocating a new slice of exactly the same type for lossless copying of
|
||||
// data without knowing about the underlying type.
|
||||
//
|
||||
// It is exactly the same syntax as the make builtin:
|
||||
//
|
||||
// make(MuLaw, len, cap)
|
||||
//
|
||||
// Where cap cannot be less than len.
|
||||
Make(length, capacity int) Slice
|
||||
|
||||
// CopyTo operates exactly like the copy builtin, but this slice is always
|
||||
// the source operand. Equivalent slice syntax:
|
||||
//
|
||||
// copy(dst, src)
|
||||
// -> src.CopyTo(dst)
|
||||
//
|
||||
CopyTo(dst Slice) int
|
||||
}
|
||||
|
||||
// sliceCopy copies copies audio samples from the source slice to the
|
||||
// destination slice. Returns the number of elements copied, which is the
|
||||
// minimum of the dst.Len() and src.Len() values.
|
||||
func sliceCopy(dst, src Slice) int {
|
||||
var i int
|
||||
for i = 0; i < src.Len() && i < dst.Len(); i++ {
|
||||
dst.Set(i, src.At(i))
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// Min returns the minimum value in the Slice.
|
||||
func Min(s Slice) float64 {
|
||||
if s.Len() == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
min := math.MaxFloat64
|
||||
for i, l := 0, s.Len(); i < l; i++ {
|
||||
if v := s.At(i); v < min {
|
||||
min = v
|
||||
}
|
||||
}
|
||||
return min
|
||||
}
|
||||
|
||||
// Max returns the minimum value in the Slice.
|
||||
func Max(s Slice) float64 {
|
||||
if s.Len() == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
max := -math.MaxFloat64
|
||||
for i, l := 0, s.Len(); i < l; i++ {
|
||||
if v := s.At(i); v > max {
|
||||
max = v
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
// Limits returns the minimum and maximum value in the Slice.
|
||||
func Limits(s Slice) (min, max float64) {
|
||||
if s.Len() == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
min = +math.MaxFloat64
|
||||
max = -math.MaxFloat64
|
||||
for i, l := 0, s.Len(); i < l; i++ {
|
||||
v := s.At(i)
|
||||
if v < min {
|
||||
min = v
|
||||
}
|
||||
if v > max {
|
||||
max = v
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Normalize the samples in the buffer.
|
||||
func Normalize(s Slice) {
|
||||
min, max := Limits(s)
|
||||
for i, l := 0, s.Len(); i < l; i++ {
|
||||
val := s.At(i)
|
||||
s.Set(i, 2*((val-min)/(max-min))-1)
|
||||
}
|
||||
}
|
||||
|
||||
// Saturate the samples in the buffer to fit in [-1, 1].
|
||||
func Saturate(s Slice) {
|
||||
for i, l := 0, s.Len(); i < l; i++ {
|
||||
v := s.At(i)
|
||||
if v > 1 {
|
||||
s.Set(i, 1)
|
||||
} else if v < -1 {
|
||||
s.Set(i, -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resample an audio slice.
|
||||
func Resample(dst, src Slice, dstRate, srcRate physic.Frequency, channels, quality int) (read, written int) {
|
||||
d := ToFloat64(dst)
|
||||
s := ToFloat64(src)
|
||||
r := resample.NewWithSkipZeros(channels, int(srcRate/physic.Hertz), int(dstRate/physic.Hertz), quality)
|
||||
read, written = r.ProcessFloat64(0, s, d)
|
||||
d.CopyTo(dst)
|
||||
return
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package audio
|
||||
|
||||
// InterleavedStereoToMono converts interleaved stereo to mono samples.
|
||||
//
|
||||
// The size of src should be twice the size of dst. No bounds checking
|
||||
// is performed while writing to dst.
|
||||
func InterleavedStereoToMono(dst, src Slice) {
|
||||
var (
|
||||
i, j int
|
||||
l = src.Len() / 2
|
||||
)
|
||||
for ; i < l; i, j = i+1, j+2 {
|
||||
dst.Set(i, (src.At(j)+src.At(j+1))/2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"go.maze.io/harmon/config"
|
||||
"go.maze.io/harmon/hardware"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
type Stream interface {
|
||||
hardware.Driver
|
||||
|
||||
// Channels is the number of channels.
|
||||
Channels() int
|
||||
|
||||
// SampleRate is the audio sampling rate.
|
||||
SampleRate() physic.Frequency
|
||||
|
||||
// Samples is a channel of interleaved audio samples.
|
||||
Samples() <-chan []int16
|
||||
}
|
||||
|
||||
type Reader struct {
|
||||
io.Reader
|
||||
|
||||
// Format is the audio sample format.
|
||||
Format Format
|
||||
|
||||
// Ch is the number of channels.
|
||||
Ch int
|
||||
|
||||
// Rate is the sampling rate.
|
||||
Rate physic.Frequency
|
||||
}
|
||||
|
||||
func NewReader(r io.Reader, f Format, ch int, rate physic.Frequency) Stream {
|
||||
return &Reader{
|
||||
Reader: r,
|
||||
Format: f,
|
||||
Ch: ch,
|
||||
Rate: rate,
|
||||
}
|
||||
}
|
||||
|
||||
func (r Reader) Type() string {
|
||||
return "file"
|
||||
}
|
||||
|
||||
func (r Reader) Halt() error {
|
||||
if c, ok := r.Reader.(io.Closer); ok {
|
||||
return c.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Reader) Channels() int {
|
||||
return r.Ch
|
||||
}
|
||||
|
||||
func (r Reader) SampleRate() physic.Frequency {
|
||||
return r.Rate
|
||||
}
|
||||
|
||||
func (r *Reader) Read(b *Buffer) (n int, err error) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
|
||||
l := len(b.Buf)
|
||||
l -= l % (b.Ch * b.Format.BytesPerSample()) // align to samples
|
||||
n, err = r.Reader.Read(b.Buf[:l]) // read
|
||||
n /= (b.Ch * b.Format.BytesPerSample()) // return sample count
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Reader) read(send chan []int16) {
|
||||
const numBuf = 16
|
||||
|
||||
var (
|
||||
b = NewBuffer(int(r.Rate/physic.Hertz), r.Ch, r.Format)
|
||||
order = r.Format.Order()
|
||||
buf [numBuf][]int16
|
||||
n int
|
||||
)
|
||||
for i := range buf {
|
||||
buf[i] = make([]int16, int(r.Rate/physic.Hertz)*r.Ch)
|
||||
}
|
||||
|
||||
for {
|
||||
if _, err := r.Read(b); err != nil {
|
||||
close(send)
|
||||
return
|
||||
}
|
||||
|
||||
samples, _ := b.Decode(buf[n], order)
|
||||
select {
|
||||
case send <- buf[n][:samples]:
|
||||
default:
|
||||
}
|
||||
|
||||
n = (n + 1) % numBuf
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reader) Samples() <-chan []int16 {
|
||||
samples := make(chan []int16)
|
||||
go r.read(samples)
|
||||
return samples
|
||||
}
|
||||
|
||||
// Open a stream backed by a file (or a FIFO).
|
||||
func Open(name string, f Format, ch int, rate physic.Frequency) (Stream, error) {
|
||||
r, err := os.OpenFile(name, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewReader(r, f, ch, rate), nil
|
||||
}
|
||||
|
||||
func openFile(config config.Audio) (Stream, error) {
|
||||
if config.Rate <= 0 {
|
||||
return nil, errors.New("audio rate not configured")
|
||||
}
|
||||
if config.Channels <= 0 {
|
||||
return nil, errors.New("audio chanels not configured")
|
||||
}
|
||||
if config.Bits == 0 {
|
||||
return nil, errors.New("audio bits not configured")
|
||||
}
|
||||
|
||||
var (
|
||||
rate = physic.Frequency(config.Rate) * physic.Hertz
|
||||
f Format
|
||||
)
|
||||
switch config.Bits {
|
||||
case 8:
|
||||
f = Int8Format
|
||||
case 16:
|
||||
f = Int16LEFormat
|
||||
case 32:
|
||||
f = Int32LEFormat
|
||||
default:
|
||||
return nil, fmt.Errorf("audio bits should be 8, 16 or 32, got %d", config.Bits)
|
||||
}
|
||||
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"type": config.Type,
|
||||
"bits": config.Bits,
|
||||
"channels": config.Channels,
|
||||
"rate": rate,
|
||||
}).Debug("open audio driver")
|
||||
return Open(config.Path, f, config.Channels, rate)
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("file", openFile)
|
||||
Register("fifo", openFile)
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package audio
|
||||
|
||||
import "math"
|
||||
|
||||
// Uint8 represents a unsigned 8-bit linear PCM encoded audio sample.
|
||||
type Uint8 []uint8
|
||||
|
||||
// Uint8ToFloat64 converts a Uint8 encoded audio sample to Float64.
|
||||
func Uint8ToFloat64(s uint8) float64 {
|
||||
// In 0 to 1 range
|
||||
f := float64(s) / float64(math.MaxUint8)
|
||||
|
||||
// Switch to -1 to +1 range
|
||||
f *= 2
|
||||
f--
|
||||
return f
|
||||
}
|
||||
|
||||
// Float64ToUint8 converts a Float64 encoded audio sample to Uint8.
|
||||
func Float64ToUint8(s float64) uint8 {
|
||||
// In -1 to +1 range, switch to 0 to 1
|
||||
s++
|
||||
s /= 2
|
||||
return uint8(math.Floor((s * float64(math.MaxUint8)) + 0.5))
|
||||
}
|
||||
|
||||
// Len implements the Slice interface.
|
||||
func (p Uint8) Len() int {
|
||||
return len(p)
|
||||
}
|
||||
|
||||
// Cap implements the Slice interface.
|
||||
func (p Uint8) Cap() int {
|
||||
return cap(p)
|
||||
}
|
||||
|
||||
// At implements the Slice interface.
|
||||
func (p Uint8) At(i int) float64 {
|
||||
return Uint8ToFloat64(p[i])
|
||||
}
|
||||
|
||||
// Set implements the Slice interface.
|
||||
func (p Uint8) Set(i int, s float64) {
|
||||
p[i] = Float64ToUint8(s)
|
||||
}
|
||||
|
||||
// Slice implements the Slice interface.
|
||||
func (p Uint8) Slice(low, high int) Slice {
|
||||
return p[low:high]
|
||||
}
|
||||
|
||||
// Make implements the Slice interface.
|
||||
func (p Uint8) Make(length, capacity int) Slice {
|
||||
return make(Uint8, length, capacity)
|
||||
}
|
||||
|
||||
// CopyTo implements the Slice interface.
|
||||
func (p Uint8) CopyTo(dst Slice) int {
|
||||
d, ok := dst.(Uint8)
|
||||
if ok {
|
||||
return copy(d, p)
|
||||
}
|
||||
return sliceCopy(dst, p)
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
[player]
|
||||
protocol = "mpd"
|
||||
#host = "volumio.local:6600"
|
||||
#password = ""
|
||||
|
||||
[audio]
|
||||
source = "tcp"
|
||||
host = "volumio.local:6601"
|
||||
|
||||
[[page]]
|
||||
screens = ["main_left", "main_right"]
|
||||
|
||||
[visual.vumeter_left]
|
||||
visual = "vumeter"
|
||||
config = {channel = 1, channels = 2}
|
||||
|
||||
[visual.vumeter_right]
|
||||
visual = "vumeter_mirror"
|
||||
config = {channel = 2, channels = 2}
|
||||
|
||||
[visual.peak]
|
||||
visual = "peak"
|
||||
config =
|
||||
|
||||
[display.main]
|
||||
driver = "lcdproc"
|
||||
host = "fly.maze.network"
|
||||
|
||||
[display.test]
|
||||
driver = "sdl"
|
||||
width = 256
|
||||
height = 32
|
||||
|
||||
[display.left]
|
||||
driver = "ssd1306"
|
||||
type = "i2c"
|
||||
width = 128
|
||||
height = 64
|
||||
bus = "" # default bus
|
||||
address = 0x78
|
||||
|
||||
[display.right]
|
||||
driver = "ssd1306"
|
||||
type = "i2c"
|
||||
width = 128
|
||||
height = 64
|
||||
bus = "" # default bus
|
||||
address = 0x7A
|
||||
|
||||
#[display.tft]
|
||||
#driver = "st7739"
|
||||
#type = "spi"
|
||||
#width = 240
|
||||
#height = 240
|
||||
#bus = "" # default bus
|
||||
##dc = "24"
|
||||
##reset = "25"
|
||||
##cs = "8"
|
||||
|
||||
[input.rotary.main]
|
||||
ccw = "volume-down"
|
||||
cw = "volume-up"
|
||||
click = "mute-toggle"
|
||||
@@ -1,46 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"git.maze.io/go/bragi/hardware/display/sdl"
|
||||
"git.maze.io/go/bragi/hardware/input"
|
||||
)
|
||||
|
||||
func main() {
|
||||
d, err := sdl.New()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
inputs, err := input.Detect()
|
||||
if err != nil {
|
||||
log.Fatalln("failed to detect input sources:", err)
|
||||
}
|
||||
log.Printf("detected %d input sources:", len(inputs))
|
||||
for _, input := range inputs {
|
||||
log.Println("input:", input.Name())
|
||||
}
|
||||
|
||||
var wait sync.WaitGroup
|
||||
for _, s := range inputs {
|
||||
wait.Add(1)
|
||||
go func(s input.Source, wait *sync.WaitGroup) {
|
||||
defer wait.Done()
|
||||
|
||||
events, err := s.Events()
|
||||
if err != nil {
|
||||
log.Println("failed to get events from source:", s.Name(), err)
|
||||
return
|
||||
}
|
||||
|
||||
for e := range events {
|
||||
log.Println("event:", e)
|
||||
}
|
||||
}(s, &wait)
|
||||
}
|
||||
|
||||
log.Fatalln(d.Run())
|
||||
wait.Wait()
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"image/color"
|
||||
"sync"
|
||||
|
||||
"git.maze.io/go/bragi/hardware/display/gc9a01"
|
||||
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||
"periph.io/x/conn/v3/spi/spireg"
|
||||
"periph.io/x/host/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
config gc9a01.Config
|
||||
reset string
|
||||
dc string
|
||||
cs string
|
||||
bl string
|
||||
)
|
||||
flag.StringVar(&config.Port, "spi-bus", "", "SPI bus (empty for default)")
|
||||
flag.StringVar(&reset, "gpio-reset", "GPIO6", "reset pin")
|
||||
flag.StringVar(&dc, "gpio-dc", "GPIO7", "data/command pin")
|
||||
flag.StringVar(&cs, "gpio-cs", "GPIO8", "chip select pin")
|
||||
flag.StringVar(&bl, "gpio-bl", "GPIO9", "backlight pin")
|
||||
flag.IntVar(&config.Width, "width", 240, "display width")
|
||||
flag.IntVar(&config.Height, "height", 240, "display height")
|
||||
flag.IntVar(&config.VSyncLines, "vsync", 2, "number of VSync lines")
|
||||
flag.IntVar(&config.RowOffset, "row-offset", 0, "row offset")
|
||||
flag.IntVar(&config.ColumnOffset, "column-offset", 0, "column offset")
|
||||
flag.Parse()
|
||||
|
||||
config.Reset = gpioreg.ByName(reset)
|
||||
config.DC = gpioreg.ByName(dc)
|
||||
config.CS = gpioreg.ByName(cs)
|
||||
config.BL = gpioreg.ByName(bl)
|
||||
|
||||
_, err := host.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
p, err := spireg.Open(config.Port)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
d, err := gc9a01.New(p, config)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
bounds := d.Bounds()
|
||||
width, height := bounds.Dx(), bounds.Dy()
|
||||
|
||||
white := color.RGBA{255, 255, 255, 255}
|
||||
red := color.RGBA{255, 0, 0, 255}
|
||||
blue := color.RGBA{0, 0, 255, 255}
|
||||
green := color.RGBA{0, 255, 0, 255}
|
||||
black := color.RGBA{0, 0, 0, 255}
|
||||
|
||||
d.FillRectangle(0, 0, width, height, black)
|
||||
d.FillRectangle(0, 0, width/2, height/2, white)
|
||||
d.FillRectangle(width/2, 0, width/2, height/2, red)
|
||||
d.FillRectangle(0, height/2, width/2, height/2, green)
|
||||
d.FillRectangle(width/2, height/2, width/2, height/2, blue)
|
||||
d.FillRectangle(width/4, height/4, width/2, height/2, black)
|
||||
|
||||
var wait sync.WaitGroup
|
||||
wait.Add(1)
|
||||
wait.Wait()
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"git.maze.io/go/bragi/hardware/input"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logrus.SetLevel(logrus.TraceLevel)
|
||||
|
||||
sources, err := input.Detect()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var wait sync.WaitGroup
|
||||
for _, s := range sources {
|
||||
wait.Add(1)
|
||||
go test(s, &wait)
|
||||
}
|
||||
wait.Wait()
|
||||
}
|
||||
|
||||
func test(s input.Source, wait *sync.WaitGroup) {
|
||||
defer wait.Done()
|
||||
|
||||
events, err := s.Events()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
for e := range events {
|
||||
fmt.Println(e)
|
||||
switch e.Type {
|
||||
case input.RotaryClockwise:
|
||||
println("clockwise")
|
||||
case input.RotaryCounterClockwise:
|
||||
println("counter clockwise")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
package main
|
||||
@@ -1,36 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
bragi "git.maze.io/go/bragi"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
|
||||
s := bragi.NewMPD("volumio.local:6600")
|
||||
log := logrus.WithField("source", s.Name())
|
||||
log.Info("created source")
|
||||
for e := range s.Events() {
|
||||
switch e := e.(type) {
|
||||
case *bragi.ConnectedEvent:
|
||||
log.Info("connected")
|
||||
|
||||
case *bragi.DisconnectedEvent:
|
||||
log.Info("disconnected")
|
||||
|
||||
case *bragi.StatusEvent:
|
||||
t := e.Status.Track
|
||||
if t != nil {
|
||||
logrus.
|
||||
WithField("track", t).
|
||||
WithField("file", t.Path).
|
||||
Info("received track")
|
||||
}
|
||||
|
||||
default:
|
||||
log.WithField("event", e).Info("received event")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/kyoh86/xdg"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
configFileBase = "harmon.conf"
|
||||
configFileBaseAlt = "harmon.cfg"
|
||||
)
|
||||
|
||||
func findConfigFile() string {
|
||||
var name string
|
||||
for _, dir := range append(xdg.AllConfigDirs(), ".") {
|
||||
// Base
|
||||
name = filepath.Join(dir, configFileBase)
|
||||
logrus.WithField("name", name).Trace("auto detecting configuration file")
|
||||
if i, err := os.Stat(name); err == nil && !i.IsDir() {
|
||||
logrus.WithField("name", name).Trace("found configuration file")
|
||||
return name
|
||||
}
|
||||
|
||||
// Alt
|
||||
name = filepath.Join(dir, configFileBaseAlt)
|
||||
logrus.WithField("name", name).Trace("auto detecting configuration file")
|
||||
if i, err := os.Stat(name); err == nil && !i.IsDir() {
|
||||
logrus.WithField("name", name).Trace("found configuration file")
|
||||
return name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,179 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"context"
|
||||
"flag"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"runtime"
|
||||
|
||||
"github.com/adrg/xdg"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"periph.io/x/host/v3"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
_ "git.maze.io/go/harmon/display/all" // Load all display drivers
|
||||
)
|
||||
"go.maze.io/harmon"
|
||||
"go.maze.io/harmon/config"
|
||||
|
||||
var (
|
||||
configurationPath = append(makeConfigurationPath(), ".")
|
||||
configurationFile string
|
||||
configuration *config.Structure
|
||||
logFile string
|
||||
logDebug bool
|
||||
logTrace bool
|
||||
_ "go.maze.io/harmon/hardware/display/all" // Display drivers
|
||||
_ "go.maze.io/harmon/player/all" // Player drivers
|
||||
)
|
||||
|
||||
func main() {
|
||||
var entrypoint = &cobra.Command{
|
||||
Use: "harmon",
|
||||
Short: "Harmon is a music player frontend for graphic displays",
|
||||
Args: entrypointArgs,
|
||||
Run: entrypoint,
|
||||
}
|
||||
configFlag := flag.String("config", "", "configuration file path (default: auto detect)")
|
||||
debugFlag := flag.Bool("debug", false, "enable debug log messages")
|
||||
traceFlag := flag.Bool("trace", false, "enable trace log messages (very noisy!)")
|
||||
flag.Parse()
|
||||
|
||||
flag := entrypoint.PersistentFlags()
|
||||
flag.StringVarP(&configurationFile, "config", "c", "", "configuration file (default is look in "+strings.Join(configurationPath, ",")+")")
|
||||
flag.BoolVarP(&logDebug, "debug", "D", false, "enable debug log messages")
|
||||
flag.BoolVarP(&logTrace, "trace", "T", false, "enable trace log messages")
|
||||
flag.StringVarP(&logFile, "log", "l", "", "log file (default: use standard output)")
|
||||
entrypoint.MarkFlagRequired("config")
|
||||
|
||||
if err := entrypoint.Execute(); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func fatal(err error) {
|
||||
fmt.Fprintf(os.Stderr, "Fatal error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func setup() {
|
||||
viper.SetConfigFile("harmon.conf")
|
||||
viper.AddConfigPath(".")
|
||||
viper.SetConfigName(".harmon")
|
||||
viper.SetDefault("license", "MIT")
|
||||
}
|
||||
|
||||
func makeConfigurationPath() []string {
|
||||
dirs := make([]string, len(xdg.ConfigDirs))
|
||||
for i, dir := range xdg.ConfigDirs {
|
||||
dirs[i] = filepath.Join(dir, "harmon")
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
func entrypointArgs(cmd *cobra.Command, args []string) (err error) {
|
||||
// Setup logger
|
||||
if logFile != "" {
|
||||
logrus.WithField("path", logFile).Info("logging to file")
|
||||
var w io.Writer
|
||||
if w, err = os.OpenFile(logFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0640); err != nil {
|
||||
return
|
||||
}
|
||||
logrus.SetOutput(w)
|
||||
}
|
||||
if logTrace {
|
||||
if *traceFlag {
|
||||
logrus.SetLevel(logrus.TraceLevel)
|
||||
} else if logDebug {
|
||||
} else if *debugFlag {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
}
|
||||
|
||||
// Load configuration
|
||||
if configurationFile == "" {
|
||||
for _, dir := range configurationPath {
|
||||
if dir, err = filepath.Abs(dir); err != nil {
|
||||
return
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"version": harmon.Version,
|
||||
"host_os": runtime.GOOS,
|
||||
"host_arch": runtime.GOARCH,
|
||||
}).Info("Harmon starting")
|
||||
|
||||
if *configFlag == "" {
|
||||
if *configFlag = findConfigFile(); *configFlag == "" {
|
||||
logrus.Fatal("could not auto detect configuration file; supply one with -config")
|
||||
}
|
||||
logrus.WithField("path", dir).Trace("looking for harmon.conf")
|
||||
if i, ferr := os.Stat(filepath.Join(dir, "harmon.conf")); ferr == nil && !i.IsDir() {
|
||||
if configurationFile, err = filepath.Abs(i.Name()); err != nil {
|
||||
return
|
||||
}
|
||||
logrus.WithField("path", configurationFile).Trace("using for harmon.conf")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if configuration, err = config.Load(configurationFile); err != nil {
|
||||
if config.ExplainError(configurationFile, err) {
|
||||
return errors.New("configuration failed")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func entrypoint(cmd *cobra.Command, args []string) {
|
||||
if len(configuration.Display) == 0 {
|
||||
logrus.Fatal("no displays configured")
|
||||
config, err := config.Load(*configFlag)
|
||||
if err != nil {
|
||||
logrus.WithError(err).Fatal("configuration file contains errors")
|
||||
}
|
||||
|
||||
var (
|
||||
displays = make(map[string]display.Display)
|
||||
err error
|
||||
)
|
||||
|
||||
teardown := func() {
|
||||
for _, d := range displays {
|
||||
logrus.WithField("display", d.String()).Debug("halting...")
|
||||
if d != nil {
|
||||
_ = d.Halt()
|
||||
}
|
||||
}
|
||||
}
|
||||
defer teardown()
|
||||
|
||||
// Configure host
|
||||
if _, err = host.Init(); err != nil {
|
||||
controller, err := harmon.NewController(config)
|
||||
if err != nil {
|
||||
logrus.WithError(err).Fatal("host setup failed")
|
||||
}
|
||||
|
||||
// Configure displays
|
||||
for _, config := range configuration.Display {
|
||||
var (
|
||||
log = logrus.WithFields(logrus.Fields{
|
||||
"name": config.Name,
|
||||
"type": config.Type,
|
||||
})
|
||||
output display.Display
|
||||
)
|
||||
log.Info("setting up display")
|
||||
if output, err = display.New(config); err != nil {
|
||||
log.WithError(err).Fatal("display setup failed")
|
||||
}
|
||||
|
||||
if err = display.DrawImageFile(output, "harmon-color.png"); err != nil {
|
||||
logrus.
|
||||
WithField("display", config.Name).
|
||||
WithError(err).
|
||||
Fatal("display splash failed")
|
||||
}
|
||||
if err = output.Refresh(); err != nil {
|
||||
logrus.
|
||||
WithField("display", config.Name).
|
||||
WithError(err).
|
||||
Fatal("display refresh failed")
|
||||
}
|
||||
|
||||
displays[config.Name] = output
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
signals := make(chan os.Signal)
|
||||
signal.Notify(signals, os.Interrupt)
|
||||
signal.Notify(signals, os.Kill)
|
||||
go func(signals <-chan os.Signal, cancel func()) {
|
||||
defer cancel()
|
||||
signal := <-signals
|
||||
logrus.WithField("signal", signal).Warn("terminating by signal")
|
||||
}(signals, cancel)
|
||||
|
||||
fmt.Println("idling...")
|
||||
for {
|
||||
s := <-signals
|
||||
logrus.WithField("signal", s.String()).Info("terminating")
|
||||
return
|
||||
if err = controller.Run(ctx); err != nil && err != context.Canceled {
|
||||
logrus.WithError(err).Fatal("terminating by fatal error")
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// Copyright 2018 The Periph Authors. All rights reserved.
|
||||
// Use of this source code is governed under the Apache License, Version 2.0
|
||||
// that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"image"
|
||||
"log"
|
||||
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/basicfont"
|
||||
"golang.org/x/image/math/fixed"
|
||||
"periph.io/x/conn/v3/i2c/i2creg"
|
||||
"periph.io/x/devices/v3/ssd1306"
|
||||
"periph.io/x/devices/v3/ssd1306/image1bit"
|
||||
"periph.io/x/host/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Make sure periph is initialized.
|
||||
if _, err := host.Init(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Use i2creg I²C bus registry to find the first available I²C bus.
|
||||
b, err := i2creg.Open("")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer b.Close()
|
||||
|
||||
dev, err := ssd1306.NewI2C(b, &ssd1306.DefaultOpts)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to initialize ssd1306: %v", err)
|
||||
}
|
||||
|
||||
img := image1bit.NewVerticalLSB(dev.Bounds())
|
||||
f := basicfont.Face7x13
|
||||
drawer := font.Drawer{
|
||||
Dst: img,
|
||||
Src: &image.Uniform{image1bit.On},
|
||||
Face: f,
|
||||
Dot: fixed.P(0, img.Bounds().Dy()-1-f.Descent),
|
||||
}
|
||||
drawer.DrawString("Hello from periph!")
|
||||
if err := dev.Draw(dev.Bounds(), img, image.Point{}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// Copyright 2018 The Periph Authors. All rights reserved.
|
||||
// Use of this source code is governed under the Apache License, Version 2.0
|
||||
// that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"image"
|
||||
"log"
|
||||
|
||||
"git.maze.io/go/harmon/display/ssd1326"
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/basicfont"
|
||||
"golang.org/x/image/math/fixed"
|
||||
"periph.io/x/conn/v3/i2c/i2creg"
|
||||
"periph.io/x/devices/v3/ssd1306/image1bit"
|
||||
"periph.io/x/host/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Make sure periph is initialized.
|
||||
if _, err := host.Init(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Use i2creg I²C bus registry to find the first available I²C bus.
|
||||
b, err := i2creg.Open("")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer b.Close()
|
||||
|
||||
/*
|
||||
dev, err := ssd1322.NewI2C(b, &ssd1322.DefaultOpts)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to initialize ssd1322: %v", err)
|
||||
}
|
||||
*/
|
||||
|
||||
dev, err := ssd1326.NewI2C(b, 0x3C)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
//img := image1bit.NewVerticalLSB(dev.Bounds())
|
||||
f := basicfont.Face7x13
|
||||
drawer := font.Drawer{
|
||||
Dst: dev,
|
||||
Src: &image.Uniform{image1bit.On},
|
||||
Face: f,
|
||||
Dot: fixed.P(0, dev.Bounds().Dy()-1-f.Descent),
|
||||
}
|
||||
drawer.DrawString("Hello from periph!")
|
||||
if err := dev.Refresh(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"flag"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"os"
|
||||
|
||||
"git.maze.io/go/bragi/audio"
|
||||
"git.maze.io/go/bragi/display"
|
||||
"git.maze.io/go/bragi/hardware/display/console"
|
||||
audioinput "git.maze.io/go/bragi/hardware/input/audio"
|
||||
"git.maze.io/go/bragi/internal/pixel"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fifoFlag := flag.String("fifo", "", "PCM16 audio FIFO stream")
|
||||
tcpFlag := flag.String("tcp", "locaclhost:6601", "PCM16 audio stream")
|
||||
beFlag := flag.Bool("be", false, "PCM16 data is big endian (default: use little endian)")
|
||||
channelsFlag := flag.Int("channels", 2, "audio channels")
|
||||
sampleRateFlag := flag.Int("samplerate", 44100, "audio sample rate")
|
||||
flag.Parse()
|
||||
|
||||
var (
|
||||
byteOrder binary.ByteOrder = binary.LittleEndian
|
||||
sampleRate = physic.Frequency(*sampleRateFlag) * physic.Hertz
|
||||
d display.Image
|
||||
s audioinput.Reader
|
||||
err error
|
||||
)
|
||||
if *beFlag {
|
||||
byteOrder = binary.BigEndian
|
||||
}
|
||||
if *fifoFlag != "" {
|
||||
s, err = audioinput.OpenPCM16(*fifoFlag, byteOrder, *channelsFlag, sampleRate)
|
||||
} else {
|
||||
s, err = audioinput.OpenPCM16TCP(*tcpFlag, byteOrder, *channelsFlag, sampleRate)
|
||||
}
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
defer s.Halt()
|
||||
|
||||
if d, err = console.New(nil); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
defer d.Halt()
|
||||
|
||||
var (
|
||||
rate = 10
|
||||
//img = image.NewGray(image.Rect(0, 0, 128, 60))
|
||||
//visual = audioinput.NewPeak(40, *channelsFlag, rate)
|
||||
visual = audioinput.NewVUMeter(40, 1, *channelsFlag)
|
||||
samples = make(audio.Int16, (*sampleRateFlag**channelsFlag)/rate)
|
||||
)
|
||||
for {
|
||||
if _, err = s.ReadSamples(samples); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
visual.Process(samples)
|
||||
visual.Render(d, image.Point{}, color.White)
|
||||
if err = d.Refresh(); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
//displayText(img)
|
||||
}
|
||||
}
|
||||
|
||||
func fatal(err error) {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func displayText(img image.Image) {
|
||||
fmt.Print("\x1b[2J") // clear screen
|
||||
size := img.Bounds().Size()
|
||||
for y := 0; y < size.Y; y++ {
|
||||
for x := 0; x < size.X; x++ {
|
||||
if pixel.IsOn(img.At(x, y)) {
|
||||
fmt.Print("#")
|
||||
} else {
|
||||
fmt.Print(" ")
|
||||
}
|
||||
}
|
||||
fmt.Print("\n")
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
)
|
||||
|
||||
func main() {
|
||||
configFlag := flag.String("config", "bragi.toml", "config file")
|
||||
flag.Parse()
|
||||
|
||||
// Load the configuration file.
|
||||
cfg, err := config.Load(*configFlag)
|
||||
if err != nil {
|
||||
if config.ExplainError(*configFlag, err) {
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Fatalln("failed to load configuration:", err)
|
||||
}
|
||||
|
||||
fmt.Printf("configured player:\n")
|
||||
fmt.Printf(" %s@%s\n", cfg.Player.Type, cfg.Player.Host)
|
||||
|
||||
fmt.Printf("configured %d display(s):\n", len(cfg.Display))
|
||||
for _, display := range cfg.Display {
|
||||
fmt.Printf(" %s:\n", display.Name)
|
||||
fmt.Printf(" %s %dx%d\n", display.Type, display.Size[0], display.Size[1])
|
||||
}
|
||||
|
||||
fmt.Printf("configured %d input(s):\n", len(cfg.Input))
|
||||
/*
|
||||
if cfg.Input != nil {
|
||||
fmt.Printf("configured inputs:\n")
|
||||
if cfg.Input.Rotary != nil {
|
||||
fmt.Printf(" rotary encoders:\n")
|
||||
for name, _ := range cfg.Input.Rotary {
|
||||
fmt.Printf(" - %s\n", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"git.maze.io/go/harmon/config"
|
||||
"git.maze.io/go/harmon/display"
|
||||
_ "git.maze.io/go/harmon/display/all" // Load all drivers
|
||||
)
|
||||
|
||||
func main() {
|
||||
var cfg config.Display
|
||||
cfg.Bus = new(string)
|
||||
flag.StringVar(&cfg.Name, "name", "", "name")
|
||||
flag.StringVar(&cfg.Type, "type", "test", "driver type, use 'help' to get a list of available drivers")
|
||||
flag.StringVar(cfg.Bus, "bus", "", "bus is the I²C or SPI bus")
|
||||
flag.StringVar(&cfg.Host, "host", "", "driver host address")
|
||||
flag.StringVar(&cfg.Port, "port", "", "driver port number or name")
|
||||
debugFlag := flag.Bool("debug", false, "enable debug messages")
|
||||
traceFlag := flag.Bool("trace", false, "enable trace messages")
|
||||
flag.Parse()
|
||||
|
||||
if *traceFlag {
|
||||
logrus.SetLevel(logrus.TraceLevel)
|
||||
} else if *debugFlag {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
}
|
||||
|
||||
if cfg.Type == "" || cfg.Type == "help" || cfg.Type == "list" {
|
||||
fmt.Println("available drivers:")
|
||||
for _, driver := range display.List() {
|
||||
fmt.Println(" -", driver)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
d, err := display.New(&cfg)
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = d.Halt()
|
||||
}()
|
||||
|
||||
if err = testDisplay(d); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
|
||||
var wait sync.WaitGroup
|
||||
wait.Add(1)
|
||||
wait.Wait()
|
||||
}
|
||||
|
||||
func fatal(err error) {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
/*
|
||||
func testTextDisplay(d display.Text) (err error) {
|
||||
d.Text(0, 0, "hello, world! this is Braghi")
|
||||
for y := 1; y < d.Rows(); y++ {
|
||||
d.Text(0, y, fmt.Sprintf("extra row %d", y))
|
||||
}
|
||||
return
|
||||
}
|
||||
*/
|
||||
|
||||
func testDisplay(d display.Display) (err error) {
|
||||
return
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
|
||||
"git.maze.io/go/bragi/player/mpd"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addrFlag := flag.String("addr", mpd.DefaultAddr, "mpd server address")
|
||||
passwordFlag := flag.String("password", "", "mpd password")
|
||||
debugFlag := flag.Bool("debug", false, "enable debug logging")
|
||||
traceFlag := flag.Bool("trace", false, "enable trace logging")
|
||||
flag.Parse()
|
||||
|
||||
if *traceFlag {
|
||||
logrus.SetLevel(logrus.TraceLevel)
|
||||
} else if *debugFlag {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
}
|
||||
|
||||
c, err := mpd.New(*addrFlag, *passwordFlag, "test")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
//log.Fatalln(c.Close())
|
||||
events, err := c.Events()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
for event := range events {
|
||||
log.Println(event)
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,32 @@
|
||||
// Package config contains the configuration structure and parser.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||
)
|
||||
|
||||
/*
|
||||
// Load the configuration file.
|
||||
func Load(name string) (*Configuration, error) {
|
||||
var (
|
||||
cfg Configuration
|
||||
md, err = toml.DecodeFile(name, &cfg)
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if u := md.Undecoded(); len(u) > 0 {
|
||||
return nil, fmt.Errorf("bragi: unknown configuration keys: %v", u)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
*/
|
||||
|
||||
// Structure holds the configuration settings for the application.
|
||||
type Structure struct {
|
||||
Audio *Audio `hcl:"audio,block"`
|
||||
Player *Player `hcl:"player,block"`
|
||||
Page []*Page `hcl:"page,block"`
|
||||
Display []*Display `hcl:"display,block"`
|
||||
Input []*Input `hcl:"input,block"`
|
||||
Visual []*Visual `hcl:"visual,block"`
|
||||
// Config structure.
|
||||
type Config struct {
|
||||
Display Display `hcl:"display,block"`
|
||||
Input Input `hcl:"input,block"`
|
||||
Audio Audio `hcl:"audio,block"`
|
||||
Player Player `hcl:"player,block"`
|
||||
}
|
||||
|
||||
// Audio stream configuration.
|
||||
type Audio struct {
|
||||
Type string `hcl:"type"`
|
||||
Host *string `hcl:"host"`
|
||||
Path *string `hcl:"path"`
|
||||
}
|
||||
|
||||
// Player configuration for the music player.
|
||||
type Player struct {
|
||||
Type string `hcl:"type"`
|
||||
Host *string `hcl:"host"`
|
||||
Password *string `hcl:"password"`
|
||||
}
|
||||
|
||||
// Page configuration.
|
||||
type Page struct {
|
||||
Name string `hcl:"name,label"`
|
||||
Visual []string `hcl:"visual"`
|
||||
Action *PageAction `hcl:"action,block"`
|
||||
}
|
||||
|
||||
type PageAction struct {
|
||||
RotaryCW *string `hcl:"rotary_cw"`
|
||||
RotaryCCW *string `hcl:"rotary_ccw"`
|
||||
RotaryClick *string `hcl:"rotary_click"`
|
||||
RotaryHold *string `hcl:"rotary_hold"`
|
||||
}
|
||||
|
||||
// Display configuration for the display(s).
|
||||
// Display configuration for OLED and TFT screens.
|
||||
type Display struct {
|
||||
Name string `hcl:"name,label"`
|
||||
FPS int `hcl:"fps,optional"`
|
||||
Left DisplayConfig `hcl:"left,block"`
|
||||
Right DisplayConfig `hcl:"right,block"`
|
||||
Color DisplayConfig `hcl:"color,block"`
|
||||
}
|
||||
|
||||
// DisplayConfig is the configuration for one display.
|
||||
type DisplayConfig struct {
|
||||
Name string
|
||||
|
||||
// Type of display.
|
||||
Type string `hcl:"type"`
|
||||
|
||||
// Mode of operation; i2c or spi (defaults to i2c).
|
||||
Mode string `hcl:"mode,optional"`
|
||||
|
||||
// Size of the display in pixels.
|
||||
Size string `hcl:"size"`
|
||||
|
||||
@@ -101,60 +59,41 @@ type Display struct {
|
||||
|
||||
// Rotate the screen.
|
||||
Rotate string `hcl:"rotate,optional"`
|
||||
|
||||
// Flip the screen vertically (if supported by hardware).
|
||||
Flip bool `hcl:"flip,optional"`
|
||||
|
||||
// Mirror the screen horizontally (if supported by hardware).
|
||||
Mirror bool `hcl:"flip,optional"`
|
||||
}
|
||||
|
||||
// Input configuration for the input devices.
|
||||
// Input peripherals.
|
||||
type Input struct {
|
||||
Name string `hcl:"name,label"`
|
||||
Encoder Encoder `hcl:"encoder,block"`
|
||||
}
|
||||
|
||||
// Encoder is a rotary encoder.
|
||||
type Encoder struct {
|
||||
Type string `hcl:"type"`
|
||||
|
||||
CW string `hcl:"cw,optional"`
|
||||
CCW string `hcl:"ccw,optional"`
|
||||
Switch string `hcl:"sw,optional"`
|
||||
}
|
||||
|
||||
// InputRotary configuration for a rotary encoder.
|
||||
type InputRotary struct {
|
||||
// Name of the rotary encoder.
|
||||
Name string `hcl:"name,label"`
|
||||
|
||||
// ID is the device identifier, if left empty the device is the first rotary found.
|
||||
ID *string `hcl:"id,omitempty"`
|
||||
|
||||
// CCW is the counter-clockwise action.
|
||||
CCW string `hcl:"ccw"`
|
||||
|
||||
// CW is the clockwise action.
|
||||
CW string `hcl:"cw"`
|
||||
|
||||
// Click is the switch action.
|
||||
Click string `hcl:"click"`
|
||||
}
|
||||
|
||||
// Visual configuration.
|
||||
type Visual struct {
|
||||
Name string `hcl:"name,label"`
|
||||
// Audio source provides PCM samples.
|
||||
type Audio struct {
|
||||
Type string `hcl:"type"`
|
||||
Config map[string]string `hcl:"config,optional"`
|
||||
Path string `hcl:"path,optional"`
|
||||
Host string `hcl:"host,optional"`
|
||||
Rate float64 `hcl:"rate,optional"`
|
||||
Channels int `hcl:"channels,optional"`
|
||||
Bits int `hcl:"bits,optional"`
|
||||
}
|
||||
|
||||
// BusType is the bus type (i2c or spi).
|
||||
type BusType string
|
||||
|
||||
func (t *BusType) UnmarshalText(text []byte) error {
|
||||
switch string(text) {
|
||||
case "i2c", "spi":
|
||||
*t = BusType(string(text))
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("bragi: invalid bus type %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
// PinOut is the GPIO output pin.
|
||||
type PinOut struct {
|
||||
Pin gpio.PinOut
|
||||
}
|
||||
|
||||
func (c *PinOut) UnmarshalText(text []byte) error {
|
||||
if c.Pin = gpioreg.ByName(string(text)); c.Pin == nil {
|
||||
return fmt.Errorf("bragi: invalid GPIO pin %q", text)
|
||||
}
|
||||
return nil
|
||||
// Player controls the audio.
|
||||
type Player struct {
|
||||
Type string `hcl:"type"`
|
||||
Host string `hcl:"host,optional"`
|
||||
Password string `hcl:"password,optional"`
|
||||
}
|
||||
@@ -3,33 +3,16 @@ package config
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/hashicorp/hcl/v2"
|
||||
"github.com/hashicorp/hcl/v2/gohcl"
|
||||
"github.com/hashicorp/hcl/v2/hclsyntax"
|
||||
"github.com/hashicorp/hcl/v2/json"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/zclconf/go-cty/cty"
|
||||
"github.com/zclconf/go-cty/cty/function"
|
||||
)
|
||||
|
||||
var evalContext = &hcl.EvalContext{
|
||||
Functions: map[string]function.Function{
|
||||
"hex": hexFunc,
|
||||
"bounds": boundsFunc,
|
||||
"rotary": rotaryFunc,
|
||||
"volume": volumeFunc,
|
||||
//"volume": volumeFunc,
|
||||
//"goto": gotoFunc,
|
||||
},
|
||||
}
|
||||
|
||||
// Load the configuration file.
|
||||
func Load(name string) (*Structure, error) {
|
||||
func Load(name string) (*Config, error) {
|
||||
log := logrus.WithField("path", name)
|
||||
log.Debug("loading configuration")
|
||||
|
||||
@@ -39,46 +22,14 @@ func Load(name string) (*Structure, error) {
|
||||
}
|
||||
|
||||
var (
|
||||
config = new(Structure)
|
||||
config = new(Config)
|
||||
ctx *hcl.EvalContext
|
||||
file *hcl.File
|
||||
meta toml.MetaData
|
||||
diag hcl.Diagnostics
|
||||
)
|
||||
|
||||
switch ext := strings.ToLower(filepath.Ext(name)); ext {
|
||||
case ".json":
|
||||
log.Trace("parsing as JSON")
|
||||
file, diag = json.Parse(source, name)
|
||||
|
||||
case ".hcl", ".cfg", ".conf":
|
||||
log.Trace("parsing as HCL")
|
||||
start := hcl.Pos{Line: 1, Column: 1}
|
||||
file, diag = hclsyntax.ParseConfig(source, name, start)
|
||||
|
||||
case ".toml":
|
||||
log.Trace("parsing as TOML")
|
||||
if meta, err = toml.Decode(string(source), config); err != nil {
|
||||
return nil, err
|
||||
} else if undecoded := meta.Undecoded(); len(undecoded) > 0 {
|
||||
diag = diag.Append(&hcl.Diagnostic{
|
||||
Severity: hcl.DiagError,
|
||||
Summary: "Undecoded contents",
|
||||
Detail: fmt.Sprintf("Cannot read from %s: undecoded items in configuration: %v.", name, undecoded),
|
||||
})
|
||||
return nil, diag
|
||||
}
|
||||
|
||||
default:
|
||||
diag = diag.Append(&hcl.Diagnostic{
|
||||
Severity: hcl.DiagError,
|
||||
Summary: "Unsupported file format",
|
||||
Detail: fmt.Sprintf("Cannot read from %s: unrecognized file format suffix %q.", name, ext),
|
||||
})
|
||||
return nil, diag
|
||||
}
|
||||
|
||||
if diag.HasErrors() {
|
||||
if file, diag = hclsyntax.ParseConfig(source, name, start); diag.HasErrors() {
|
||||
return nil, diag
|
||||
}
|
||||
|
||||
@@ -130,59 +81,3 @@ func explainSubject(diag *hcl.Diagnostic) bool {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
hexFunc = function.New(&function.Spec{
|
||||
Params: []function.Parameter{{
|
||||
Name: "number",
|
||||
Type: cty.String,
|
||||
}},
|
||||
Type: function.StaticReturnType(cty.String),
|
||||
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
|
||||
v := args[0].AsString()
|
||||
if strings.HasPrefix(strings.ToLower(v), "0x") {
|
||||
v = v[2:]
|
||||
}
|
||||
i, err := strconv.ParseUint(v, 16, 64)
|
||||
if err != nil {
|
||||
return cty.NumberUIntVal(0), err
|
||||
}
|
||||
return cty.NumberUIntVal(i), nil
|
||||
},
|
||||
})
|
||||
|
||||
rotaryFunc = function.New(&function.Spec{
|
||||
Params: []function.Parameter{{
|
||||
Name: "action",
|
||||
Type: cty.String,
|
||||
}},
|
||||
Type: function.StaticReturnType(cty.String),
|
||||
})
|
||||
|
||||
boundsFunc = function.New(&function.Spec{
|
||||
Params: []function.Parameter{{
|
||||
Name: "width",
|
||||
Type: cty.Number,
|
||||
}, {
|
||||
Name: "height",
|
||||
Type: cty.Number,
|
||||
}},
|
||||
Type: function.StaticReturnType(cty.String),
|
||||
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
|
||||
w := args[0].AsString()
|
||||
h := args[1].AsString()
|
||||
return cty.StringVal(w + "x" + h), nil
|
||||
},
|
||||
})
|
||||
|
||||
volumeFunc = function.New(&function.Spec{
|
||||
Params: []function.Parameter{{
|
||||
Name: "level",
|
||||
Type: cty.Number,
|
||||
}},
|
||||
Type: function.StaticReturnType(cty.String),
|
||||
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
|
||||
return cty.StringVal("volume:" + args[0].AsString()), nil
|
||||
},
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,214 @@
|
||||
package harmon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/host/v3"
|
||||
|
||||
"go.maze.io/harmon/audio"
|
||||
"go.maze.io/harmon/config"
|
||||
"go.maze.io/harmon/hardware"
|
||||
"go.maze.io/harmon/hardware/display"
|
||||
"go.maze.io/harmon/internal/pixel"
|
||||
"go.maze.io/harmon/player"
|
||||
"go.maze.io/harmon/visual"
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
// Left, right and color displays.
|
||||
Left hardware.Display
|
||||
Right hardware.Display
|
||||
Color hardware.Display
|
||||
|
||||
// Player.
|
||||
Player player.Player
|
||||
|
||||
// Audio source.
|
||||
Audio audio.Stream
|
||||
|
||||
// Stream of audio samples.
|
||||
Stream audio.Stream
|
||||
|
||||
// Visual effects.
|
||||
visual struct {
|
||||
offline *visual.Offline
|
||||
}
|
||||
|
||||
fps time.Duration
|
||||
connected bool
|
||||
}
|
||||
|
||||
func NewController(config *config.Config) (*Controller, error) {
|
||||
state, err := host.Init()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log := logrus.NewEntry(logrus.StandardLogger())
|
||||
for _, driver := range state.Failed {
|
||||
log.WithField("driver", driver.String()).WithError(driver.Err).Trace("host driver failed to load")
|
||||
}
|
||||
for _, driver := range state.Skipped {
|
||||
log.WithField("driver", driver.String()).Trace("host driver skipped")
|
||||
}
|
||||
for _, driver := range state.Loaded {
|
||||
log.WithField("driver", driver.String()).Debug("host driver loaded")
|
||||
}
|
||||
|
||||
c := &Controller{}
|
||||
if err = c.loadPlayer(config.Player); err != nil {
|
||||
c.teardown()
|
||||
return nil, err
|
||||
}
|
||||
if err = c.loadAudio(config.Audio); err != nil {
|
||||
c.teardown()
|
||||
return nil, err
|
||||
}
|
||||
if err = c.loadDisplays(config.Display); err != nil {
|
||||
c.teardown()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Controller) log() *logrus.Entry {
|
||||
return logrus.WithField("type", "controller")
|
||||
}
|
||||
|
||||
func (c *Controller) loadPlayer(config config.Player) (err error) {
|
||||
c.Player, err = player.New(config)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Controller) loadAudio(config config.Audio) (err error) {
|
||||
c.Audio, err = audio.New(config)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Controller) loadDisplays(config config.Display) (err error) {
|
||||
log := c.log()
|
||||
|
||||
if c.fps = time.Second / time.Duration(config.FPS); c.fps <= 0 {
|
||||
log.WithField("fps", c.fps).Debug("setting default frame rate")
|
||||
c.fps = time.Second / 15
|
||||
} else {
|
||||
log.WithField("fps", c.fps).Debug("setting frame rate")
|
||||
}
|
||||
|
||||
if c.Left, err = display.Load(config.Left); err != nil {
|
||||
return fmt.Errorf("error loading left display driver: %w", err)
|
||||
} else if err = c.Left.Fill(pixel.On); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Right, err = display.Load(config.Right); err != nil {
|
||||
return fmt.Errorf("error loading right display driver: %w", err)
|
||||
} else if err = c.Right.Fill(pixel.Off); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.visual.offline = visual.NewOffline(c.Left, c.Right, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Controller) teardown() {
|
||||
log := c.log()
|
||||
if c.Player != nil {
|
||||
log.Debug("halt player")
|
||||
}
|
||||
if c.Audio != nil {
|
||||
log.WithError(c.Audio.Halt()).Debug("halt audio")
|
||||
}
|
||||
if c.Left != nil {
|
||||
log.WithError(c.Left.Halt()).Debug("halt left screen")
|
||||
}
|
||||
if c.Right != nil {
|
||||
log.WithError(c.Right.Halt()).Debug("halt right screen")
|
||||
}
|
||||
if c.Color != nil {
|
||||
log.WithError(c.Color.Halt()).Debug("halt color screen")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) Run(ctx context.Context) error {
|
||||
defer c.teardown()
|
||||
|
||||
playerEvents, err := c.Player.Events()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.log().Info("Harmon controller running...")
|
||||
|
||||
var (
|
||||
fps = time.NewTicker(c.fps)
|
||||
update = time.NewTicker(25 * time.Millisecond)
|
||||
last time.Time
|
||||
frames int
|
||||
)
|
||||
|
||||
defer fps.Stop()
|
||||
defer update.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case event := <-playerEvents:
|
||||
c.handlePlayer(event)
|
||||
|
||||
case <-fps.C:
|
||||
frames++
|
||||
c.handleFrame()
|
||||
|
||||
case now := <-update.C:
|
||||
if now.Sub(last) > time.Second {
|
||||
c.log().WithField("fps", frames).Debug("frame rate")
|
||||
last = now
|
||||
frames = 0
|
||||
}
|
||||
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) handlePlayer(event player.Event) {
|
||||
log := c.log().WithField("from", "player")
|
||||
log.WithFields(logrus.Fields{
|
||||
"event": event.String(),
|
||||
}).Trace("new event")
|
||||
|
||||
switch event := event.(type) {
|
||||
case player.ConnectedEvent:
|
||||
log.Info("player connected")
|
||||
c.connected = true
|
||||
|
||||
case player.DisconnectedEvent:
|
||||
log.Warn("player disconnected")
|
||||
c.connected = false
|
||||
|
||||
case player.PlayEvent:
|
||||
log.WithField("track", event.Track).Info("now playing")
|
||||
|
||||
case player.StatusEvent:
|
||||
log.WithField("state", event.Status).Trace("player status")
|
||||
|
||||
default:
|
||||
log.WithField("event", event).Warn("unhandled event")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) handleFrame() {
|
||||
log := c.log()
|
||||
if c.connected {
|
||||
|
||||
} else {
|
||||
if err := c.visual.offline.Render(); err != nil {
|
||||
log.WithError(err).Warn("offline render failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
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),
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,411 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,535 +0,0 @@
|
||||
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))
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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"
|
||||
)
|
||||
@@ -1,192 +0,0 @@
|
||||
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{}
|
||||
}
|
||||
*/
|
||||
@@ -1,90 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,537 +0,0 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,134 +0,0 @@
|
||||
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{}
|
||||
)
|
||||
@@ -1,195 +0,0 @@
|
||||
// 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"
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,278 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
// 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{}
|
||||
)
|
||||
@@ -1,58 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,562 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,227 +0,0 @@
|
||||
// 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{}
|
||||
)
|
||||
@@ -1,103 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,888 +0,0 @@
|
||||
// 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)
|
||||
@@ -1,147 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package bragi
|
||||
|
||||
import "time"
|
||||
|
||||
type Event interface {
|
||||
// Source returns the source of the event.
|
||||
Source() Source
|
||||
|
||||
// Time of the event.
|
||||
Time() time.Time
|
||||
}
|
||||
|
||||
type (
|
||||
baseEvent struct {
|
||||
at time.Time
|
||||
source Source
|
||||
}
|
||||
|
||||
ConnectedEvent struct {
|
||||
baseEvent
|
||||
}
|
||||
|
||||
DisconnectedEvent struct {
|
||||
baseEvent
|
||||
Err error
|
||||
}
|
||||
|
||||
StatusEvent struct {
|
||||
baseEvent
|
||||
Status *Status
|
||||
}
|
||||
|
||||
TrackEvent struct {
|
||||
baseEvent
|
||||
Track *Track
|
||||
}
|
||||
)
|
||||
|
||||
func (e *baseEvent) Source() Source { return e.source }
|
||||
func (e *baseEvent) Time() time.Time { return e.at }
|
||||
|
||||
func NewConnectedEvent(s Source) *ConnectedEvent {
|
||||
return &ConnectedEvent{baseEvent{time.Now(), s}}
|
||||
}
|
||||
|
||||
func NewDisconnectedEvent(s Source, err error) *DisconnectedEvent {
|
||||
return &DisconnectedEvent{baseEvent{time.Now(), s}, err}
|
||||
}
|
||||
|
||||
func NewStatusEvent(s Source, v *Status) *StatusEvent {
|
||||
return &StatusEvent{baseEvent{time.Now(), s}, v}
|
||||
}
|
||||
|
||||
func NewTrackEvent(s Source, t *Track) *TrackEvent {
|
||||
return &TrackEvent{baseEvent{time.Now(), s}, t}
|
||||
}
|
||||
@@ -1,57 +1,25 @@
|
||||
module git.maze.io/go/harmon
|
||||
module go.maze.io/harmon
|
||||
|
||||
go 1.23.4
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.4.0
|
||||
github.com/fhs/gompd/v2 v2.3.0
|
||||
github.com/hashicorp/hcl/v2 v2.23.0
|
||||
github.com/maddyblue/go-dsp v0.0.0-20180508042940-11479a337f12
|
||||
github.com/kyoh86/xdg v1.2.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cobra v1.8.1
|
||||
golang.org/x/image v0.19.0
|
||||
github.com/zclconf/go-cty v1.16.0
|
||||
golang.org/x/image v0.23.0
|
||||
periph.io/x/conn/v3 v3.7.1
|
||||
periph.io/x/devices/v3 v3.7.2
|
||||
periph.io/x/host/v3 v3.8.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/adrg/xdg v0.5.3 // indirect
|
||||
github.com/agext/levenshtein v1.2.1 // indirect
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/gopherjs/gopherjs v0.0.0-20190411002643-bd77b112433e // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/libui-ng/golang-ui v0.0.0-20230331052320-13dec0981460 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/mjibson/go-dsp v0.0.0-20180508042940-11479a337f12 // indirect
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||
github.com/oov/audio v0.0.0-20171004131523-88a2be6dbe38 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.11.0 // indirect
|
||||
github.com/spf13/cast v1.6.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/spf13/viper v1.19.0 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/therecipe/qt v0.0.0-20200904063919-c0c124a5770d // indirect
|
||||
github.com/veandco/go-sdl2 v0.4.40 // indirect
|
||||
github.com/zclconf/go-cty v1.13.0 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||
golang.org/x/mod v0.17.0 // indirect
|
||||
golang.org/x/sys v0.29.0 // indirect
|
||||
golang.org/x/term v0.28.0 // indirect
|
||||
golang.org/x/text v0.17.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -1,141 +1,47 @@
|
||||
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
|
||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78=
|
||||
github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ=
|
||||
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
|
||||
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fhs/gompd/v2 v2.3.0 h1:wuruUjmOODRlJhrYx73rJnzS7vTSXSU7pWmZtM3VPE0=
|
||||
github.com/fhs/gompd/v2 v2.3.0/go.mod h1:nNdZtcpD5VpmzZbRl5rV6RhxeMmAWTxEsSIMBkmMIy4=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20190411002643-bd77b112433e h1:XWcjeEtTFTOVA9Fs1w7n2XBftk5ib4oZrhzWk0B+3eA=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20190411002643-bd77b112433e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/hashicorp/hcl/v2 v2.23.0 h1:Fphj1/gCylPxHutVSEOf2fBOh1VE4AuLV7+kbJf3qos=
|
||||
github.com/hashicorp/hcl/v2 v2.23.0/go.mod h1:62ZYHrXgPoX8xBnzl8QzbWq4dyDsDtfCRgIq1rbJEvA=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/libui-ng/golang-ui v0.0.0-20230331052320-13dec0981460 h1:+D5DQimWDP/ZiV3956+9aZC6bmrFZKS+nQL+HStOiuM=
|
||||
github.com/libui-ng/golang-ui v0.0.0-20230331052320-13dec0981460/go.mod h1:g/A5zMH2kHpEPtNi5r/pvuOv2BHt6L2BEop6vqnk5iU=
|
||||
github.com/maddyblue/go-dsp v0.0.0-20180508042940-11479a337f12 h1:7wMSBdw7hwomSkZtcM7P8WpacZYt5/wYUtg7Z83WMr8=
|
||||
github.com/maddyblue/go-dsp v0.0.0-20180508042940-11479a337f12/go.mod h1:YZub1Eb8ornlY/qMNCsKJnX+D6pNo8NOmwcuwrtXz8w=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/kyoh86/xdg v1.2.0 h1:CERuT/ShdTDj+A2UaX3hQ3mOV369+Sj+wyn2nIRIIkI=
|
||||
github.com/kyoh86/xdg v1.2.0/go.mod h1:/mg8zwu1+qe76oTFUBnyS7rJzk7LLC0VGEzJyJ19DHs=
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/mjibson/go-dsp v0.0.0-20180508042940-11479a337f12 h1:dd7vnTDfjtwCETZDrRe+GPYNLA1jBtbZeyfyE8eZCyk=
|
||||
github.com/mjibson/go-dsp v0.0.0-20180508042940-11479a337f12/go.mod h1:i/KKcxEWEO8Yyl11DYafRPKOPVYTrhxiTRigjtEEXZU=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/oov/audio v0.0.0-20171004131523-88a2be6dbe38 h1:4Upfs5rLQdx7KwBct3bmPYAhWsDDJdx660gYb7Lv9TQ=
|
||||
github.com/oov/audio v0.0.0-20171004131523-88a2be6dbe38/go.mod h1:Xj06yMta9R1RSKiHmxL0Bo2TB8wiKVnMgA0KVopHHkk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
|
||||
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
|
||||
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
|
||||
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
|
||||
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/therecipe/qt v0.0.0-20200904063919-c0c124a5770d h1:T+d8FnaLSvM/1BdlDXhW4d5dr2F07bAbB+LpgzMxx+o=
|
||||
github.com/therecipe/qt v0.0.0-20200904063919-c0c124a5770d/go.mod h1:SUUR2j3aE1z6/g76SdD6NwACEpvCxb3fvG82eKbD6us=
|
||||
github.com/veandco/go-sdl2 v0.4.40 h1:fZv6wC3zz1Xt167P09gazawnpa0KY5LM7JAvKpX9d/U=
|
||||
github.com/veandco/go-sdl2 v0.4.40/go.mod h1:OROqMhHD43nT4/i9crJukyVecjPNYYuCofep6SNiAjY=
|
||||
github.com/zclconf/go-cty v1.13.0 h1:It5dfKTTZHe9aeppbNOda3mN7Ag7sg6QkBNm6TkyFa0=
|
||||
github.com/zclconf/go-cty v1.13.0/go.mod h1:YKQzy/7pZ7iq2jNFzy5go57xdxdWoLLpaEp4u238AE0=
|
||||
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
|
||||
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190418165655-df01cb2cc480/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
|
||||
golang.org/x/image v0.19.0 h1:D9FX4QWkLfkeqaC62SonffIIuYdOk/UE2XKUBgRIBIQ=
|
||||
golang.org/x/image v0.19.0/go.mod h1:y0zrRqlQRWQ5PXaYCOMLTW2fpsxZ8Qh9I/ohnInJEys=
|
||||
github.com/zclconf/go-cty v1.16.0 h1:xPKEhst+BW5D0wxebMZkxgapvOE/dw7bFTlgSc9nD6w=
|
||||
github.com/zclconf/go-cty v1.16.0/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE=
|
||||
golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=
|
||||
golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=
|
||||
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190420063019-afa5a82059c6/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
|
||||
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
|
||||
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4=
|
||||
golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
|
||||
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
periph.io/x/conn/v3 v3.7.1 h1:tMjNv3WO8jEz/ePuXl7y++2zYi8LsQ5otbmqGKy3Myg=
|
||||
periph.io/x/conn/v3 v3.7.1/go.mod h1:c+HCVjkzbf09XzcqZu/t+U8Ss/2QuJj0jgRF6Nye838=
|
||||
periph.io/x/devices/v3 v3.7.2 h1:aMcDOrHBpnmZrSr8qE09pc22kT8LSf3FiI6clHwSPDE=
|
||||
periph.io/x/devices/v3 v3.7.2/go.mod h1:bb68xsoeCzslYzyTgJmV4yzZm6MmIloPG/A5ou6UCTo=
|
||||
periph.io/x/host/v3 v3.8.2 h1:ayKUDzgUCN0g8+/xM9GTkWaOBhSLVcVHGTfjAOi8OsQ=
|
||||
periph.io/x/host/v3 v3.8.2/go.mod h1:yFL76AesNHR68PboofSWYaQTKmvPXsQH2Apvp/ls/K4=
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Package all loads all display drivers.
|
||||
package all
|
||||
|
||||
import (
|
||||
_ "go.maze.io/harmon/hardware/display/ssd1306" // SSD1306
|
||||
)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 19 KiB |
@@ -1,156 +1,61 @@
|
||||
audio {
|
||||
type = "tcp"
|
||||
host = "volumio.local:6601"
|
||||
}
|
||||
display {
|
||||
fps = 15
|
||||
|
||||
player {
|
||||
type = "mpd"
|
||||
}
|
||||
|
||||
page "main" {
|
||||
visual = [
|
||||
"vumeter-left@left",
|
||||
//"vumeter-right@right",
|
||||
]
|
||||
|
||||
action {
|
||||
rotary_cw = "volume:+1"
|
||||
rotary_ccw = "volume:-1"
|
||||
rotary_click = "page:peak"
|
||||
rotary_hold = "mute"
|
||||
}
|
||||
|
||||
/*
|
||||
action {
|
||||
rotary_cw = volume(1)
|
||||
rotary_ccw = volume(-1)
|
||||
rotary_click = goto("peak")
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
page "peak" {
|
||||
visual = [
|
||||
"peak@left",
|
||||
]
|
||||
|
||||
/*
|
||||
action = {
|
||||
rotary_cw = volume(1)
|
||||
rotary_ccw = volume(-1)
|
||||
rotary_click = goto("peak")
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
display "color" {
|
||||
type = "st7789"
|
||||
reset = "GPIO23"
|
||||
dc = "GPIO25"
|
||||
bl = "GPIO24"
|
||||
size = "240x240"
|
||||
}
|
||||
*/
|
||||
|
||||
display "left" {
|
||||
left {
|
||||
type = "ssd1306"
|
||||
addr = "0x3d"
|
||||
size = "128x64"
|
||||
}
|
||||
}
|
||||
|
||||
display "right" {
|
||||
right {
|
||||
type = "ssd1306"
|
||||
addr = "0x3c"
|
||||
size = "128x64"
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// Waveshare 240x320 ST7789V2
|
||||
display "left" {
|
||||
color {
|
||||
type = "st7789"
|
||||
bl = "GPIO18"
|
||||
reset = "GPIO27"
|
||||
dc = "GPIO25"
|
||||
cs = "GPIO8"
|
||||
size = "240x320"
|
||||
//rotate = "90"
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
display "main" {
|
||||
type = "ssd1326"
|
||||
addr = "0x3c"
|
||||
size = "256x64"
|
||||
}
|
||||
|
||||
display "left" {
|
||||
type = "split"
|
||||
addr = "main"
|
||||
size = "128x64"
|
||||
port = "0,0,128,64"
|
||||
}
|
||||
|
||||
display "right" {
|
||||
type = "split"
|
||||
addr = "main"
|
||||
size = "128x64"
|
||||
port = "128,0,256,64"
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
display "left" {
|
||||
type = "ssd1306"
|
||||
addr = "0x3C"
|
||||
size = "128x64"
|
||||
}
|
||||
|
||||
display "right" {
|
||||
type = "ssd1306"
|
||||
addr = "0x7a"
|
||||
size = "128x64"
|
||||
}
|
||||
|
||||
display "main" {
|
||||
type = "row"
|
||||
addr = "left,right"
|
||||
}
|
||||
|
||||
display "main_stack" {
|
||||
type = "column"
|
||||
addr = "left,right"
|
||||
}
|
||||
*/
|
||||
|
||||
input "knob" {
|
||||
type = "rotary"
|
||||
}
|
||||
|
||||
visual "vumeter-left" {
|
||||
type = "vumeter"
|
||||
|
||||
config = {
|
||||
channel = 1
|
||||
channels = 2
|
||||
size = "240x240"
|
||||
reset = "GPIOx" # reset pin
|
||||
dc = "GPIOx" # data control pin
|
||||
bl = "GPIOx" # backlight pin
|
||||
}
|
||||
}
|
||||
|
||||
visual "vumeter-right" {
|
||||
type = "vumeter"
|
||||
|
||||
config = {
|
||||
channel = 1
|
||||
channels = 2
|
||||
mirror = true
|
||||
input {
|
||||
encoder {
|
||||
# The rotary is configured as input device.
|
||||
#
|
||||
# On Raspberry Pi, this can be done by adding the following line
|
||||
# to /boot/config.txt:
|
||||
#
|
||||
# # Rotary encoder on GPIO20 & GPIO21
|
||||
# dtoverlay=rotary-encoder,pin_a=20,pin_b=21,relative_axis=1,steps-per-period=2
|
||||
#
|
||||
# # Rotary push button, KEY_MUTE on GPIO16
|
||||
# dtoverlay=gpio-key,gpio=16,label="rotary-switch",keycode=113
|
||||
type = "input"
|
||||
#type = "gpio"
|
||||
#cw = "GPIOx" # clock wise pulse pin
|
||||
#ccw = "GPIOx" # counter clock wise pulse pin
|
||||
#sw = "GPIOx" # switch pin
|
||||
}
|
||||
}
|
||||
|
||||
visual "peak" {
|
||||
type = "peak"
|
||||
player {
|
||||
# Auto detect the player.
|
||||
type = "auto"
|
||||
|
||||
## Music Player Daemon
|
||||
# type = "mpd"
|
||||
# host = "localhost:6600"
|
||||
# password = ""
|
||||
}
|
||||
|
||||
visual "volume" {
|
||||
type = "volume"
|
||||
audio {
|
||||
type = "fifo"
|
||||
path = "/tmp/mpd.fifo"
|
||||
rate = 44100
|
||||
channels = 2
|
||||
bits = 16
|
||||
}
|
||||
|
Before Width: | Height: | Size: 16 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" enable-background="new 0 0 64 64"><path d="m49.814 2.054c-2.674-.387-5.672 1.309-6.259 5.282-.489 3.318-1.75 11.499-2.392 15.652-.969-.808-2.25-1.258-3.631-1.258-1.922 0-3.92.908-5.039 2.628-.18-.215-.367-.426-.591-.61-.95-.785-2.227-1.216-3.593-1.216-2.185 0-4.384 1.114-5.226 3.258l-2.423-12.219c-.588-2.065-2.011-3.523-3.906-3.999-1.9-.478-3.995.109-5.339 1.494-1.305 1.345-1.732 3.261-1.178 5.264.172.993 2.77 16.044 3.205 18.759.221 1.363.161 2.731.088 4.464-.101 2.341-.224 5.255.333 9.356 1.019 7.509 7.789 12.637 17.248 13.066.386.017.775.025 1.166.025 8.107 0 17.257-3.772 19.234-12.396 1.188-5.17.274-8.597-1.606-11.181.384-2.932 2.971-22.789 4.021-30.276.518-3.706-1.767-5.756-4.112-6.093m-4.698 5.293c.848-5.745 7.037-4.297 6.421.185l-3.848 28.504c-1.406-1.225-3.012-2.269-4.603-3.298l-.12-.077c0 0 .02-4.028.104-5.422.038-.665-.111-1.75-.485-2.391.001 0 1.906-13.256 2.531-17.501m-5.182 18.874v4.951c-1.274-.256-2.382.042-3.595.38-.771.216-1.65.456-2.74.602l-.327-5.306c-.001-4.482 6.681-3.97 6.662-.627m-15.756 1.189c-.313-4.188 6.281-4.063 6.379-.129v4.969c-1.728.159-3.487 1.158-4.057 3.098-.179.611-.24 1.324-.139 2.059-.984-.583-1.637-1.643-1.637-2.892l-.546-7.105m-9.251 7.5c-.451-2.804-3.438-19.063-3.438-19.063-1.285-4.519 5.657-6.304 6.75-1.999 0 0 3.212 16.56 4.499 22.031.494 2.095 2.503 3.661 4.679 3.941.417.508.963.979 1.673 1.379.014.008.024.021.04.029l.02.009c.904.419 1.907.818 2.973 1.023-2.235 1.249-4.039 3.685-2.945 7.665-.089-6.568 5.296-7.904 7.995-8.062.048.05 2.861 3.18 3.146 3.718.27.509.063 1.8.063 1.8s.587-1.223.337-1.919c-.229-.634-2.205-4.233-3.584-4.836-.707-.311-1.961.375-3.592.055-1.111-.218-2.785-1.058-3.631-1.568-2.828-1.707-2.323-5.567.234-5.391 3.102.215 5.094-.508 6.564-.916 1.716-.48 3.142-.709 4.717.322 0 0 7.408 5.25 8.471 8.844 1.28 5.884-1.971 16.588-17.522 17.5-6.108 0-9.994-1.734-12.313-3.368-2.172-1.772-4.195-4.189-4.638-7.444-.532-3.925-.246-12.185-.498-13.75"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 16 KiB |
@@ -1,115 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
|
||||
"git.maze.io/go/bragi/audio"
|
||||
"git.maze.io/go/bragi/hardware"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
// Visualizer processes raw audio that can be rendered onto a display.
|
||||
type Visualizer interface {
|
||||
Process(audio.Slice)
|
||||
Render(dst draw.Image, origin image.Point, c color.Color)
|
||||
}
|
||||
|
||||
// Reader can read samples.
|
||||
type Reader interface {
|
||||
hardware.Resource
|
||||
|
||||
Channels() int
|
||||
SampleRate() physic.Frequency
|
||||
ReadSamples(audio.Slice) (int, error)
|
||||
}
|
||||
|
||||
type Filter interface {
|
||||
Filter(audio.Slice) audio.Slice
|
||||
}
|
||||
|
||||
type pcm16Reader struct {
|
||||
name string
|
||||
channels int
|
||||
sampleRate physic.Frequency
|
||||
rc io.ReadCloser
|
||||
byteOrder binary.ByteOrder
|
||||
b audio.Int16
|
||||
}
|
||||
|
||||
// OpenPCM16 reads from a raw linear 16-bit PCM file (or fifo).
|
||||
func OpenPCM16(name string, byteOrder binary.ByteOrder, channels int, sampleRate physic.Frequency) (Reader, error) {
|
||||
f, err := os.OpenFile(name, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pcm16Reader{
|
||||
name: name,
|
||||
channels: channels,
|
||||
sampleRate: sampleRate,
|
||||
rc: f,
|
||||
byteOrder: byteOrder,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// OpenPCM16TCP reads from a raw linear 16-bit PCM stream over TCP.
|
||||
func OpenPCM16TCP(addr string, byteOrder binary.ByteOrder, channels int, sampleRate physic.Frequency) (Reader, error) {
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pcm16Reader{
|
||||
name: "tcp://" + addr,
|
||||
channels: channels,
|
||||
sampleRate: sampleRate,
|
||||
rc: c,
|
||||
byteOrder: byteOrder,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *pcm16Reader) String() string {
|
||||
return fmt.Sprintf("pcm reader %s", r.name)
|
||||
}
|
||||
|
||||
func (r *pcm16Reader) Halt() error {
|
||||
return r.rc.Close()
|
||||
}
|
||||
|
||||
func (r *pcm16Reader) Channels() int {
|
||||
return r.channels
|
||||
}
|
||||
|
||||
func (r *pcm16Reader) SampleRate() physic.Frequency {
|
||||
return r.sampleRate
|
||||
}
|
||||
|
||||
func (r *pcm16Reader) ReadSamples(p audio.Slice) (n int, err error) {
|
||||
var (
|
||||
data audio.Int16
|
||||
ok bool
|
||||
)
|
||||
if data, ok = p.(audio.Int16); !ok {
|
||||
length := p.Len()
|
||||
if l := len(r.b); l < length {
|
||||
r.b = make(audio.Int16, p.Len())
|
||||
} else {
|
||||
r.b = r.b[:length]
|
||||
}
|
||||
data = r.b
|
||||
}
|
||||
if err = binary.Read(r.rc, r.byteOrder, &data); err != nil {
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
// Convert back
|
||||
r.b.CopyTo(p)
|
||||
}
|
||||
return p.Len(), nil
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
"image/draw"
|
||||
)
|
||||
|
||||
func drawSprite(p draw.Image, x, y int, sprite []uint8, c color.Color) {
|
||||
/*
|
||||
for dy, row := range sprite {
|
||||
for dx := 0; dx < 8; dx++ {
|
||||
if row&(1<<(7-dx)) != 0 {
|
||||
p.Set(x+dx, y+dy, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
w, h, data := sprite[0], sprite[1], sprite[2:]
|
||||
for dy := 0; dy < int(h); dy++ {
|
||||
//pix := data[dy*int(w>>3):]
|
||||
for dx := 0; dx < int(w); dx++ {
|
||||
//b := pix[dx>>3]
|
||||
//if b&(1<<(7-(dx%8))) != 0 {
|
||||
// p.Set(x+dx, y+dy, c)
|
||||
//}
|
||||
byteOffset := int(dy/8)*int(w) + dx
|
||||
bitOffset := dy % 8
|
||||
if data[byteOffset]&(1<<bitOffset) != 0 {
|
||||
p.Set(x+dx, y+dy, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func drawLine(p draw.Image, x1, y1, x2, y2 int, c color.Color) {
|
||||
var dx, dy, e, slope int
|
||||
|
||||
// Because drawing p1 -> p2 is equivalent to draw p2 -> p1,
|
||||
// I sort points in x-axis order to handle only half of possible cases.
|
||||
if x1 > x2 {
|
||||
x1, y1, x2, y2 = x2, y2, x1, y1
|
||||
}
|
||||
|
||||
dx, dy = x2-x1, y2-y1
|
||||
// Because point is x-axis ordered, dx cannot be negative
|
||||
if dy < 0 {
|
||||
dy = -dy
|
||||
}
|
||||
|
||||
switch {
|
||||
|
||||
// Is line a point ?
|
||||
case x1 == x2 && y1 == y2:
|
||||
p.Set(x1, y1, c)
|
||||
|
||||
// Is line an horizontal ?
|
||||
case y1 == y2:
|
||||
for ; dx != 0; dx-- {
|
||||
p.Set(x1, y1, c)
|
||||
x1++
|
||||
}
|
||||
p.Set(x1, y1, c)
|
||||
|
||||
// Is line a vertical ?
|
||||
case x1 == x2:
|
||||
if y1 > y2 {
|
||||
y1, y2 = y2, y1
|
||||
}
|
||||
for ; dy != 0; dy-- {
|
||||
p.Set(x1, y1, c)
|
||||
y1++
|
||||
}
|
||||
p.Set(x1, y1, c)
|
||||
|
||||
// Is line a diagonal ?
|
||||
case dx == dy:
|
||||
if y1 < y2 {
|
||||
for ; dx != 0; dx-- {
|
||||
p.Set(x1, y1, c)
|
||||
x1++
|
||||
y1++
|
||||
}
|
||||
} else {
|
||||
for ; dx != 0; dx-- {
|
||||
p.Set(x1, y1, c)
|
||||
x1++
|
||||
y1--
|
||||
}
|
||||
}
|
||||
p.Set(x1, y1, c)
|
||||
|
||||
// wider than high ?
|
||||
case dx > dy:
|
||||
if y1 < y2 {
|
||||
// BresenhamDxXRYD(img, x1, y1, x2, y2, col)
|
||||
dy, e, slope = 2*dy, dx, 2*dx
|
||||
for ; dx != 0; dx-- {
|
||||
p.Set(x1, y1, c)
|
||||
x1++
|
||||
e -= dy
|
||||
if e < 0 {
|
||||
y1++
|
||||
e += slope
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// BresenhamDxXRYU(img, x1, y1, x2, y2, col)
|
||||
dy, e, slope = 2*dy, dx, 2*dx
|
||||
for ; dx != 0; dx-- {
|
||||
p.Set(x1, y1, c)
|
||||
x1++
|
||||
e -= dy
|
||||
if e < 0 {
|
||||
y1--
|
||||
e += slope
|
||||
}
|
||||
}
|
||||
}
|
||||
p.Set(x2, y2, c)
|
||||
|
||||
// higher than wide.
|
||||
default:
|
||||
if y1 < y2 {
|
||||
// BresenhamDyXRYD(img, x1, y1, x2, y2, col)
|
||||
dx, e, slope = 2*dx, dy, 2*dy
|
||||
for ; dy != 0; dy-- {
|
||||
p.Set(x1, y1, c)
|
||||
y1++
|
||||
e -= dx
|
||||
if e < 0 {
|
||||
x1++
|
||||
e += slope
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// BresenhamDyXRYU(img, x1, y1, x2, y2, col)
|
||||
dx, e, slope = 2*dx, dy, 2*dy
|
||||
for ; dy != 0; dy-- {
|
||||
p.Set(x1, y1, c)
|
||||
y1--
|
||||
e -= dx
|
||||
if e < 0 {
|
||||
x1++
|
||||
e += slope
|
||||
}
|
||||
}
|
||||
}
|
||||
p.Set(x2, y2, c)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package audio
|
||||
|
||||
// Deinterleave multi channel samples to separate slices.
|
||||
func Deinterleave(samples []int16, slices [][]int16) {
|
||||
if len(samples) == 0 {
|
||||
return
|
||||
}
|
||||
if len(slices) == 1 {
|
||||
copy(slices[0], samples)
|
||||
return
|
||||
}
|
||||
|
||||
channels := len(slices)
|
||||
for i, sample := range samples {
|
||||
j, k := i%channels, i/channels
|
||||
slices[j][k] = sample
|
||||
}
|
||||
}
|
||||
|
||||
// Interleave multi channel samples to a single slice.
|
||||
func Interleave(slices [][]int16, samples []int16) {
|
||||
if len(slices) == 0 {
|
||||
return
|
||||
}
|
||||
if len(slices) == 1 {
|
||||
copy(samples, slices[0])
|
||||
return
|
||||
}
|
||||
|
||||
channels := len(slices)
|
||||
for i := range samples {
|
||||
j, k := i%channels, i/channels
|
||||
samples[i] = slices[j][k]
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"math"
|
||||
"sort"
|
||||
|
||||
"git.maze.io/go/bragi/audio"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
var (
|
||||
spriteLeft = []uint8{
|
||||
0x08, /* width */
|
||||
0x05, /* height */
|
||||
0b10000,
|
||||
0b10000,
|
||||
0b10000,
|
||||
0b10000,
|
||||
0b11110,
|
||||
}
|
||||
spriteRight = []uint8{
|
||||
0x08, /* width */
|
||||
0x05, /* height */
|
||||
0b11110,
|
||||
0b10001,
|
||||
0b11110,
|
||||
0b10100,
|
||||
0b10010,
|
||||
}
|
||||
)
|
||||
|
||||
type Peak struct {
|
||||
rate physic.Frequency
|
||||
channels int
|
||||
level audio.Float64
|
||||
peaks []audio.Float64
|
||||
}
|
||||
|
||||
func NewPeak(sampleRate physic.Frequency, channels int, keep int) *Peak {
|
||||
if channels < 1 {
|
||||
channels = 1
|
||||
} else if channels > 2 {
|
||||
channels = 2
|
||||
}
|
||||
|
||||
v := &Peak{
|
||||
rate: sampleRate,
|
||||
channels: channels,
|
||||
level: make(audio.Float64, channels),
|
||||
}
|
||||
|
||||
if keep > 0 {
|
||||
for i := 0; i < channels; i++ {
|
||||
v.peaks = append(v.peaks, make(audio.Float64, keep))
|
||||
}
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
func (v *Peak) Process(samples audio.Slice) {
|
||||
sum := make([]float64, v.channels)
|
||||
for i, l := 0, samples.Len(); i < l; i++ {
|
||||
k := samples.At(i)
|
||||
if k < 0 {
|
||||
k = -k
|
||||
}
|
||||
if k > 1 {
|
||||
k = 1
|
||||
}
|
||||
n := i % v.channels
|
||||
sum[n] += math.Pow(k, 2)
|
||||
}
|
||||
|
||||
//log.Printf("max: %+v", max)
|
||||
for n, k := range sum {
|
||||
l := math.Sqrt(k / float64(samples.Len()))
|
||||
v.level[n] = l
|
||||
|
||||
if v.peaks != nil {
|
||||
copy(v.peaks[n][1:], v.peaks[n])
|
||||
v.peaks[n][0] = l
|
||||
//sortSlice(v.peaks[n], true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Peak) Render(dst draw.Image, origin image.Point, c color.Color) {
|
||||
var (
|
||||
r = image.Rect(0, 0, 64, 11)
|
||||
scale = 1.0 / float64(r.Dx()-6)
|
||||
)
|
||||
|
||||
// Clear buffer
|
||||
draw.Draw(dst, r.Add(origin), image.Black, image.Point{}, draw.Src)
|
||||
|
||||
ox, oy := origin.X, origin.Y
|
||||
|
||||
// Draw sprites
|
||||
drawSprite(dst, ox-3, oy+0, spriteLeft[:], c)
|
||||
drawSprite(dst, ox-3, oy+6, spriteRight[:], c)
|
||||
|
||||
// Draw line
|
||||
ox += 6
|
||||
drawLine(dst, ox, oy+2, ox+r.Dx()-6, oy+2, c)
|
||||
drawLine(dst, ox, oy+8, ox+r.Dx()-6, oy+8, c)
|
||||
|
||||
// Draw bar
|
||||
lw := int(v.level[0] / scale)
|
||||
rw := lw
|
||||
if v.channels > 1 {
|
||||
rw = int(v.level[1] / scale)
|
||||
}
|
||||
drawLine(dst, ox, oy+1, ox+lw, oy+1, c)
|
||||
drawLine(dst, ox, oy+3, ox+lw, oy+3, c)
|
||||
drawLine(dst, ox, oy+7, ox+rw, oy+7, c)
|
||||
drawLine(dst, ox, oy+9, ox+rw, oy+9, c)
|
||||
|
||||
if v.peaks != nil {
|
||||
lw = int(audio.Max(v.peaks[0]) / scale) //int(v.peaks[0][0] / scale)
|
||||
rw = lw
|
||||
if v.channels > 1 {
|
||||
rw = int(audio.Max(v.peaks[1]) / scale) //int(v.peaks[1][0] / scale)
|
||||
}
|
||||
drawLine(dst, ox+lw, oy+1, ox+lw, oy+3, c)
|
||||
drawLine(dst, ox+rw, oy+7, ox+rw, oy+9, c)
|
||||
}
|
||||
}
|
||||
|
||||
func sortSlice(s audio.Float64, reverse bool) {
|
||||
sort.Slice(s, func(i, j int) bool {
|
||||
if reverse {
|
||||
return s[i] > s[j]
|
||||
}
|
||||
return s[i] < s[j]
|
||||
})
|
||||
}
|
||||
|
||||
var _ Visualizer = (*Peak)(nil)
|
||||
@@ -1 +0,0 @@
|
||||
package audio
|
||||
@@ -1,205 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"math"
|
||||
|
||||
"git.maze.io/go/bragi/audio"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
)
|
||||
|
||||
type VUMeter struct {
|
||||
rate physic.Frequency
|
||||
channel int
|
||||
channels int
|
||||
level float64
|
||||
//peaks []audio.Float64
|
||||
}
|
||||
|
||||
func NewVUMeter(sampleRate physic.Frequency, channel, channels int) *VUMeter {
|
||||
if channel < 1 {
|
||||
channel = 1
|
||||
} else if channel > 2 {
|
||||
channel = 2
|
||||
}
|
||||
if channels < 1 {
|
||||
channels = 1
|
||||
} else if channels > 2 {
|
||||
channels = 2
|
||||
}
|
||||
|
||||
v := &VUMeter{
|
||||
rate: sampleRate,
|
||||
channel: channel,
|
||||
channels: channels,
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
func (v *VUMeter) Process(samples audio.Slice) {
|
||||
var sum float64
|
||||
for i, l := 0, samples.Len(); i < l; i++ {
|
||||
k := samples.At(i)
|
||||
if k < 0 {
|
||||
k = -k
|
||||
}
|
||||
if k > 1 {
|
||||
k = 1
|
||||
}
|
||||
if n := i % v.channels; n == v.channel {
|
||||
sum += math.Pow(k, 2)
|
||||
}
|
||||
}
|
||||
|
||||
// RMS level
|
||||
v.level = math.Sqrt(sum / float64(samples.Len()))
|
||||
}
|
||||
|
||||
func (v *VUMeter) Render(dst draw.Image, origin image.Point, c color.Color) {
|
||||
// Clear buffer
|
||||
draw.Draw(dst, dst.Bounds(), image.Black, image.Point{}, draw.Src)
|
||||
|
||||
// Draw background
|
||||
drawSprite(dst, origin.X, origin.Y, vumeterBackground[v.channel-1], c)
|
||||
|
||||
var (
|
||||
scale = 1.0 / float64(len(needleCoordinates))
|
||||
angle = int(v.level / scale)
|
||||
point = needleCoordinates[angle].Add(origin)
|
||||
)
|
||||
drawLine(dst, point.X, point.Y, origin.X+64, origin.Y+96, c)
|
||||
}
|
||||
|
||||
var needleCoordinates = []image.Point{
|
||||
{0, 23},
|
||||
{1, 23},
|
||||
{2, 22},
|
||||
{3, 21},
|
||||
{3, 21},
|
||||
{4, 20},
|
||||
{5, 19},
|
||||
{6, 19},
|
||||
{7, 18},
|
||||
{8, 17},
|
||||
{9, 17},
|
||||
{10, 16},
|
||||
{10, 16},
|
||||
{11, 15},
|
||||
{12, 14},
|
||||
{13, 14},
|
||||
{14, 13},
|
||||
{15, 13},
|
||||
{16, 12},
|
||||
{17, 12},
|
||||
{18, 11},
|
||||
{19, 11},
|
||||
{20, 10},
|
||||
{21, 10},
|
||||
{22, 9},
|
||||
{23, 9},
|
||||
{24, 8},
|
||||
{25, 8},
|
||||
{26, 7},
|
||||
{27, 7},
|
||||
{28, 6},
|
||||
{29, 6},
|
||||
{30, 6},
|
||||
{31, 5},
|
||||
{32, 5},
|
||||
{33, 5},
|
||||
{34, 4},
|
||||
{35, 4},
|
||||
{36, 4},
|
||||
{37, 3},
|
||||
{38, 3},
|
||||
{39, 3},
|
||||
{40, 2},
|
||||
{41, 2},
|
||||
{42, 2},
|
||||
{43, 2},
|
||||
{45, 1},
|
||||
{46, 1},
|
||||
{47, 1},
|
||||
{48, 1},
|
||||
{49, 1},
|
||||
{50, 0},
|
||||
{51, 0},
|
||||
{52, 0},
|
||||
{53, 0},
|
||||
{54, 0},
|
||||
{55, 0},
|
||||
{56, 0},
|
||||
{57, 0},
|
||||
{59, 0},
|
||||
{60, 0},
|
||||
{61, 0},
|
||||
{62, 0},
|
||||
{63, 0},
|
||||
{64, 0},
|
||||
{65, 0},
|
||||
{66, 0},
|
||||
{67, 0},
|
||||
{68, 0},
|
||||
{70, 0},
|
||||
{71, 0},
|
||||
{72, 0},
|
||||
{73, 0},
|
||||
{74, 0},
|
||||
{75, 0},
|
||||
{76, 0},
|
||||
{77, 0},
|
||||
{78, 1},
|
||||
{79, 1},
|
||||
{80, 1},
|
||||
{81, 1},
|
||||
{82, 1},
|
||||
{84, 2},
|
||||
{85, 2},
|
||||
{86, 2},
|
||||
{87, 2},
|
||||
{88, 3},
|
||||
{89, 3},
|
||||
{90, 3},
|
||||
{91, 4},
|
||||
{92, 4},
|
||||
{93, 4},
|
||||
{94, 5},
|
||||
{95, 5},
|
||||
{96, 5},
|
||||
{97, 6},
|
||||
{98, 6},
|
||||
{99, 6},
|
||||
{100, 7},
|
||||
{101, 7},
|
||||
{102, 8},
|
||||
{103, 8},
|
||||
{104, 9},
|
||||
{105, 9},
|
||||
{106, 10},
|
||||
{107, 10},
|
||||
{108, 11},
|
||||
{109, 11},
|
||||
{110, 12},
|
||||
{111, 12},
|
||||
{112, 13},
|
||||
{113, 13},
|
||||
{114, 14},
|
||||
{115, 14},
|
||||
{116, 15},
|
||||
{117, 16},
|
||||
{117, 16},
|
||||
{118, 17},
|
||||
{119, 17},
|
||||
{120, 18},
|
||||
{121, 19},
|
||||
{122, 19},
|
||||
{123, 20},
|
||||
{124, 21},
|
||||
{124, 21},
|
||||
{125, 22},
|
||||
{126, 23},
|
||||
{127, 23},
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"math"
|
||||
)
|
||||
|
||||
type Waveform struct {
|
||||
bins []int8
|
||||
height int
|
||||
scale float64
|
||||
decimate int
|
||||
r image.Rectangle
|
||||
}
|
||||
|
||||
func NewWaveform(x, y int) *Waveform {
|
||||
return &Waveform{
|
||||
bins: make([]int8, x),
|
||||
height: y,
|
||||
scale: float64(y>>1) / math.MaxInt16,
|
||||
decimate: 1,
|
||||
r: image.Rect(0, 0, x, y),
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Waveform) Process(sample int16) {
|
||||
v.shift()
|
||||
v.bins[0] = int8(float64(sample) * v.scale)
|
||||
}
|
||||
|
||||
func (v *Waveform) shift() {
|
||||
copy(v.bins[1:], v.bins)
|
||||
v.bins[0] = 0
|
||||
}
|
||||
|
||||
func (v *Waveform) Draw(i draw.Image, o image.Point) {
|
||||
draw.Draw(i, v.r.Add(o), image.Black, image.Point{}, draw.Src)
|
||||
for x, h := range v.bins {
|
||||
drawLine(i, o.X+x, o.Y+int(h), o.X+x, o.Y+v.height, color.White)
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package input
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Event interface {
|
||||
String() string
|
||||
|
||||
// Source this event originated from.
|
||||
Source() Source
|
||||
|
||||
// Time of the event.
|
||||
Time() time.Time
|
||||
}
|
||||
|
||||
type (
|
||||
baseEvent struct {
|
||||
source Source
|
||||
time time.Time
|
||||
}
|
||||
|
||||
// Button event.
|
||||
Button struct {
|
||||
baseEvent
|
||||
|
||||
// Pressed indicates if the button is pressed or released.
|
||||
Pressed bool
|
||||
}
|
||||
|
||||
// Rotary encoder event.
|
||||
Rotary struct {
|
||||
baseEvent
|
||||
|
||||
// Delta is the rate of change.
|
||||
Delta int
|
||||
|
||||
// Switch indicates if the rotary switch is pressed or released.
|
||||
Switch bool
|
||||
}
|
||||
|
||||
// Key event.
|
||||
Key struct {
|
||||
baseEvent
|
||||
|
||||
// Pressed indicates if the key is pressed or released.
|
||||
Pressed bool
|
||||
|
||||
// Code is the key scan code.
|
||||
Code uint
|
||||
}
|
||||
)
|
||||
|
||||
func (e baseEvent) Source() Source { return e.source }
|
||||
func (e baseEvent) Time() time.Time { return e.time }
|
||||
func (e *baseEvent) SetTime(t time.Time) { e.time = t }
|
||||
|
||||
func makeBaseEvent(source Source) baseEvent {
|
||||
return baseEvent{
|
||||
source: source,
|
||||
time: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
func (e Button) String() string {
|
||||
if e.Pressed {
|
||||
return "button pressed"
|
||||
}
|
||||
return "button released"
|
||||
}
|
||||
|
||||
func NewButtonEvent(source Source, pressed bool) Event {
|
||||
return &Button{
|
||||
baseEvent: makeBaseEvent(source),
|
||||
Pressed: pressed,
|
||||
}
|
||||
}
|
||||
|
||||
func (e Rotary) String() string {
|
||||
if e.Delta == 0 {
|
||||
if e.Switch {
|
||||
return "rotary pressed"
|
||||
}
|
||||
return "rotary released"
|
||||
}
|
||||
return fmt.Sprintf("rotary delta=%d", e.Delta)
|
||||
}
|
||||
|
||||
func NewRotaryEvent(source Source, delta int, pressed bool) Event {
|
||||
return &Rotary{
|
||||
baseEvent: makeBaseEvent(source),
|
||||
Delta: delta,
|
||||
Switch: pressed,
|
||||
}
|
||||
}
|
||||
|
||||
func (e Key) String() string {
|
||||
if e.Pressed {
|
||||
return "key pressed"
|
||||
}
|
||||
return "key released"
|
||||
}
|
||||
|
||||
func NewKeyEvent(source Source, pressed bool, code uint) Event {
|
||||
return &Key{
|
||||
baseEvent: makeBaseEvent(source),
|
||||
Pressed: pressed,
|
||||
Code: code,
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package input
|
||||
|
||||
var detectors []func() ([]Source, error)
|
||||
|
||||
// Detect returns a list of input sources.
|
||||
func Detect() ([]Source, error) {
|
||||
var s []Source
|
||||
|
||||
for _, d := range detectors {
|
||||
ds, err := d()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s = append(s, ds...)
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Register a new input source detector.
|
||||
func Register(detector func() ([]Source, error)) {
|
||||
detectors = append(detectors, detector)
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
package input
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
devfsPath = "/dev"
|
||||
sysfsPath = "/sys"
|
||||
)
|
||||
|
||||
func init() {
|
||||
detectors = append(detectors, detectLinux)
|
||||
}
|
||||
|
||||
func detectLinux() ([]Source, error) {
|
||||
log := logrus.WithField("input", "detect")
|
||||
|
||||
ps, err := linuxPheripherals()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debugf("detected %d peripherals", len(ps))
|
||||
|
||||
ss := make([]Source, 0, len(ps))
|
||||
for _, p := range ps {
|
||||
if i := strings.IndexByte(p.name, '@'); i != -1 {
|
||||
switch p.name[:i] {
|
||||
case "button":
|
||||
log.WithField("path", p.path).Debug("detected button")
|
||||
ss = append(ss, newLinuxButton(p))
|
||||
case "rotary":
|
||||
log.WithField("path", p.path).Debug("detected rotary encoder")
|
||||
ss = append(ss, newLinuxRotary(p))
|
||||
default:
|
||||
log.WithField("path", p.path).Debugf("unsupported %q peripheral", p.name[:i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return ss, nil
|
||||
}
|
||||
|
||||
type linuxPheripheral struct {
|
||||
name string
|
||||
bus string
|
||||
vendor string
|
||||
product string
|
||||
version string
|
||||
phys string
|
||||
path string
|
||||
}
|
||||
|
||||
/*
|
||||
I: Bus=0019 Vendor=0001 Product=0001 Version=0100
|
||||
N: Name="button@10"
|
||||
P: Phys=gpio-keys/input0
|
||||
S: Sysfs=/devices/platform/button@10/input/input0
|
||||
U: Uniq=
|
||||
H: Handlers=kbd event0
|
||||
B: PROP=0
|
||||
B: EV=3
|
||||
B: KEY=20000 0 0 0
|
||||
|
||||
I: Bus=0019 Vendor=0000 Product=0000 Version=0000
|
||||
N: Name="rotary@14"
|
||||
P: Phys=
|
||||
S: Sysfs=/devices/platform/rotary@14/input/input1
|
||||
U: Uniq=
|
||||
H: Handlers=event1
|
||||
B: PROP=0
|
||||
B: EV=5
|
||||
B: REL=1
|
||||
*/
|
||||
func linuxPheripherals() (ps []*linuxPheripheral, err error) {
|
||||
log := logrus.WithField("input", "linux")
|
||||
log.Trace("detecting peripherals")
|
||||
|
||||
b, err := os.ReadFile("/proc/bus/input/devices")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, segment := range strings.Split(string(b), "\n\n") {
|
||||
lines := strings.Split(segment, "\n")
|
||||
perip := new(linuxPheripheral)
|
||||
for _, line := range lines {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
log.WithField("line", line).Trace("parsing line")
|
||||
switch {
|
||||
case strings.HasPrefix(line, "I: "):
|
||||
for _, kv := range strings.Split(strings.TrimPrefix(line, "I: "), " ") {
|
||||
kv := strings.SplitN(kv, "=", 2)
|
||||
switch kv[0] {
|
||||
case "Bus":
|
||||
case "Vendor":
|
||||
perip.vendor = kv[1]
|
||||
case "Product":
|
||||
perip.product = kv[1]
|
||||
case "Version":
|
||||
perip.version = kv[1]
|
||||
}
|
||||
}
|
||||
case strings.HasPrefix(line, "N: Name="):
|
||||
perip.name = strings.TrimFunc(strings.TrimPrefix(line, "N: Name="), func(r rune) bool {
|
||||
return r == '"' || r == '@'
|
||||
})
|
||||
case strings.HasPrefix(line, "P: Phys="):
|
||||
perip.phys = strings.TrimPrefix(line, "P: Phys=")
|
||||
//case strings.HasPrefix(line, "S: Sysfs="):
|
||||
// perip.sysfs = filepath.Join(sysfsPath, strings.TrimPrefix(line, "S: Sysfs="), "device")
|
||||
case strings.HasPrefix(line, "H: Handlers="):
|
||||
for _, handler := range strings.Split(strings.TrimPrefix(line, "H: Handlers="), " ") {
|
||||
if strings.HasPrefix(handler, "event") {
|
||||
perip.path = filepath.Join(devfsPath, "input", handler)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if perip.path != "" {
|
||||
log.WithFields(logrus.Fields{
|
||||
"name": perip.name,
|
||||
"bus": perip.bus,
|
||||
"vendor": perip.vendor,
|
||||
"product": perip.product,
|
||||
"version": perip.version,
|
||||
"phys": perip.phys,
|
||||
"path": perip.path,
|
||||
}).Trace("found peripheral")
|
||||
ps = append(ps, perip)
|
||||
}
|
||||
}
|
||||
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
type linuxInputEvent struct {
|
||||
Secs uint32
|
||||
USecs uint32
|
||||
Type uint16
|
||||
Code uint16
|
||||
Value int32
|
||||
}
|
||||
|
||||
func (e linuxInputEvent) Time() time.Time {
|
||||
return time.Unix(int64(e.Secs), int64(e.USecs))
|
||||
}
|
||||
|
||||
func readLinuxInputEvents(name string, cb func(linuxInputEvent) error) error {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var raw linuxInputEvent
|
||||
for {
|
||||
if err := binary.Read(f, binary.LittleEndian, &raw); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if err := cb(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type linuxButton struct {
|
||||
p *linuxPheripheral
|
||||
}
|
||||
|
||||
func newLinuxButton(p *linuxPheripheral) *linuxButton {
|
||||
return &linuxButton{p: p}
|
||||
}
|
||||
|
||||
func (s *linuxButton) Name() string {
|
||||
return s.p.name
|
||||
}
|
||||
|
||||
func (s *linuxButton) Events() (<-chan Event, error) {
|
||||
log := logrus.
|
||||
WithField("input", "button").
|
||||
WithField("path", s.p.path)
|
||||
log.Debug("opening linux button source")
|
||||
|
||||
events := make(chan Event)
|
||||
go s.readEvents(events)
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (s *linuxButton) readEvents(events chan<- Event) {
|
||||
defer close(events)
|
||||
|
||||
log := logrus.
|
||||
WithField("input", "button").
|
||||
WithField("path", s.p.path)
|
||||
|
||||
err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error {
|
||||
log.WithField("data", ev).Debug("button event")
|
||||
|
||||
if ev.Code == 0 {
|
||||
return nil // not sure what this is
|
||||
}
|
||||
|
||||
var pressed bool
|
||||
if ev.Value == 1 {
|
||||
pressed = true
|
||||
}
|
||||
|
||||
select {
|
||||
case events <- NewButtonEvent(s, pressed):
|
||||
default:
|
||||
log.Warn("dropping event")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.WithError(err).Error("failed to read events")
|
||||
}
|
||||
}
|
||||
|
||||
type linuxRotary struct {
|
||||
p *linuxPheripheral
|
||||
}
|
||||
|
||||
func newLinuxRotary(p *linuxPheripheral) *linuxRotary {
|
||||
return &linuxRotary{p: p}
|
||||
}
|
||||
|
||||
func (s *linuxRotary) Name() string {
|
||||
return s.p.name
|
||||
}
|
||||
|
||||
func (s *linuxRotary) Events() (<-chan Event, error) {
|
||||
log := logrus.
|
||||
WithField("input", "rotary").
|
||||
WithField("path", s.p.path)
|
||||
log.Debug("opening linux rotary source")
|
||||
|
||||
events := make(chan Event)
|
||||
go s.readEvents(events)
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (s *linuxRotary) readEvents(events chan<- Event) {
|
||||
defer close(events)
|
||||
|
||||
log := logrus.
|
||||
WithField("input", "rotary").
|
||||
WithField("path", s.p.path)
|
||||
|
||||
err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error {
|
||||
log.WithField("data", ev).Debug("rotary event")
|
||||
|
||||
select {
|
||||
case events <- NewRotaryEvent(s, int(ev.Value), ev.Value == 0):
|
||||
default:
|
||||
log.Warn("dropping event")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.WithError(err).Error("failed to read events")
|
||||
}
|
||||
}
|
||||
|
||||
// Interface checks
|
||||
var (
|
||||
_ Source = (*linuxButton)(nil)
|
||||
)
|
||||
@@ -1,121 +0,0 @@
|
||||
package rotary
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"periph.io/x/conn/v3/gpio"
|
||||
)
|
||||
|
||||
type Rotary struct {
|
||||
s1, s2, key gpio.PinIO
|
||||
state [4]state
|
||||
}
|
||||
|
||||
func NewRotary(s1, s2, key gpio.PinIO) (*Rotary, error) {
|
||||
return &Rotary{
|
||||
s1: s1,
|
||||
s2: s2,
|
||||
key: key,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Rotary) log() *logrus.Entry {
|
||||
return logrus.WithField("input", "rotary")
|
||||
}
|
||||
|
||||
func (r *Rotary) Run(ctx context.Context) <-chan Event {
|
||||
r.s1.In(gpio.PullNoChange, gpio.BothEdges)
|
||||
r.s2.In(gpio.PullNoChange, gpio.BothEdges)
|
||||
|
||||
update := make(chan state)
|
||||
go r.waitForEdgeOnPin(ctx, r.s1, update)
|
||||
go r.waitForEdgeOnPin(ctx, r.s2, update)
|
||||
go r.waitForEdgeOnPin(ctx, r.key, update)
|
||||
|
||||
keys := make(chan Event)
|
||||
go r.process(ctx, update, keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func (r *Rotary) waitForEdgeOnPin(ctx context.Context, pin gpio.PinIO, update chan<- state) error {
|
||||
log := r.log().WithField("pin", pin.Name())
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Debug("context done")
|
||||
return ctx.Err()
|
||||
|
||||
default:
|
||||
log.Trace("waiting for edge")
|
||||
if !pin.WaitForEdge(-1) {
|
||||
log.Trace("wait for edge failed")
|
||||
continue
|
||||
}
|
||||
|
||||
level := pin.Read()
|
||||
|
||||
log.WithField("level", level).Trace("edge detected")
|
||||
update <- state{
|
||||
pin: pin,
|
||||
level: level,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Rotary) process(ctx context.Context, update <-chan state, keys chan<- Event) {
|
||||
log := r.log()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
|
||||
case newState := <-update:
|
||||
switch newState.pin {
|
||||
case r.key:
|
||||
if newState.level == gpio.High {
|
||||
log.Debug("key release detected")
|
||||
keys <- KeyRelease
|
||||
} else {
|
||||
log.Debug("key press detected")
|
||||
keys <- KeyPress
|
||||
}
|
||||
default:
|
||||
if newState == r.state[3] {
|
||||
continue
|
||||
}
|
||||
r.state = [4]state{
|
||||
r.state[1],
|
||||
r.state[2],
|
||||
r.state[3],
|
||||
newState,
|
||||
}
|
||||
if isCW(r.state) {
|
||||
log.Debug("clockwise rotation detected")
|
||||
keys <- Clockwise
|
||||
} else if isCCW(r.state) {
|
||||
log.Debug("counter clockwise rotation detected")
|
||||
keys <- CounterClockwise
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type state struct {
|
||||
pin gpio.PinIO
|
||||
level gpio.Level
|
||||
}
|
||||
|
||||
func stateEq(a, b [4]state) bool {
|
||||
return a[0].level == b[0].level && a[1].level == b[1].level && a[2].level == b[2].level && a[3].level == b[3].level
|
||||
}
|
||||
|
||||
func isCW(s [4]state) bool {
|
||||
return s[0].level == gpio.High && s[1].level == gpio.High && s[2].level == gpio.Low && s[3].level == gpio.Low
|
||||
}
|
||||
|
||||
func isCCW(s [4]state) bool {
|
||||
return s[0].level == gpio.High && s[1].level == gpio.Low && s[2].level == gpio.Low && s[3].level == gpio.High
|
||||
}
|
||||