Checkpoint
No files matched your search
@@ -0,0 +1,44 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
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,201 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
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,64 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
[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"
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
package main
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
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,179 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"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
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
configurationPath = append(makeConfigurationPath(), ".")
|
||||||
|
configurationFile string
|
||||||
|
configuration *config.Structure
|
||||||
|
logFile string
|
||||||
|
logDebug bool
|
||||||
|
logTrace bool
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var entrypoint = &cobra.Command{
|
||||||
|
Use: "harmon",
|
||||||
|
Short: "Harmon is a music player frontend for graphic displays",
|
||||||
|
Args: entrypointArgs,
|
||||||
|
Run: entrypoint,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
logrus.SetLevel(logrus.TraceLevel)
|
||||||
|
} else if logDebug {
|
||||||
|
logrus.SetLevel(logrus.DebugLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load configuration
|
||||||
|
if configurationFile == "" {
|
||||||
|
for _, dir := range configurationPath {
|
||||||
|
if dir, err = filepath.Abs(dir); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
signals := make(chan os.Signal)
|
||||||
|
signal.Notify(signals, os.Interrupt)
|
||||||
|
signal.Notify(signals, os.Kill)
|
||||||
|
|
||||||
|
fmt.Println("idling...")
|
||||||
|
for {
|
||||||
|
s := <-signals
|
||||||
|
logrus.WithField("signal", s.String()).Info("terminating")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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).
|
||||||
|
type Display struct {
|
||||||
|
Name string `hcl:"name,label"`
|
||||||
|
|
||||||
|
// Type of display.
|
||||||
|
Type string `hcl:"type"`
|
||||||
|
|
||||||
|
// Size of the display in pixels.
|
||||||
|
Size string `hcl:"size"`
|
||||||
|
|
||||||
|
// Bus is the I²C or SPI bus name.
|
||||||
|
Bus string `hcl:"bus,optional"`
|
||||||
|
|
||||||
|
// Address is the I²C address.
|
||||||
|
Address string `hcl:"addr,optional"`
|
||||||
|
|
||||||
|
// Frequency is the I²C or SPI bus frequency.
|
||||||
|
Freq string `hcl:"frequency,optional"`
|
||||||
|
|
||||||
|
// Reset is the reset pin.
|
||||||
|
Reset string `hcl:"reset,optional"`
|
||||||
|
|
||||||
|
// DC is the data/command pin.
|
||||||
|
DC string `hcl:"dc,optional"`
|
||||||
|
|
||||||
|
// CS is the chip select pin.
|
||||||
|
CS string `hcl:"cs,optional"`
|
||||||
|
|
||||||
|
// BL is the backlight pin.
|
||||||
|
BL string `hcl:"bl,optional"`
|
||||||
|
|
||||||
|
// Host name.
|
||||||
|
Host string `hcl:"host,optional"`
|
||||||
|
|
||||||
|
// Port name or number.
|
||||||
|
Port string `hcl:"port,optional"`
|
||||||
|
|
||||||
|
// Rotate the screen.
|
||||||
|
Rotate string `hcl:"rotate,optional"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Input configuration for the input devices.
|
||||||
|
type Input struct {
|
||||||
|
Name string `hcl:"name,label"`
|
||||||
|
Type string `hcl:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
Type string `hcl:"type"`
|
||||||
|
Config map[string]string `hcl:"config,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
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
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) {
|
||||||
|
log := logrus.WithField("path", name)
|
||||||
|
log.Debug("loading configuration")
|
||||||
|
|
||||||
|
source, err := os.ReadFile(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
config = new(Structure)
|
||||||
|
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() {
|
||||||
|
return nil, diag
|
||||||
|
}
|
||||||
|
|
||||||
|
if diag = gohcl.DecodeBody(file.Body, ctx, config); diag.HasErrors() {
|
||||||
|
return nil, diag
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExplainError(name string, err error) bool {
|
||||||
|
fmt.Printf("error type %T\n", err)
|
||||||
|
if diags, ok := err.(hcl.Diagnostics); ok {
|
||||||
|
for _, diag := range diags {
|
||||||
|
if diag.Subject != nil {
|
||||||
|
return explainSubject(diag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func explainSubject(diag *hcl.Diagnostic) bool {
|
||||||
|
if diag.Subject == nil || diag.Subject.Filename == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
source, err := os.ReadFile(diag.Subject.Filename)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Fatal error parsing %s:\n", diag.Subject)
|
||||||
|
lines := strings.Split(string(source), "\n")
|
||||||
|
start := diag.Subject.Start.Line - 3
|
||||||
|
if start < 0 {
|
||||||
|
start = 0
|
||||||
|
}
|
||||||
|
for line := start; line < diag.Subject.Start.Line; line++ {
|
||||||
|
fmt.Printf("%4d| %s\n", line+1, lines[line])
|
||||||
|
}
|
||||||
|
fmt.Print(" ...|")
|
||||||
|
if diag.Subject.Start.Column > 1 {
|
||||||
|
fmt.Print(strings.Repeat(" ", diag.Subject.Start.Column))
|
||||||
|
}
|
||||||
|
fmt.Print("^- ")
|
||||||
|
fmt.Println(diag.Summary + "\n")
|
||||||
|
fmt.Println(diag.Detail)
|
||||||
|
|
||||||
|
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,264 @@
|
|||||||
|
package lcdproc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/textproto"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.maze.io/go/bragi/config"
|
||||||
|
"git.maze.io/go/bragi/display"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultPort = "13666"
|
||||||
|
DefaultAddr = "localhost:" + DefaultPort
|
||||||
|
screenName = "bragi"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
Version string
|
||||||
|
ProtocolVersion string
|
||||||
|
|
||||||
|
addr string
|
||||||
|
conn *textproto.Conn
|
||||||
|
width, height int
|
||||||
|
cellWidth, cellHeight int
|
||||||
|
text [][]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(config *config.Display) (display.Text, error) {
|
||||||
|
var (
|
||||||
|
addr, host, port string
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if host = config.Host; host == "" {
|
||||||
|
host = "localhost"
|
||||||
|
}
|
||||||
|
if port = config.Port; port == "" {
|
||||||
|
port = DefaultPort
|
||||||
|
}
|
||||||
|
addr = net.JoinHostPort(host, port)
|
||||||
|
|
||||||
|
log := logrus.WithFields(logrus.Fields{
|
||||||
|
"driver": "lcdproc",
|
||||||
|
"addr": addr,
|
||||||
|
})
|
||||||
|
log.Debug("connecting to server")
|
||||||
|
|
||||||
|
conn, err := textproto.Dial("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &Client{
|
||||||
|
addr: addr,
|
||||||
|
conn: conn,
|
||||||
|
}
|
||||||
|
if err = c.hello(log); err != nil {
|
||||||
|
_ = conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = c.setup(log); err != nil {
|
||||||
|
_ = conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c.text = make([][]byte, c.height)
|
||||||
|
for i := 0; i < c.height; i++ {
|
||||||
|
c.text[i] = make([]byte, c.width)
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) hello(log *logrus.Entry) (err error) {
|
||||||
|
log.Trace("sending hello")
|
||||||
|
var id uint
|
||||||
|
if id, err = c.conn.Cmd("hello"); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.conn.StartResponse(id)
|
||||||
|
defer c.conn.EndResponse(id)
|
||||||
|
|
||||||
|
var line string
|
||||||
|
if line, err = c.conn.ReadLine(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.WithFields(logrus.Fields{
|
||||||
|
"data": line,
|
||||||
|
"id": id,
|
||||||
|
}).Trace("recieved response")
|
||||||
|
|
||||||
|
var parts = strings.Split(line, " ")
|
||||||
|
for i := 0; i < len(parts); i++ {
|
||||||
|
switch part := parts[i]; part {
|
||||||
|
case "connect":
|
||||||
|
i++ // ignore "LCDproc"
|
||||||
|
c.Version = parts[i]
|
||||||
|
i++
|
||||||
|
log.Debugf("received version %s", c.Version)
|
||||||
|
case "protocol":
|
||||||
|
i++
|
||||||
|
c.ProtocolVersion = parts[i]
|
||||||
|
log.Debugf("received protocol version %s", c.ProtocolVersion)
|
||||||
|
case "lcd": // ignore
|
||||||
|
case "wid":
|
||||||
|
i++
|
||||||
|
c.width, _ = strconv.Atoi(parts[i])
|
||||||
|
case "hgt":
|
||||||
|
i++
|
||||||
|
c.height, _ = strconv.Atoi(parts[i])
|
||||||
|
case "cellwid":
|
||||||
|
i++
|
||||||
|
c.cellWidth, _ = strconv.Atoi(parts[i])
|
||||||
|
case "cellhgt":
|
||||||
|
i++
|
||||||
|
c.cellHeight, _ = strconv.Atoi(parts[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugf("%dx%d display", c.width*c.cellWidth, c.height*c.cellHeight)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) setup(log *logrus.Entry) (err error) {
|
||||||
|
if err = c.sendCommand("client_set -name Bragi"); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = c.fireCommand("screen_del %s", screenName); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = c.fireCommand("screen_add %s", screenName); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = c.sendCommand("screen_set %s -cursor off -heartbeat off -priority foreground -duration -wid %d -hgt %d", screenName, c.width, c.height); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for y := 0; y < c.height; y++ {
|
||||||
|
if err = c.sendCommand("widget_add %s row%d string", screenName, y); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) log() *logrus.Entry {
|
||||||
|
return logrus.WithFields(logrus.Fields{
|
||||||
|
"driver": "lcdproc",
|
||||||
|
"addr": c.addr,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendCommand(format string, args ...interface{}) (err error) {
|
||||||
|
log := c.log().WithField("command", fmt.Sprintf(format, args...))
|
||||||
|
log.Debug("sending command")
|
||||||
|
|
||||||
|
var id uint
|
||||||
|
if id, err = c.conn.Cmd(format, args...); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.conn.StartResponse(id)
|
||||||
|
defer c.conn.EndResponse(id)
|
||||||
|
|
||||||
|
log = log.WithField("id", id)
|
||||||
|
log.Trace("reading response")
|
||||||
|
for {
|
||||||
|
var line string
|
||||||
|
if line, err = c.conn.ReadLine(); err != nil {
|
||||||
|
log.WithError(err).Error("error reading response")
|
||||||
|
c.conn.EndResponse(id)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.WithField("data", line).Trace("response")
|
||||||
|
switch {
|
||||||
|
case line == "success":
|
||||||
|
return
|
||||||
|
case strings.HasPrefix(line, "huh? "):
|
||||||
|
return textproto.ProtocolError(line[5:])
|
||||||
|
case strings.HasPrefix(line, "listen "):
|
||||||
|
continue
|
||||||
|
case strings.HasPrefix(line, "ignore "):
|
||||||
|
continue
|
||||||
|
default:
|
||||||
|
return textproto.ProtocolError("unexpected response: " + line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) fireCommand(format string, args ...interface{}) (err error) {
|
||||||
|
log := c.log().WithField("command", fmt.Sprintf(format, args...))
|
||||||
|
log.Debug("sending command")
|
||||||
|
|
||||||
|
var id uint
|
||||||
|
if id, err = c.conn.Cmd(format, args...); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.conn.StartResponse(id)
|
||||||
|
defer c.conn.EndResponse(id)
|
||||||
|
|
||||||
|
log = log.WithField("id", id)
|
||||||
|
log.Trace("reading response")
|
||||||
|
for {
|
||||||
|
var line string
|
||||||
|
if line, err = c.conn.ReadLine(); err != nil {
|
||||||
|
log.WithError(err).Error("error reading response")
|
||||||
|
c.conn.EndResponse(id)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.WithField("data", line).Trace("response")
|
||||||
|
switch {
|
||||||
|
case line == "success":
|
||||||
|
return
|
||||||
|
case strings.HasPrefix(line, "huh? "):
|
||||||
|
return
|
||||||
|
case strings.HasPrefix(line, "listen "):
|
||||||
|
continue
|
||||||
|
case strings.HasPrefix(line, "ignore "):
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) String() string {
|
||||||
|
return fmt.Sprintf("lcdproc %s at %s", c.Version, c.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Columns() int {
|
||||||
|
return c.width
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Rows() int {
|
||||||
|
return c.height
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Halt() error {
|
||||||
|
return c.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (Client) Refresh() error { return nil }
|
||||||
|
|
||||||
|
func (c *Client) Size() (w, h int) {
|
||||||
|
return c.width * c.cellWidth, c.height * c.cellHeight
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Text(x, y int, message string) {
|
||||||
|
w := len(message)
|
||||||
|
if x+w > c.width {
|
||||||
|
message = message[:c.width-x]
|
||||||
|
}
|
||||||
|
_ = c.fireCommand("widget_set %s main %d %d %q", screenName, x+1, y+1, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("lcdproc", func(config *config.Display) (display.Display, error) {
|
||||||
|
return New(config)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package sdl
|
||||||
|
|
||||||
|
import "git.maze.io/go/harmon/input"
|
||||||
|
|
||||||
|
type keyboardInput struct {
|
||||||
|
//events chan *sdl.KeyboardEvent
|
||||||
|
events chan input.Event
|
||||||
|
}
|
||||||
|
|
||||||
|
func newKeyboardInput() *keyboardInput {
|
||||||
|
return &keyboardInput{
|
||||||
|
events: make(chan input.Event),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (keyboardInput) Name() string {
|
||||||
|
return "keyboard"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k *keyboardInput) Events() (<-chan input.Event, error) {
|
||||||
|
return k.events, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package sdl
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/veandco/go-sdl2/sdl"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/input"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
initOnce sync.Once
|
||||||
|
initTime time.Time
|
||||||
|
quitOnce sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
type Device struct {
|
||||||
|
window *sdl.Window
|
||||||
|
surface *sdl.Surface
|
||||||
|
keyboardInput *keyboardInput
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() (*Device, error) {
|
||||||
|
var err error
|
||||||
|
initOnce.Do(func() {
|
||||||
|
err = sdl.Init(sdl.INIT_EVERYTHING)
|
||||||
|
if err == nil {
|
||||||
|
initTime = time.Now()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
b int32 = 32
|
||||||
|
w int32 = 256
|
||||||
|
h int32 = 32
|
||||||
|
)
|
||||||
|
|
||||||
|
window, err := sdl.CreateWindow("Bragi OLED emulator",
|
||||||
|
sdl.WINDOWPOS_UNDEFINED,
|
||||||
|
sdl.WINDOWPOS_UNDEFINED,
|
||||||
|
w+2*b,
|
||||||
|
h+2*b,
|
||||||
|
sdl.WINDOW_SHOWN)
|
||||||
|
if err != nil {
|
||||||
|
sdl.Quit()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
surface, err := window.GetSurface()
|
||||||
|
if err != nil {
|
||||||
|
_ = window.Destroy()
|
||||||
|
sdl.Quit()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
surface.FillRect(nil, 0)
|
||||||
|
|
||||||
|
surface.FillRect(&sdl.Rect{0, 0, b + b + w, b + b + h}, sdl.MapRGBA(surface.Format, 128, 64, 0, 255))
|
||||||
|
surface.FillRect(&sdl.Rect{b, b, w, h}, sdl.MapRGBA(surface.Format, 255, 128, 0, 255))
|
||||||
|
window.UpdateSurface()
|
||||||
|
|
||||||
|
d := &Device{
|
||||||
|
window: window,
|
||||||
|
surface: surface,
|
||||||
|
keyboardInput: newKeyboardInput(),
|
||||||
|
}
|
||||||
|
|
||||||
|
input.Register(func() ([]input.Source, error) {
|
||||||
|
return []input.Source{
|
||||||
|
d.keyboardInput,
|
||||||
|
}, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Close() error {
|
||||||
|
err := d.window.Destroy()
|
||||||
|
quitOnce.Do(sdl.Quit)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Run() error {
|
||||||
|
for running := true; running; {
|
||||||
|
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
|
||||||
|
switch event := event.(type) {
|
||||||
|
case *sdl.QuitEvent:
|
||||||
|
running = false
|
||||||
|
break
|
||||||
|
|
||||||
|
case *sdl.KeyboardEvent:
|
||||||
|
d.handleKeyboardEvent(event)
|
||||||
|
|
||||||
|
case *sdl.MouseMotionEvent:
|
||||||
|
//select {
|
||||||
|
//case d.mouseMotionEvents <- event:
|
||||||
|
//default:
|
||||||
|
//}
|
||||||
|
|
||||||
|
default:
|
||||||
|
log.Printf("SDL event: %T", event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return d.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) handleKeyboardEvent(event *sdl.KeyboardEvent) {
|
||||||
|
/*
|
||||||
|
var kind input.EventType
|
||||||
|
switch event.Type {
|
||||||
|
case sdl.KEYDOWN:
|
||||||
|
kind = input.KeyPress
|
||||||
|
case sdl.KEYUP:
|
||||||
|
kind = input.KeyRelease
|
||||||
|
}
|
||||||
|
d.keyboardInput.events <- input.Event{
|
||||||
|
Type: kind,
|
||||||
|
Time: initTime.Add(time.Duration(event.Timestamp) * time.Second),
|
||||||
|
Code: int(event.Keysym.Sym),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package ssd1306
|
||||||
|
|
||||||
|
import "git.maze.io/go/harmon/display"
|
||||||
|
|
||||||
|
// Registers
|
||||||
|
const (
|
||||||
|
Address = 0x3D
|
||||||
|
Address_128_32 = 0x3C
|
||||||
|
|
||||||
|
SETCONTRAST = 0x81
|
||||||
|
DISPLAYALLON_RESUME = 0xA4
|
||||||
|
DISPLAYALLON = 0xA5
|
||||||
|
NORMALDISPLAY = 0xA6
|
||||||
|
INVERTDISPLAY = 0xA7
|
||||||
|
DISPLAYOFF = 0xAE
|
||||||
|
DISPLAYON = 0xAF
|
||||||
|
SETDISPLAYOFFSET = 0xD3
|
||||||
|
SETCOMPINS = 0xDA
|
||||||
|
SETVCOMDETECT = 0xDB
|
||||||
|
SETDISPLAYCLOCKDIV = 0xD5
|
||||||
|
SETPRECHARGE = 0xD9
|
||||||
|
SETMULTIPLEX = 0xA8
|
||||||
|
SETLOWCOLUMN = 0x00
|
||||||
|
SETHIGHCOLUMN = 0x10
|
||||||
|
SETSTARTLINE = 0x40
|
||||||
|
MEMORYMODE = 0x20
|
||||||
|
COLUMNADDR = 0x21
|
||||||
|
PAGEADDR = 0x22
|
||||||
|
COMSCANINC = 0xC0
|
||||||
|
COMSCANDEC = 0xC8
|
||||||
|
SEGREMAP = 0xA0
|
||||||
|
CHARGEPUMP = 0x8D
|
||||||
|
ACTIVATE_SCROLL = 0x2F
|
||||||
|
DEACTIVATE_SCROLL = 0x2E
|
||||||
|
SET_VERTICAL_SCROLL_AREA = 0xA3
|
||||||
|
RIGHT_HORIZONTAL_SCROLL = 0x26
|
||||||
|
LEFT_HORIZONTAL_SCROLL = 0x27
|
||||||
|
VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29
|
||||||
|
VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A
|
||||||
|
|
||||||
|
EXTERNALVCC VccMode = 0x1
|
||||||
|
SWITCHCAPVCC VccMode = 0x2
|
||||||
|
|
||||||
|
NO_ROTATION = display.NoRotation
|
||||||
|
ROTATION_180 = display.Rotate180
|
||||||
|
)
|
||||||
@@ -0,0 +1,411 @@
|
|||||||
|
package ssd1306
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/draw"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/display/oled"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("ssd1306", newDevice)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
errBufferSize = errors.New("invalid size buffer")
|
||||||
|
errOutOfRange = errors.New("out of screen range")
|
||||||
|
)
|
||||||
|
|
||||||
|
type ResetValue [2]byte
|
||||||
|
|
||||||
|
// Device wraps I2C or SPI connection.
|
||||||
|
type Device struct {
|
||||||
|
bus oled.Bus
|
||||||
|
buffer pixel.Image[pixel.Monochrome]
|
||||||
|
width int16
|
||||||
|
height int16
|
||||||
|
bufferSize int16
|
||||||
|
vccState VccMode
|
||||||
|
canReset bool
|
||||||
|
resetCol ResetValue
|
||||||
|
resetPage ResetValue
|
||||||
|
rotation display.Rotation
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config is the configuration for the display
|
||||||
|
type Config struct {
|
||||||
|
Width int16
|
||||||
|
Height int16
|
||||||
|
VccState VccMode
|
||||||
|
//Address uint16
|
||||||
|
// ResetCol and ResetPage are used to reset the screen to 0x0
|
||||||
|
// This is useful for some screens that have a different size than 128x64
|
||||||
|
// For example, the Thumby's screen is 72x40
|
||||||
|
// The default values are normally set automatically based on the size.
|
||||||
|
// If you're using a different size, you might need to set these values manually.
|
||||||
|
ResetCol ResetValue
|
||||||
|
ResetPage ResetValue
|
||||||
|
Rotation display.Rotation
|
||||||
|
}
|
||||||
|
|
||||||
|
type VccMode uint8
|
||||||
|
|
||||||
|
func newDevice(config *config.Display) (display.Display, error) {
|
||||||
|
width, height, err := display.ParseSize(config.Size, 128, 0)
|
||||||
|
if err != nil || height == 0 {
|
||||||
|
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rotation, err := display.ParseRotation(config.Rotate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bus, err := oled.NewBus(config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := &Device{
|
||||||
|
bus: bus,
|
||||||
|
}
|
||||||
|
if err = d.Configure(Config{
|
||||||
|
Width: int16(width),
|
||||||
|
Height: int16(height),
|
||||||
|
Rotation: rotation,
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure initializes the display with default configuration
|
||||||
|
func (d *Device) Configure(cfg Config) error {
|
||||||
|
var zeroReset ResetValue
|
||||||
|
if cfg.Width != 0 {
|
||||||
|
d.width = cfg.Width
|
||||||
|
} else {
|
||||||
|
d.width = 128
|
||||||
|
}
|
||||||
|
if cfg.Height != 0 {
|
||||||
|
d.height = cfg.Height
|
||||||
|
} else {
|
||||||
|
d.height = 64
|
||||||
|
}
|
||||||
|
if cfg.VccState != 0 {
|
||||||
|
d.vccState = cfg.VccState
|
||||||
|
} else {
|
||||||
|
d.vccState = SWITCHCAPVCC
|
||||||
|
}
|
||||||
|
if cfg.ResetCol != zeroReset {
|
||||||
|
d.resetCol = cfg.ResetCol
|
||||||
|
} else {
|
||||||
|
d.resetCol = ResetValue{0, uint8(d.width - 1)}
|
||||||
|
}
|
||||||
|
if cfg.ResetPage != zeroReset {
|
||||||
|
d.resetPage = cfg.ResetPage
|
||||||
|
} else {
|
||||||
|
d.resetPage = ResetValue{0, uint8(d.height/8) - 1}
|
||||||
|
}
|
||||||
|
d.bufferSize = d.width * d.height / 8
|
||||||
|
d.buffer = pixel.NewImage[pixel.Monochrome](int(d.width), int(d.height))
|
||||||
|
//d.buffer = make([]byte, d.bufferSize)
|
||||||
|
//d.canReset = cfg.Address != 0 || d.width != 128 || d.height != 64 // I2C or not 128x64
|
||||||
|
|
||||||
|
time.Sleep(100 * time.Nanosecond)
|
||||||
|
d.Command(DISPLAYOFF)
|
||||||
|
d.Command(SETDISPLAYCLOCKDIV)
|
||||||
|
d.Command(0x80)
|
||||||
|
d.Command(SETMULTIPLEX)
|
||||||
|
d.Command(uint8(d.height - 1))
|
||||||
|
d.Command(SETDISPLAYOFFSET)
|
||||||
|
d.Command(0x0)
|
||||||
|
d.Command(SETSTARTLINE | 0x0)
|
||||||
|
d.Command(CHARGEPUMP)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x10)
|
||||||
|
} else {
|
||||||
|
d.Command(0x14)
|
||||||
|
}
|
||||||
|
d.Command(MEMORYMODE)
|
||||||
|
d.Command(0x00)
|
||||||
|
|
||||||
|
d.SetRotation(cfg.Rotation)
|
||||||
|
|
||||||
|
if (d.width == 128 && d.height == 64) || (d.width == 64 && d.height == 48) { // 128x64 or 64x48
|
||||||
|
d.Command(SETCOMPINS)
|
||||||
|
d.Command(0x12)
|
||||||
|
d.Command(SETCONTRAST)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x9F)
|
||||||
|
} else {
|
||||||
|
d.Command(0xCF)
|
||||||
|
}
|
||||||
|
} else if d.width == 128 && d.height == 32 { // 128x32
|
||||||
|
d.Command(SETCOMPINS)
|
||||||
|
d.Command(0x02)
|
||||||
|
d.Command(SETCONTRAST)
|
||||||
|
d.Command(0x8F)
|
||||||
|
} else if d.width == 96 && d.height == 16 { // 96x16
|
||||||
|
d.Command(SETCOMPINS)
|
||||||
|
d.Command(0x2)
|
||||||
|
d.Command(SETCONTRAST)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x10)
|
||||||
|
} else {
|
||||||
|
d.Command(0xAF)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// fail silently, it might work
|
||||||
|
println("there's no configuration for this display's size")
|
||||||
|
}
|
||||||
|
|
||||||
|
d.Command(SETPRECHARGE)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x22)
|
||||||
|
} else {
|
||||||
|
d.Command(0xF1)
|
||||||
|
}
|
||||||
|
d.Command(SETVCOMDETECT)
|
||||||
|
d.Command(0x40)
|
||||||
|
d.Command(DISPLAYALLON_RESUME)
|
||||||
|
d.Command(NORMALDISPLAY)
|
||||||
|
d.Command(DEACTIVATE_SCROLL)
|
||||||
|
return d.Command(DISPLAYON)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearBuffer clears the image buffer
|
||||||
|
func (d *Device) ClearBuffer() {
|
||||||
|
/*
|
||||||
|
for i := int16(0); i < d.bufferSize; i++ {
|
||||||
|
d.buffer[i] = 0
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
d.buffer.Clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearDisplay clears the image buffer and clear the display
|
||||||
|
func (d *Device) ClearDisplay() error {
|
||||||
|
d.ClearBuffer()
|
||||||
|
return d.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh sends the whole buffer to the screen
|
||||||
|
func (d *Device) Refresh() error {
|
||||||
|
// Reset the screen to 0x0
|
||||||
|
// This works fine with I2C
|
||||||
|
// In the 128x64 (SPI) screen resetting to 0x0 after 128 times corrupt the buffer
|
||||||
|
// Since we're printing the whole buffer, avoid resetting it in this case
|
||||||
|
if d.canReset {
|
||||||
|
d.Command(COLUMNADDR)
|
||||||
|
d.Command(d.resetCol[0])
|
||||||
|
d.Command(d.resetCol[1])
|
||||||
|
d.Command(PAGEADDR)
|
||||||
|
d.Command(d.resetPage[0])
|
||||||
|
d.Command(d.resetPage[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.Tx(d.buffer.RawBuffer(), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPixel enables or disables a pixel in the buffer
|
||||||
|
// color.RGBA{0, 0, 0, 255} is consider transparent, anything else
|
||||||
|
// with enable a pixel on the screen
|
||||||
|
func (d *Device) SetPixel(x int16, y int16, c pixel.Monochrome) {
|
||||||
|
if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 {
|
||||||
|
x, y = y, x
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
byteIndex := x + (y/8)*d.width
|
||||||
|
if c == pixel.Off {
|
||||||
|
d.buffer[byteIndex] &^= 1 << uint8(y%8)
|
||||||
|
} else {
|
||||||
|
d.buffer[byteIndex] |= 1 << uint8(y%8)
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
d.buffer.SetPixel(int(x), int(y), c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPixel returns if the specified pixel is on (true) or off (false)
|
||||||
|
func (d *Device) GetPixel(x int16, y int16) pixel.Monochrome {
|
||||||
|
if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 {
|
||||||
|
x, y = y, x
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
byteIndex := x + (y/8)*d.width
|
||||||
|
return (d.buffer[byteIndex] >> uint8(y%8) & 0x1) == 1
|
||||||
|
*/
|
||||||
|
return d.buffer.GetPixel(int(x), int(y))
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// SetBuffer changes the whole buffer at once
|
||||||
|
func (d *Device) SetBuffer(buffer []byte) error {
|
||||||
|
if int16(len(buffer)) != d.bufferSize {
|
||||||
|
return errBufferSize
|
||||||
|
}
|
||||||
|
for i := int16(0); i < d.bufferSize; i++ {
|
||||||
|
d.buffer[i] = buffer[i]
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
// GetBuffer returns the whole buffer
|
||||||
|
func (d *Device) GetBuffer() []byte {
|
||||||
|
return d.buffer.RawBuffer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command sends a command to the display
|
||||||
|
func (d *Device) Command(command uint8) error {
|
||||||
|
return d.bus.Tx([]byte{command}, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tx sends data to the display
|
||||||
|
func (d *Device) Tx(data []byte, isCommand bool) error {
|
||||||
|
return d.bus.Tx(data, isCommand)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the current size of the display.
|
||||||
|
func (d *Device) Size16() (w, h int16) {
|
||||||
|
return d.width, d.height
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawBitmap copies the bitmap to the screen at the given coordinates.
|
||||||
|
func (d *Device) DrawBitmap(x, y int16, bitmap pixel.Image[pixel.Monochrome]) error {
|
||||||
|
width, height := bitmap.Size()
|
||||||
|
if x < 0 || x+int16(width) > d.width || y < 0 || y+int16(height) > d.height {
|
||||||
|
return errOutOfRange
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < width; i++ {
|
||||||
|
for j := 0; j < height; j++ {
|
||||||
|
d.SetPixel(x+int16(i), y+int16(j), bitmap.GetPixel(i, j))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotation returns the currently configured rotation.
|
||||||
|
func (d *Device) Rotation() display.Rotation {
|
||||||
|
return d.rotation
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRotation changes the rotation of the device (clock-wise).
|
||||||
|
func (d *Device) SetRotation(rotation display.Rotation) error {
|
||||||
|
d.rotation = rotation
|
||||||
|
switch d.rotation {
|
||||||
|
case display.NoRotation:
|
||||||
|
d.Command(SEGREMAP | 0x1) // Reverse horizontal mapping
|
||||||
|
d.Command(COMSCANDEC) // Reverse vertical mapping
|
||||||
|
case display.Rotate180:
|
||||||
|
d.Command(SEGREMAP) // Normal horizontal mapping
|
||||||
|
d.Command(COMSCANINC) // Normal vertical mapping
|
||||||
|
// nothing to do
|
||||||
|
default:
|
||||||
|
d.Command(SEGREMAP | 0x1) // Reverse horizontal mapping
|
||||||
|
d.Command(COMSCANDEC) // Reverse vertical mapping
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the sleep mode for this display. When sleeping, the panel uses a lot
|
||||||
|
// less power. The display won't show an image anymore, but the memory contents
|
||||||
|
// should be kept.
|
||||||
|
func (d *Device) Sleep(sleepEnabled bool) error {
|
||||||
|
if sleepEnabled {
|
||||||
|
d.Command(DISPLAYOFF)
|
||||||
|
} else {
|
||||||
|
d.Command(DISPLAYON)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillRectangle fills a rectangle at a given coordinates with a color
|
||||||
|
func (d *Device) FillRectangle(x, y, width, height int16, c pixel.Monochrome) error {
|
||||||
|
dw, dh := d.Size16()
|
||||||
|
|
||||||
|
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||||
|
x >= d.width || (x+width) > dw || y >= dh || (y+height) > dh {
|
||||||
|
return errOutOfRange
|
||||||
|
}
|
||||||
|
|
||||||
|
if x+width == dw && y+height == dh && c == pixel.Off {
|
||||||
|
d.ClearDisplay()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := x; i < x+width; i++ {
|
||||||
|
for j := y; j < y+height; j++ {
|
||||||
|
d.SetPixel(i, j, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetScroll sets the vertical scrolling for the display, which is a NOP for this display.
|
||||||
|
func (d *Device) SetScroll(line int16) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
/* draw.Image interface */
|
||||||
|
|
||||||
|
func (d *Device) At(x, y int) color.Color {
|
||||||
|
return d.GetPixel(int16(x), int16(y))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Bounds() image.Rectangle {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
return image.Rect(0, 0, int(d.height), int(d.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) ColorModel() color.Model {
|
||||||
|
return pixel.MonochromeModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Set(x, y int, c color.Color) {
|
||||||
|
c = pixel.MonochromeModel.Convert(c)
|
||||||
|
d.SetPixel(int16(x), int16(y), c.(pixel.Monochrome))
|
||||||
|
}
|
||||||
|
|
||||||
|
/* display.Image interface */
|
||||||
|
|
||||||
|
func (d *Device) Halt() error {
|
||||||
|
return d.bus.Halt()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Size() image.Point {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
return image.Pt(int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
return image.Pt(int(d.height), int(d.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) String() string {
|
||||||
|
return fmt.Sprintf("ssd1306:%dx%d", d.width, d.height)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* display.imageDrawer interface */
|
||||||
|
|
||||||
|
func (d *Device) DrawImage(img image.Image) error {
|
||||||
|
draw.Draw(d.buffer, d.buffer.Bounds(), img, image.Point{}, draw.Src)
|
||||||
|
return d.Refresh()
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package st7789
|
||||||
|
|
||||||
|
type FrameRate uint8
|
||||||
|
|
||||||
|
// Registers
|
||||||
|
const (
|
||||||
|
NOP = 0x00
|
||||||
|
SWRESET = 0x01
|
||||||
|
RDDID = 0x04
|
||||||
|
RDDST = 0x09
|
||||||
|
SLPIN = 0x10
|
||||||
|
SLPOUT = 0x11
|
||||||
|
PTLON = 0x12
|
||||||
|
NORON = 0x13
|
||||||
|
INVOFF = 0x20
|
||||||
|
INVON = 0x21
|
||||||
|
DISPOFF = 0x28
|
||||||
|
DISPON = 0x29
|
||||||
|
CASET = 0x2A
|
||||||
|
RASET = 0x2B
|
||||||
|
RAMWR = 0x2C
|
||||||
|
RAMRD = 0x2E
|
||||||
|
PTLAR = 0x30
|
||||||
|
COLMOD = 0x3A
|
||||||
|
MADCTL = 0x36
|
||||||
|
MADCTL_MY = 0x80
|
||||||
|
MADCTL_MX = 0x40
|
||||||
|
MADCTL_MV = 0x20
|
||||||
|
MADCTL_ML = 0x10
|
||||||
|
MADCTL_RGB = 0x00
|
||||||
|
MADCTL_BGR = 0x08
|
||||||
|
MADCTL_MH = 0x04
|
||||||
|
RDID1 = 0xDA
|
||||||
|
RDID2 = 0xDB
|
||||||
|
RDID3 = 0xDC
|
||||||
|
RDID4 = 0xDD
|
||||||
|
FRMCTR1 = 0xB1
|
||||||
|
RGBCTRL = 0xB1
|
||||||
|
FRMCTR2 = 0xB2
|
||||||
|
PORCTRL = 0xB2
|
||||||
|
FRMCTR3 = 0xB3
|
||||||
|
INVCTR = 0xB4
|
||||||
|
DISSET5 = 0xB6
|
||||||
|
PWCTR1 = 0xC0
|
||||||
|
PWCTR2 = 0xC1
|
||||||
|
PWCTR3 = 0xC2
|
||||||
|
PWCTR4 = 0xC3
|
||||||
|
PWCTR5 = 0xC4
|
||||||
|
VMCTR1 = 0xC5
|
||||||
|
FRCTRL2 = 0xC6
|
||||||
|
PWCTR6 = 0xFC
|
||||||
|
GMCTRP1 = 0xE0
|
||||||
|
GMCTRN1 = 0xE1
|
||||||
|
GSCAN = 0x45
|
||||||
|
|
||||||
|
// Allowable frame rate codes for FRCTRL2 (Identifier is in Hz)
|
||||||
|
FRAMERATE_111 FrameRate = 0x01
|
||||||
|
FRAMERATE_105 FrameRate = 0x02
|
||||||
|
FRAMERATE_99 FrameRate = 0x03
|
||||||
|
FRAMERATE_94 FrameRate = 0x04
|
||||||
|
FRAMERATE_90 FrameRate = 0x05
|
||||||
|
FRAMERATE_86 FrameRate = 0x06
|
||||||
|
FRAMERATE_82 FrameRate = 0x07
|
||||||
|
FRAMERATE_78 FrameRate = 0x08
|
||||||
|
FRAMERATE_75 FrameRate = 0x09
|
||||||
|
FRAMERATE_72 FrameRate = 0x0A
|
||||||
|
FRAMERATE_69 FrameRate = 0x0B
|
||||||
|
FRAMERATE_67 FrameRate = 0x0C
|
||||||
|
FRAMERATE_64 FrameRate = 0x0D
|
||||||
|
FRAMERATE_62 FrameRate = 0x0E
|
||||||
|
FRAMERATE_60 FrameRate = 0x0F // 60 is default
|
||||||
|
FRAMERATE_58 FrameRate = 0x10
|
||||||
|
FRAMERATE_57 FrameRate = 0x11
|
||||||
|
FRAMERATE_55 FrameRate = 0x12
|
||||||
|
FRAMERATE_53 FrameRate = 0x13
|
||||||
|
FRAMERATE_52 FrameRate = 0x14
|
||||||
|
FRAMERATE_50 FrameRate = 0x15
|
||||||
|
FRAMERATE_49 FrameRate = 0x16
|
||||||
|
FRAMERATE_48 FrameRate = 0x17
|
||||||
|
FRAMERATE_46 FrameRate = 0x18
|
||||||
|
FRAMERATE_45 FrameRate = 0x19
|
||||||
|
FRAMERATE_44 FrameRate = 0x1A
|
||||||
|
FRAMERATE_43 FrameRate = 0x1B
|
||||||
|
FRAMERATE_42 FrameRate = 0x1C
|
||||||
|
FRAMERATE_41 FrameRate = 0x1D
|
||||||
|
FRAMERATE_40 FrameRate = 0x1E
|
||||||
|
FRAMERATE_39 FrameRate = 0x1F
|
||||||
|
|
||||||
|
MAX_VSYNC_SCANLINES = 254
|
||||||
|
)
|
||||||
@@ -0,0 +1,535 @@
|
|||||||
|
package st7789
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"math"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
"periph.io/x/conn/v3/spi/spireg"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("st7789", newDevice)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Device struct {
|
||||||
|
conn spi.Conn
|
||||||
|
reset, cs, dc, bl gpio.PinOut
|
||||||
|
width int16
|
||||||
|
height int16
|
||||||
|
columnOffsetCfg int16
|
||||||
|
rowOffsetCfg int16
|
||||||
|
columnOffset int16
|
||||||
|
rowOffset int16
|
||||||
|
rotation display.Rotation
|
||||||
|
frameRate FrameRate
|
||||||
|
batchLength int32
|
||||||
|
isBGR bool
|
||||||
|
vSyncLines int16
|
||||||
|
}
|
||||||
|
|
||||||
|
type Opts struct {
|
||||||
|
Width int16
|
||||||
|
Height int16
|
||||||
|
Rotation display.Rotation
|
||||||
|
RowOffset int16
|
||||||
|
ColumnOffset int16
|
||||||
|
FrameRate FrameRate
|
||||||
|
VSyncLines int16
|
||||||
|
}
|
||||||
|
|
||||||
|
var DefaultOpts = Opts{
|
||||||
|
Width: 240,
|
||||||
|
Height: 320,
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDevice(config *config.Display) (display.Display, error) {
|
||||||
|
log := logrus.WithFields(logrus.Fields{
|
||||||
|
"type": "st7789",
|
||||||
|
"name": config.Name,
|
||||||
|
})
|
||||||
|
|
||||||
|
log.WithField("port", config.Port).Trace("opening SPI port")
|
||||||
|
port, err := spireg.Open(config.Port)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
bits = 8
|
||||||
|
reset gpio.PinOut
|
||||||
|
dc gpio.PinOut
|
||||||
|
cs gpio.PinOut
|
||||||
|
bl gpio.PinOut
|
||||||
|
)
|
||||||
|
if config.DC == "" {
|
||||||
|
bits = 9
|
||||||
|
} else {
|
||||||
|
if dc, err = display.LookupPinOut(config.DC); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid dc pin: %w", err)
|
||||||
|
}
|
||||||
|
if err = dc.Out(gpio.Low); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reset, err = display.LookupPinOut(config.Reset); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid reset pin: %w", err)
|
||||||
|
}
|
||||||
|
if cs, err = display.LookupPinOut(config.CS); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid cs pin: %w", err)
|
||||||
|
}
|
||||||
|
if bl, err = display.LookupPinOut(config.BL); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid bl pin: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.WithFields(logrus.Fields{
|
||||||
|
"mode": spi.Mode0,
|
||||||
|
"bits": bits,
|
||||||
|
"reset": reset.Name(),
|
||||||
|
"dc": dc.Name(),
|
||||||
|
"cs": cs.Name(),
|
||||||
|
"bl": bl.Name(),
|
||||||
|
}).Debug("connecting on SPI port")
|
||||||
|
conn, err := port.Connect(300*physic.KiloHertz, spi.Mode0, bits)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := &Device{
|
||||||
|
conn: conn,
|
||||||
|
reset: reset,
|
||||||
|
cs: cs,
|
||||||
|
dc: dc,
|
||||||
|
bl: bl,
|
||||||
|
}
|
||||||
|
cfg := DefaultOpts
|
||||||
|
|
||||||
|
if cfg.Width != 0 {
|
||||||
|
d.width = cfg.Width
|
||||||
|
} else {
|
||||||
|
d.width = 240
|
||||||
|
}
|
||||||
|
if cfg.Height != 0 {
|
||||||
|
d.height = cfg.Height
|
||||||
|
} else {
|
||||||
|
d.height = 240
|
||||||
|
}
|
||||||
|
|
||||||
|
d.rotation = cfg.Rotation
|
||||||
|
d.rowOffsetCfg = cfg.RowOffset
|
||||||
|
d.columnOffsetCfg = cfg.ColumnOffset
|
||||||
|
|
||||||
|
if cfg.FrameRate != 0 {
|
||||||
|
d.frameRate = cfg.FrameRate
|
||||||
|
} else {
|
||||||
|
d.frameRate = FRAMERATE_60
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 {
|
||||||
|
d.vSyncLines = cfg.VSyncLines
|
||||||
|
} else {
|
||||||
|
d.vSyncLines = 16
|
||||||
|
}
|
||||||
|
|
||||||
|
d.batchLength = int32(d.width)
|
||||||
|
if d.height > d.width {
|
||||||
|
d.batchLength = int32(d.height)
|
||||||
|
}
|
||||||
|
d.batchLength += d.batchLength & 1
|
||||||
|
|
||||||
|
// Reset the device
|
||||||
|
log.Trace("reset device")
|
||||||
|
if err = d.reset.Out(gpio.High); err != nil {
|
||||||
|
_ = port.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
if err = d.reset.Out(gpio.Low); err != nil {
|
||||||
|
_ = port.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
if err = d.reset.Out(gpio.High); err != nil {
|
||||||
|
_ = port.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
|
||||||
|
// Common initialization
|
||||||
|
log.Trace("configure device")
|
||||||
|
d.Command(SWRESET) // Soft reset
|
||||||
|
time.Sleep(150 * time.Millisecond) //
|
||||||
|
|
||||||
|
d.Command(SLPOUT) // Exit sleep mode
|
||||||
|
time.Sleep(500 * time.Millisecond) //
|
||||||
|
|
||||||
|
// Memory initialization
|
||||||
|
d.Command(COLMOD) // Set color mode
|
||||||
|
d.Data(0x55) // 16-bit color
|
||||||
|
time.Sleep(10 * time.Millisecond) //
|
||||||
|
|
||||||
|
d.SetRotation(d.rotation) // Memory orientation
|
||||||
|
|
||||||
|
d.setWindow(0, 0, d.width, d.height) // Full draw window
|
||||||
|
d.FillScreen(color.RGBA{0, 0, 0, 255}) // Clear screen
|
||||||
|
|
||||||
|
// Framerate
|
||||||
|
d.Command(FRCTRL2) // Frame rate for normal mode
|
||||||
|
d.Data(uint8(d.frameRate)) // Default is 60Hz
|
||||||
|
|
||||||
|
// Frame vertical sync and "porch"
|
||||||
|
//
|
||||||
|
// Front and back porch controls vertical scanline sync time before and after
|
||||||
|
// a frame, where memory can be safely written without tearing.
|
||||||
|
//
|
||||||
|
fp := uint8(d.vSyncLines / 2) // Split the desired pause half and half
|
||||||
|
bp := uint8(d.vSyncLines - int16(fp)) // between front and back porch.
|
||||||
|
|
||||||
|
d.Command(PORCTRL)
|
||||||
|
d.Data(bp) // Back porch 5bit (0x7F max 0x08 default)
|
||||||
|
d.Data(fp) // Front porch 5bit (0x7F max 0x08 default)
|
||||||
|
d.Data(0x00) // Seprarate porch (TODO: what is this?)
|
||||||
|
d.Data(0x22) // Idle mode porch (4bit-back 4bit-front 0x22 default)
|
||||||
|
d.Data(0x22) // Partial mode porch (4bit-back 4bit-front 0x22 default)
|
||||||
|
|
||||||
|
// Ready to display
|
||||||
|
d.Command(INVON) // Inversion ON
|
||||||
|
time.Sleep(10 * time.Millisecond) //
|
||||||
|
|
||||||
|
d.Command(NORON) // Normal mode ON
|
||||||
|
time.Sleep(10 * time.Millisecond) //
|
||||||
|
|
||||||
|
d.Command(DISPON) // Screen ON
|
||||||
|
time.Sleep(10 * time.Millisecond) //
|
||||||
|
|
||||||
|
// Backlight ON
|
||||||
|
if err = d.bl.Out(gpio.High); err != nil {
|
||||||
|
_ = port.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) String() string {
|
||||||
|
return "st7789"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Bounds() image.Rectangle {
|
||||||
|
if d.rotation == display.Rotate90 || d.rotation == display.Rotate270 {
|
||||||
|
return image.Rect(0, 0, int(d.height), int(d.width))
|
||||||
|
}
|
||||||
|
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) ColorModel() color.Model {
|
||||||
|
return color.RGBAModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Halt() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Refresh() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync waits for the display to hit the next VSYNC pause
|
||||||
|
func (d *Device) Sync() {
|
||||||
|
d.SyncToScanLine(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncToScanLine waits for the display to hit a specific scanline
|
||||||
|
//
|
||||||
|
// A scanline value of 0 will forward to the beginning of the next VSYNC,
|
||||||
|
// even if the display is currently in a VSYNC pause.
|
||||||
|
//
|
||||||
|
// Syncline values appear to increment once for every two vertical
|
||||||
|
// lines on the display.
|
||||||
|
//
|
||||||
|
// NOTE: Use GetHighestScanLine and GetLowestScanLine to obtain the highest
|
||||||
|
// and lowest useful values. Values are affected by front and back porch
|
||||||
|
// vsync settings (derived from VSyncLines configuration option).
|
||||||
|
func (d *Device) SyncToScanLine(scanline uint16) {
|
||||||
|
scan := d.GetScanLine()
|
||||||
|
|
||||||
|
// Sometimes GetScanLine returns erroneous 0 on first call after draw, so double check
|
||||||
|
if scan == 0 {
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
|
||||||
|
if scanline == 0 {
|
||||||
|
// we dont know where we are in an ongoing vsync so go around
|
||||||
|
for scan < 1 {
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
for scan > 0 {
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// go around unless we're very close to the target
|
||||||
|
for scan > scanline+4 {
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
for scan < scanline {
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScanLine reads the current scanline value from the display
|
||||||
|
func (d *Device) GetScanLine() uint16 {
|
||||||
|
data := []uint8{0x00, 0x00}
|
||||||
|
d.Rx(GSCAN, data)
|
||||||
|
return uint16(data[0])<<8 + uint16(data[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetHighestScanLine calculates the last scanline id in the frame before VSYNC pause
|
||||||
|
func (d *Device) GetHighestScanLine() uint16 {
|
||||||
|
// Last scanline id appears to be backporch/2 + 320/2
|
||||||
|
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 160
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLowestScanLine calculate the first scanline id to appear after VSYNC pause
|
||||||
|
func (d *Device) GetLowestScanLine() uint16 {
|
||||||
|
// First scanline id appears to be backporch/2 + 1
|
||||||
|
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPixel sets a pixel in the screen
|
||||||
|
func (d *Device) SetPixel(x int16, y int16, c color.RGBA) {
|
||||||
|
if x < 0 || y < 0 ||
|
||||||
|
(((d.rotation == display.NoRotation || d.rotation == display.Rotate180) && (x >= d.width || y >= d.height)) ||
|
||||||
|
((d.rotation == display.Rotate90 || d.rotation == display.Rotate270) && (x >= d.height || y >= d.width))) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.FillRectangle(x, y, 1, 1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// setWindow prepares the screen to be modified at a given rectangle
|
||||||
|
func (d *Device) setWindow(x, y, w, h int16) {
|
||||||
|
x += d.columnOffset
|
||||||
|
y += d.rowOffset
|
||||||
|
d.Tx([]uint8{CASET}, true)
|
||||||
|
d.Tx([]uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)}, false)
|
||||||
|
d.Tx([]uint8{RASET}, true)
|
||||||
|
d.Tx([]uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)}, false)
|
||||||
|
d.Command(RAMWR)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillRectangle fills a rectangle at a given coordinates with a color
|
||||||
|
func (d *Device) FillRectangle(x, y, width, height int16, c color.Color) error {
|
||||||
|
|
||||||
|
k, i := int16(d.Size().X), int16(d.Size().Y)
|
||||||
|
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||||
|
x >= k || (x+width) > k || y >= i || (y+height) > i {
|
||||||
|
return errors.New("rectangle coordinates outside display area")
|
||||||
|
}
|
||||||
|
d.setWindow(x, y, width, height)
|
||||||
|
c565 := pixel.Color565Model.Convert(c).(pixel.Color565)
|
||||||
|
//c565 := RGBATo565(c)
|
||||||
|
c1 := uint8(c565 >> 8)
|
||||||
|
c2 := uint8(c565)
|
||||||
|
|
||||||
|
data := make([]uint8, d.batchLength*2)
|
||||||
|
for i := int32(0); i < d.batchLength; i++ {
|
||||||
|
data[i*2] = c1
|
||||||
|
data[i*2+1] = c2
|
||||||
|
}
|
||||||
|
j := int32(width) * int32(height)
|
||||||
|
for j > 0 {
|
||||||
|
if j >= d.batchLength {
|
||||||
|
d.Tx(data, false)
|
||||||
|
} else {
|
||||||
|
d.Tx(data[:j*2], false)
|
||||||
|
}
|
||||||
|
j -= d.batchLength
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillRectangle fills a rectangle at a given coordinates with a buffer
|
||||||
|
func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {
|
||||||
|
i, j := int16(d.Size().X), int16(d.Size().Y)
|
||||||
|
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||||
|
x >= i || (x+width) > i || y >= j || (y+height) > j {
|
||||||
|
return errors.New("rectangle coordinates outside display area")
|
||||||
|
}
|
||||||
|
if int32(width)*int32(height) != int32(len(buffer)) {
|
||||||
|
return errors.New("buffer length does not match with rectangle size")
|
||||||
|
}
|
||||||
|
d.setWindow(x, y, width, height)
|
||||||
|
|
||||||
|
k := int32(width) * int32(height)
|
||||||
|
data := make([]uint8, d.batchLength*2)
|
||||||
|
offset := int32(0)
|
||||||
|
for k > 0 {
|
||||||
|
for i := int32(0); i < d.batchLength; i++ {
|
||||||
|
if offset+i < int32(len(buffer)) {
|
||||||
|
c565 := RGBATo565(buffer[offset+i])
|
||||||
|
c1 := uint8(c565 >> 8)
|
||||||
|
c2 := uint8(c565)
|
||||||
|
data[i*2] = c1
|
||||||
|
data[i*2+1] = c2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if k >= d.batchLength {
|
||||||
|
d.Tx(data, false)
|
||||||
|
} else {
|
||||||
|
d.Tx(data[:k*2], false)
|
||||||
|
}
|
||||||
|
k -= d.batchLength
|
||||||
|
offset += d.batchLength
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawFastVLine draws a vertical line faster than using SetPixel
|
||||||
|
func (d *Device) DrawFastVLine(x, y0, y1 int16, c color.RGBA) {
|
||||||
|
if y0 > y1 {
|
||||||
|
y0, y1 = y1, y0
|
||||||
|
}
|
||||||
|
d.FillRectangle(x, y0, 1, y1-y0+1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawFastHLine draws a horizontal line faster than using SetPixel
|
||||||
|
func (d *Device) DrawFastHLine(x0, x1, y int16, c color.RGBA) {
|
||||||
|
if x0 > x1 {
|
||||||
|
x0, x1 = x1, x0
|
||||||
|
}
|
||||||
|
d.FillRectangle(x0, y, x1-x0+1, 1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillScreen fills the screen with a given color
|
||||||
|
func (d *Device) FillScreen(c color.Color) {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
d.FillRectangle(0, 0, d.width, d.height, c)
|
||||||
|
} else {
|
||||||
|
d.FillRectangle(0, 0, d.height, d.width, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRotation changes the rotation of the device (clock-wise)
|
||||||
|
func (d *Device) SetRotation(rotation display.Rotation) {
|
||||||
|
madctl := uint8(0)
|
||||||
|
switch rotation % 4 {
|
||||||
|
case display.NoRotation:
|
||||||
|
madctl = MADCTL_MX | MADCTL_MY
|
||||||
|
d.rowOffset = d.rowOffsetCfg
|
||||||
|
d.columnOffset = d.columnOffsetCfg
|
||||||
|
break
|
||||||
|
case display.Rotate90:
|
||||||
|
madctl = MADCTL_MY | MADCTL_MV
|
||||||
|
d.rowOffset = d.columnOffsetCfg
|
||||||
|
d.columnOffset = d.rowOffsetCfg
|
||||||
|
break
|
||||||
|
case display.Rotate180:
|
||||||
|
d.rowOffset = 0
|
||||||
|
d.columnOffset = 0
|
||||||
|
break
|
||||||
|
case display.Rotate270:
|
||||||
|
madctl = MADCTL_MX | MADCTL_MV
|
||||||
|
d.rowOffset = 0
|
||||||
|
d.columnOffset = 0
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if d.isBGR {
|
||||||
|
madctl |= MADCTL_BGR
|
||||||
|
}
|
||||||
|
d.Command(MADCTL)
|
||||||
|
d.Data(madctl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command sends a command to the display
|
||||||
|
func (d *Device) Command(command uint8) {
|
||||||
|
d.Tx([]byte{command}, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command sends a data to the display
|
||||||
|
func (d *Device) Data(data uint8) {
|
||||||
|
d.Tx([]byte{data}, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tx sends data to the display
|
||||||
|
func (d *Device) Tx(data []byte, isCommand bool) {
|
||||||
|
if isCommand {
|
||||||
|
d.dc.Out(gpio.Low)
|
||||||
|
} else {
|
||||||
|
d.dc.Out(gpio.High)
|
||||||
|
}
|
||||||
|
d.cs.Out(gpio.Low)
|
||||||
|
d.conn.Tx(data, nil)
|
||||||
|
d.cs.Out(gpio.High)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rx reads data from the display
|
||||||
|
func (d *Device) Rx(command uint8, read_bytes []byte) {
|
||||||
|
d.dc.Out(gpio.Low)
|
||||||
|
d.cs.Out(gpio.Low)
|
||||||
|
d.conn.Tx([]byte{command}, nil)
|
||||||
|
d.dc.Out(gpio.High)
|
||||||
|
for i := range read_bytes {
|
||||||
|
d.conn.Tx([]byte{0xFF}, read_bytes[i:i+1])
|
||||||
|
}
|
||||||
|
d.cs.Out(gpio.High)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the current size of the display.
|
||||||
|
func (d *Device) Size() image.Point {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
return image.Pt(int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
return image.Pt(int(d.height), int(d.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnableBacklight enables or disables the backlight
|
||||||
|
func (d *Device) EnableBacklight(enable bool) {
|
||||||
|
if enable {
|
||||||
|
d.bl.Out(gpio.High)
|
||||||
|
} else {
|
||||||
|
d.bl.Out(gpio.Low)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// InverColors inverts the colors of the screen
|
||||||
|
func (d *Device) InvertColors(invert bool) {
|
||||||
|
if invert {
|
||||||
|
d.Command(INVON)
|
||||||
|
} else {
|
||||||
|
d.Command(INVOFF)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsBGR changes the color mode (RGB/BGR)
|
||||||
|
func (d *Device) IsBGR(bgr bool) {
|
||||||
|
d.isBGR = bgr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) At(x, y int) color.Color {
|
||||||
|
return color.Black
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Set(x, y int, c color.Color) {
|
||||||
|
d.FillRectangle(int16(x), int16(y), int16(x)+1, int16(y)+1, color.RGBAModel.Convert(c).(color.RGBA))
|
||||||
|
}
|
||||||
|
|
||||||
|
// RGBATo565 converts a color.RGBA to uint16 used in the display
|
||||||
|
func RGBATo565(c color.RGBA) uint16 {
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return uint16((r & 0xF800) +
|
||||||
|
((g & 0xFC00) >> 5) +
|
||||||
|
((b & 0xF800) >> 11))
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package all
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "git.maze.io/go/harmon/display/console"
|
||||||
|
_ "git.maze.io/go/harmon/display/sh1106"
|
||||||
|
_ "git.maze.io/go/harmon/display/ssd1305"
|
||||||
|
_ "git.maze.io/go/harmon/display/ssd1306"
|
||||||
|
_ "git.maze.io/go/harmon/display/st7789"
|
||||||
|
_ "git.maze.io/go/harmon/display/virtual"
|
||||||
|
)
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
package console
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
|
||||||
|
"golang.org/x/term"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("console", New)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Display struct {
|
||||||
|
p *textImage
|
||||||
|
w, h int
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(config *config.Display) (display.Display, error) {
|
||||||
|
if !term.IsTerminal(0) {
|
||||||
|
return nil, errors.New("console: not a terminal")
|
||||||
|
}
|
||||||
|
|
||||||
|
w, h, err := term.GetSize(0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Display{
|
||||||
|
p: newTextImage(image.Rect(0, 0, w, h<<1)),
|
||||||
|
w: w,
|
||||||
|
h: h,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Display) String() string { return fmt.Sprintf("%dx%d console", d.w, d.h) }
|
||||||
|
func (d *Display) Columns() int { return d.w }
|
||||||
|
func (d *Display) Rows() int { return d.h }
|
||||||
|
func (d *Display) Size() image.Point { return image.Pt(d.w, d.h) }
|
||||||
|
|
||||||
|
func (d *Display) Refresh() error {
|
||||||
|
fmt.Print("\x1b[?25l\x1b[2J") // hide the cursor and clear screen
|
||||||
|
for i, l := 0, d.w*d.h; i < l; i += d.p.Stride {
|
||||||
|
fmt.Println(string(d.p.Pix[i : i+d.p.Stride]))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Display) Bounds() image.Rectangle { return d.p.Rect }
|
||||||
|
func (d *Display) ColorModel() color.Model { return d.p.ColorModel() }
|
||||||
|
func (d *Display) At(x, y int) color.Color { return d.p.At(x, y) }
|
||||||
|
func (d *Display) Set(x, y int, c color.Color) { d.p.Set(x, y, c) }
|
||||||
|
|
||||||
|
func (d *Display) Halt() error {
|
||||||
|
_, err := fmt.Print("\x1b[?25h\x1b[2J") // show the cursor and clear screen
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
type textImage struct {
|
||||||
|
// Pix holds the image's pixels, as character values. The pixel at
|
||||||
|
// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
|
||||||
|
Pix []rune
|
||||||
|
|
||||||
|
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
|
||||||
|
Stride int
|
||||||
|
|
||||||
|
// Rect is the image's bounds.
|
||||||
|
Rect image.Rectangle
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTextImage(r image.Rectangle) *textImage {
|
||||||
|
if r.Dy()%2 == 1 {
|
||||||
|
r.Max.Y++
|
||||||
|
}
|
||||||
|
p := make([]rune, r.Dx()*r.Dy()/2)
|
||||||
|
for i := range p {
|
||||||
|
p[i] = ' '
|
||||||
|
}
|
||||||
|
return &textImage{
|
||||||
|
Pix: p,
|
||||||
|
Stride: r.Dx(),
|
||||||
|
Rect: r,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *textImage) ColorModel() color.Model {
|
||||||
|
return pixel.MonochromeModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *textImage) PixOffset(x, y int) int {
|
||||||
|
return (((y - p.Rect.Min.Y) >> 1) * p.Stride) + (x - p.Rect.Min.X)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *textImage) At(x, y int) color.Color {
|
||||||
|
if !(image.Point{x, y}.In(p.Rect)) {
|
||||||
|
return pixel.Off
|
||||||
|
}
|
||||||
|
|
||||||
|
i := p.PixOffset(x, y)
|
||||||
|
r := p.Pix[i]
|
||||||
|
if y%2 == 1 {
|
||||||
|
if r == '▀' || r == '█' {
|
||||||
|
return pixel.On
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if r == '▄' || r == '█' {
|
||||||
|
return pixel.On
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pixel.Off
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *textImage) Set(x, y int, c color.Color) {
|
||||||
|
if !(image.Point{x, y}.In(p.Rect)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
i := p.PixOffset(x, y)
|
||||||
|
r := p.Pix[i]
|
||||||
|
|
||||||
|
if pixel.IsOn(c) {
|
||||||
|
if y%2 == 1 {
|
||||||
|
if r == '▀' {
|
||||||
|
p.Pix[i] = '█'
|
||||||
|
} else {
|
||||||
|
p.Pix[i] = '▄'
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if r == ' ' {
|
||||||
|
p.Pix[i] = '▄'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if y%2 == 1 {
|
||||||
|
if r == '█' {
|
||||||
|
p.Pix[i] = '▀'
|
||||||
|
} else {
|
||||||
|
p.Pix[i] = ' '
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if r == '█' {
|
||||||
|
p.Pix[i] = '▄'
|
||||||
|
} else {
|
||||||
|
p.Pix[i] = ' '
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var quadrants = []rune(" ▄▀█")
|
||||||
|
|
||||||
|
/*
|
||||||
|
func (p *textImage) PixOffset(x, y int) int {
|
||||||
|
return (y-p.Rect.Min.Y)*p.Stride + (x - p.Rect.Min.X)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *textImage) At(x, y int) color.Color {
|
||||||
|
if !(image.Point{x, y}.In(p.Rect)) {
|
||||||
|
return color.Gray{}
|
||||||
|
}
|
||||||
|
i := p.PixOffset(x, y)
|
||||||
|
return fromGrayScale(p.Pix[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *textImage) Set(x, y int, c color.Color) {
|
||||||
|
if !(image.Point{x, y}.In(p.Rect)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
i := p.PixOffset(x, y)
|
||||||
|
p.Pix[i] = toGrayScale(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
var grayScaleRamp = []rune(" ░░▒▓▓█")
|
||||||
|
|
||||||
|
func toGrayScale(c color.Color) rune {
|
||||||
|
g := color.GrayModel.Convert(c).(color.Gray)
|
||||||
|
return grayScaleRamp[g.Y>>3]
|
||||||
|
}
|
||||||
|
|
||||||
|
func fromGrayScale(r rune) color.Gray {
|
||||||
|
if i := strings.IndexRune(string(grayScaleRamp), r); i > -1 {
|
||||||
|
return color.Gray{Y: uint8(i << 3)}
|
||||||
|
}
|
||||||
|
return color.Gray{}
|
||||||
|
}
|
||||||
|
*/
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/draw"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/hardware"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Display base interface for all displays.
|
||||||
|
type Display interface {
|
||||||
|
hardware.Resource
|
||||||
|
|
||||||
|
Size() image.Point
|
||||||
|
|
||||||
|
// Refresh the display.
|
||||||
|
Refresh() error
|
||||||
|
|
||||||
|
// Image allows this display to be used as canvas.
|
||||||
|
draw.Image
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotation of the display.
|
||||||
|
type Rotation uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
NoRotation Rotation = iota
|
||||||
|
Rotate90
|
||||||
|
Rotate180
|
||||||
|
Rotate270
|
||||||
|
)
|
||||||
|
|
||||||
|
func ParseRotation(s string) (Rotation, error) {
|
||||||
|
switch strings.ToLower(s) {
|
||||||
|
case "", "no", "none":
|
||||||
|
return NoRotation, nil
|
||||||
|
case "90", "right", "cw":
|
||||||
|
return Rotate90, nil
|
||||||
|
case "180", "flip":
|
||||||
|
return Rotate180, nil
|
||||||
|
case "270", "left", "ccw":
|
||||||
|
return Rotate270, nil
|
||||||
|
default:
|
||||||
|
return NoRotation, fmt.Errorf("invalid rotation %q", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseI2CAddress(addr string) (uint16, error) {
|
||||||
|
if strings.HasPrefix(strings.ToLower(addr), "0x") {
|
||||||
|
addr = addr[2:]
|
||||||
|
}
|
||||||
|
|
||||||
|
v, err := strconv.ParseUint(addr, 16, 16)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return uint16(v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseSize(size string, defaultWidth, defaultHeight int) (width, height int, err error) {
|
||||||
|
if size == "" {
|
||||||
|
return defaultWidth, defaultHeight, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
i := strings.IndexByte(size, 'x')
|
||||||
|
if i == -1 {
|
||||||
|
return 0, 0, fmt.Errorf("display: incorrect size specifier %q: expected `widthxheight`", size)
|
||||||
|
} else if i == 0 {
|
||||||
|
if height, err = strconv.Atoi(size[1:]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return defaultWidth, height, nil
|
||||||
|
} else if i == len(size)-1 {
|
||||||
|
if width, err = strconv.Atoi(size[:i]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return width, defaultHeight, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if width, err = strconv.Atoi(size[:i]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if height, err = strconv.Atoi(size[i+1:]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package display_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseSize(t *testing.T) {
|
||||||
|
testCases := []struct {
|
||||||
|
Test string
|
||||||
|
DefaultWidth int
|
||||||
|
DefaultHeight int
|
||||||
|
Width int
|
||||||
|
Height int
|
||||||
|
}{
|
||||||
|
{"", 128, 64, 128, 64},
|
||||||
|
{"x32", 128, 64, 128, 32},
|
||||||
|
{"64x", 128, 64, 64, 64},
|
||||||
|
{"123x456", 128, 64, 123, 456},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range testCases {
|
||||||
|
t.Run(test.Test, func(it *testing.T) {
|
||||||
|
w, h, err := display.ParseSize(test.Test, test.DefaultWidth, test.DefaultHeight)
|
||||||
|
if err != nil {
|
||||||
|
it.Fatal(err)
|
||||||
|
}
|
||||||
|
if w != test.Width {
|
||||||
|
it.Errorf("expected %q to return width %d, got %d", test.Test, test.Width, w)
|
||||||
|
}
|
||||||
|
if h != test.Height {
|
||||||
|
it.Errorf("expected %q to return height %d, got %d", test.Test, test.Height, h)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
_ "image/gif" // GIF codec
|
||||||
|
_ "image/jpeg" // JPEG codec
|
||||||
|
_ "image/png" // PNG codec
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultTimeFormat = "15:04"
|
||||||
|
DefaultDateFormat = "01-02"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bitmapDrawerAt[T pixel.Color] interface {
|
||||||
|
DrawBitmap(x, y int16, bitmap pixel.Image[T]) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type imageDrawer interface {
|
||||||
|
DrawImage(image.Image) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type imageDrawerAt interface {
|
||||||
|
DrawImageAt(x, y int, img image.Image) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func DrawTime(d Display, format string) {
|
||||||
|
if format == "" {
|
||||||
|
format = DefaultTimeFormat
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func DrawSplash(d Display) error {
|
||||||
|
/*
|
||||||
|
var (
|
||||||
|
size = d.Size()
|
||||||
|
origin image.Point
|
||||||
|
)
|
||||||
|
if size.X > size.Y {
|
||||||
|
origin.X = (size.X - size.Y) / 2
|
||||||
|
size.X = size.Y
|
||||||
|
} else {
|
||||||
|
origin.Y = (size.Y - size.X) / 2
|
||||||
|
size.Y = size.X
|
||||||
|
}
|
||||||
|
|
||||||
|
r := image.Rect(0, 0, size.X, size.Y).Add(origin)
|
||||||
|
draw.Draw(d, r, resize.Resize(uint(size.X), uint(size.Y), splashImage, resize.Lanczos3), image.Point{}, draw.Src)
|
||||||
|
return d.Refresh()
|
||||||
|
*/
|
||||||
|
if drawer, ok := d.(bitmapDrawerAt[pixel.RGB565BE]); ok {
|
||||||
|
return drawer.DrawBitmap(0, 0, harmon_240_565BE)
|
||||||
|
}
|
||||||
|
return errors.New("not implemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
func DrawImage(d Display, img image.Image) {
|
||||||
|
if drawer, ok := d.(imageDrawer); ok {
|
||||||
|
logrus.Trace("using DrawImage")
|
||||||
|
if err := drawer.DrawImage(img); err != nil {
|
||||||
|
logrus.WithError(err).Warn("image draw failed")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//scaled := resize.Resize(uint(size.X), uint(size.Y), img, resize.Bicubic)
|
||||||
|
if drawer, ok := d.(imageDrawerAt); ok {
|
||||||
|
logrus.Trace("using DrawImageAt")
|
||||||
|
if err := drawer.DrawImageAt(0, 0, img); err != nil {
|
||||||
|
logrus.WithError(err).Warn("image draw failed")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.Trace("using slow cooked draw")
|
||||||
|
}
|
||||||
|
|
||||||
|
func DrawImageFile(d Display, name string) error {
|
||||||
|
f, err := os.Open(name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
i, _, err := image.Decode(f)
|
||||||
|
if err != nil {
|
||||||
|
_ = f.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
DrawImage(d, i)
|
||||||
|
return f.Close()
|
||||||
|
}
|
||||||
@@ -0,0 +1,537 @@
|
|||||||
|
// Package gc9a01 provides a driver for the GC9A01 round display controller.
|
||||||
|
package gc9a01
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.maze.io/go/bragi/hardware"
|
||||||
|
"git.maze.io/go/bragi/hardware/display/pixel"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
)
|
||||||
|
|
||||||
|
var supportedResolutions = [][2]int16{
|
||||||
|
{80, 160},
|
||||||
|
{120, 120},
|
||||||
|
{128, 128},
|
||||||
|
{160, 160},
|
||||||
|
{240, 240},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Orientation is the display orientation.
|
||||||
|
type Orientation uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Horizontal Orientation = iota
|
||||||
|
Vertical
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config for the display.
|
||||||
|
type Config struct {
|
||||||
|
hardware.SPIConfig
|
||||||
|
Width int
|
||||||
|
Height int
|
||||||
|
Orientation Orientation
|
||||||
|
VSyncLines int
|
||||||
|
RowOffset int
|
||||||
|
ColumnOffset int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Device struct {
|
||||||
|
conn spi.Conn
|
||||||
|
cs gpio.PinOut
|
||||||
|
dc gpio.PinOut
|
||||||
|
reset gpio.PinOut
|
||||||
|
bl gpio.PinOut
|
||||||
|
width int16
|
||||||
|
height int16
|
||||||
|
columnOffsetCfg int16
|
||||||
|
rowOffsetCfg int16
|
||||||
|
columnOffset int16
|
||||||
|
rowOffset int16
|
||||||
|
vSyncLines int16
|
||||||
|
orientation Orientation
|
||||||
|
batchLength int16
|
||||||
|
batchData []uint8
|
||||||
|
image *pixel.Image565
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(port spi.Port, config Config) (*Device, error) {
|
||||||
|
f := config.Frequency
|
||||||
|
if f == 0 {
|
||||||
|
f = 80 * physic.MegaHertz // 80_000_000
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := port.Connect(f, spi.Mode0, 8)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := &Device{
|
||||||
|
conn: c,
|
||||||
|
cs: config.CS,
|
||||||
|
dc: config.DC,
|
||||||
|
reset: config.Reset,
|
||||||
|
bl: config.BL,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = d.configure(config); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset the display.
|
||||||
|
func (d *Device) Reset() error {
|
||||||
|
var err error
|
||||||
|
if err = d.reset.Out(gpio.High); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
if err = d.reset.Out(gpio.Low); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
if err = d.reset.Out(gpio.High); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) command(v uint8) error {
|
||||||
|
return d.tx([]byte{v}, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) data(v uint8) error {
|
||||||
|
return d.tx([]byte{v}, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) tx(w []byte, cmd bool) (err error) {
|
||||||
|
level := gpio.Low
|
||||||
|
if cmd {
|
||||||
|
level = gpio.High
|
||||||
|
}
|
||||||
|
if err = d.dc.Out(level); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return d.conn.Tx(w, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
func (d *Device) rx(command uint8, data []byte) (err error) {
|
||||||
|
if err = d.dc.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.cs.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.conn.Tx([]byte{command}, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.dc.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.conn.Tx(nil, data); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return d.cs.Out(gpio.High)
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
func (d *Device) setOrientation() (err error) {
|
||||||
|
var reg uint8
|
||||||
|
if d.orientation == Horizontal {
|
||||||
|
reg = 0xc8
|
||||||
|
} else {
|
||||||
|
reg = 0x68
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = d.command(MADCTR); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return d.command(reg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) setWindow(x, y, w, h int) (err error) {
|
||||||
|
if d.orientation == Horizontal {
|
||||||
|
x += int(d.columnOffset)
|
||||||
|
y += int(d.rowOffset)
|
||||||
|
} else {
|
||||||
|
x += int(d.rowOffset)
|
||||||
|
y += int(d.columnOffset)
|
||||||
|
}
|
||||||
|
if err = d.command(CASET); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.tx([]uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)}, false); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.command(RASET); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = d.tx([]uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)}, false); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return d.command(RAMWR)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Backlight(on bool) error {
|
||||||
|
if on {
|
||||||
|
return d.bl.Out(gpio.High)
|
||||||
|
}
|
||||||
|
return d.bl.Out(gpio.Low)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Invert(on bool) error {
|
||||||
|
if on {
|
||||||
|
return d.command(INVON)
|
||||||
|
}
|
||||||
|
return d.command(INVOFF)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) FillRectangle(x, y, w, h int, c color.Color) (err error) {
|
||||||
|
if x < 0 || y < 0 || w <= 0 || h <= 0 ||
|
||||||
|
x >= int(d.width) || (x+w) > int(d.width) || y >= int(d.height) || (y+h) > int(d.height) {
|
||||||
|
return errors.New("gc9a01: rectangle coordinates outside display area")
|
||||||
|
}
|
||||||
|
|
||||||
|
d.setWindow(x, y, w, h)
|
||||||
|
|
||||||
|
c565 := pixel.Color565Model.Convert(c).(pixel.Color565)
|
||||||
|
c1 := uint8(c565 >> 8)
|
||||||
|
c2 := uint8(c565)
|
||||||
|
for i := 0; i < int(d.batchLength); i++ {
|
||||||
|
d.batchData[i*2+0] = c1
|
||||||
|
d.batchData[i*2+1] = c2
|
||||||
|
}
|
||||||
|
|
||||||
|
i := w * h
|
||||||
|
l := int(d.batchLength)
|
||||||
|
for i > 0 {
|
||||||
|
if i >= l {
|
||||||
|
if err = d.tx(d.batchData, false); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err = d.tx(d.batchData[:i*2], false); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i -= l
|
||||||
|
}
|
||||||
|
|
||||||
|
for yy := y; yy < y+h; yy++ {
|
||||||
|
for xx := x; xx < x+w; xx++ {
|
||||||
|
d.image.Set(xx, yy, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) At(x, y int) color.Color {
|
||||||
|
if x < 0 || x >= int(d.width) || y < 0 || y >= int(d.height) {
|
||||||
|
return color.Black
|
||||||
|
}
|
||||||
|
return d.image.At(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Set(x, y int, c color.Color) {
|
||||||
|
if x < 0 || x >= int(d.width) || y < 0 || y >= int(d.height) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = d.FillRectangle(x, y, 1, 1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Bounds() image.Rectangle {
|
||||||
|
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) ColorModel() color.Model {
|
||||||
|
return pixel.Color565Model
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) configure(config Config) (err error) {
|
||||||
|
if config.Width > 0 {
|
||||||
|
d.width = int16(config.Width)
|
||||||
|
} else {
|
||||||
|
d.width = 240
|
||||||
|
}
|
||||||
|
if config.Height > 0 {
|
||||||
|
d.height = int16(config.Height)
|
||||||
|
} else {
|
||||||
|
d.height = 240
|
||||||
|
}
|
||||||
|
|
||||||
|
var supportedResolution bool
|
||||||
|
for _, res := range supportedResolutions {
|
||||||
|
if supportedResolution = d.width == res[0] && d.height == res[1]; supportedResolution {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !supportedResolution {
|
||||||
|
return fmt.Errorf("gc9a01: unsupported resolution %dx%d", d.width, d.height)
|
||||||
|
}
|
||||||
|
|
||||||
|
d.image = pixel.NewImage565(image.Rect(0, 0, int(d.width), int(d.height)))
|
||||||
|
d.orientation = config.Orientation
|
||||||
|
d.rowOffsetCfg = int16(config.RowOffset)
|
||||||
|
d.columnOffsetCfg = int16(config.ColumnOffset)
|
||||||
|
d.batchLength = d.width
|
||||||
|
|
||||||
|
if config.VSyncLines >= 2 && config.VSyncLines <= 254 {
|
||||||
|
d.vSyncLines = int16(config.VSyncLines)
|
||||||
|
} else {
|
||||||
|
d.vSyncLines = 2
|
||||||
|
}
|
||||||
|
d.batchLength += d.batchLength & 1
|
||||||
|
d.batchData = make([]uint8, d.batchLength*2)
|
||||||
|
|
||||||
|
if err := d.Reset(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := d.setOrientation(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common initialization
|
||||||
|
_ = d.command(0xEF)
|
||||||
|
_ = d.command(0xEB)
|
||||||
|
_ = d.data(0x14)
|
||||||
|
|
||||||
|
_ = d.command(INTEN1)
|
||||||
|
_ = d.command(0xEF)
|
||||||
|
|
||||||
|
_ = d.command(0xEB)
|
||||||
|
_ = d.data(0x14)
|
||||||
|
|
||||||
|
_ = d.command(0x84)
|
||||||
|
_ = d.data(0x40)
|
||||||
|
|
||||||
|
_ = d.command(0x85)
|
||||||
|
_ = d.data(0xFF)
|
||||||
|
|
||||||
|
_ = d.command(0x86)
|
||||||
|
_ = d.data(0xFF)
|
||||||
|
|
||||||
|
_ = d.command(0x87)
|
||||||
|
_ = d.data(0xFF)
|
||||||
|
|
||||||
|
_ = d.command(0x88)
|
||||||
|
_ = d.data(0x0A)
|
||||||
|
|
||||||
|
_ = d.command(0x89)
|
||||||
|
_ = d.data(0x21)
|
||||||
|
|
||||||
|
_ = d.command(0x8A)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
|
||||||
|
_ = d.command(0x8B)
|
||||||
|
_ = d.data(0x80)
|
||||||
|
|
||||||
|
_ = d.command(0x8C)
|
||||||
|
_ = d.data(0x01)
|
||||||
|
|
||||||
|
_ = d.command(0x8D)
|
||||||
|
_ = d.data(0x01)
|
||||||
|
|
||||||
|
_ = d.command(0x8E)
|
||||||
|
_ = d.data(0xFF)
|
||||||
|
|
||||||
|
_ = d.command(0x8F)
|
||||||
|
_ = d.data(0xFF)
|
||||||
|
|
||||||
|
_ = d.command(DISFNCTL)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x20)
|
||||||
|
|
||||||
|
_ = d.command(MADCTR)
|
||||||
|
_ = d.data(0x08) //Set as vertical screen
|
||||||
|
|
||||||
|
_ = d.command(COLMOD)
|
||||||
|
_ = d.data(0x05)
|
||||||
|
|
||||||
|
_ = d.command(0x90)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
|
||||||
|
_ = d.command(0xBD)
|
||||||
|
_ = d.data(0x06)
|
||||||
|
|
||||||
|
_ = d.command(0xBC)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
|
||||||
|
_ = d.command(0xFF)
|
||||||
|
_ = d.data(0x60)
|
||||||
|
_ = d.data(0x01)
|
||||||
|
_ = d.data(0x04)
|
||||||
|
|
||||||
|
_ = d.command(PWCTR3)
|
||||||
|
_ = d.data(0x13)
|
||||||
|
_ = d.command(PWCTR4)
|
||||||
|
_ = d.data(0x13)
|
||||||
|
|
||||||
|
_ = d.command(0xC9)
|
||||||
|
_ = d.data(0x22)
|
||||||
|
|
||||||
|
_ = d.command(0xBE)
|
||||||
|
_ = d.data(0x11)
|
||||||
|
|
||||||
|
_ = d.command(0xE1)
|
||||||
|
_ = d.data(0x10)
|
||||||
|
_ = d.data(0x0E)
|
||||||
|
|
||||||
|
_ = d.command(0xDF)
|
||||||
|
_ = d.data(0x21)
|
||||||
|
_ = d.data(0x0c)
|
||||||
|
_ = d.data(0x02)
|
||||||
|
|
||||||
|
_ = d.command(GMSET1)
|
||||||
|
_ = d.data(0x45)
|
||||||
|
_ = d.data(0x09)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x26)
|
||||||
|
_ = d.data(0x2A)
|
||||||
|
|
||||||
|
_ = d.command(GMSET2)
|
||||||
|
_ = d.data(0x43)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x72)
|
||||||
|
_ = d.data(0x36)
|
||||||
|
_ = d.data(0x37)
|
||||||
|
_ = d.data(0x6F)
|
||||||
|
|
||||||
|
_ = d.command(GMSET3)
|
||||||
|
_ = d.data(0x45)
|
||||||
|
_ = d.data(0x09)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x26)
|
||||||
|
_ = d.data(0x2A)
|
||||||
|
|
||||||
|
_ = d.command(GMSET4)
|
||||||
|
_ = d.data(0x43)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x72)
|
||||||
|
_ = d.data(0x36)
|
||||||
|
_ = d.data(0x37)
|
||||||
|
_ = d.data(0x6F)
|
||||||
|
|
||||||
|
_ = d.command(0xED)
|
||||||
|
_ = d.data(0x1B)
|
||||||
|
_ = d.data(0x0B)
|
||||||
|
|
||||||
|
_ = d.command(0xAE)
|
||||||
|
_ = d.data(0x77)
|
||||||
|
|
||||||
|
_ = d.command(0xCD)
|
||||||
|
_ = d.data(0x63)
|
||||||
|
|
||||||
|
_ = d.command(0x70)
|
||||||
|
_ = d.data(0x07)
|
||||||
|
_ = d.data(0x07)
|
||||||
|
_ = d.data(0x04)
|
||||||
|
_ = d.data(0x0E)
|
||||||
|
_ = d.data(0x0F)
|
||||||
|
_ = d.data(0x09)
|
||||||
|
_ = d.data(0x07)
|
||||||
|
_ = d.data(0x08)
|
||||||
|
_ = d.data(0x03)
|
||||||
|
|
||||||
|
_ = d.command(FRMCTL)
|
||||||
|
_ = d.data(0x34)
|
||||||
|
|
||||||
|
_ = d.command(0x62)
|
||||||
|
_ = d.data(0x18)
|
||||||
|
_ = d.data(0x0D)
|
||||||
|
_ = d.data(0x71)
|
||||||
|
_ = d.data(0xED)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x18)
|
||||||
|
_ = d.data(0x0F)
|
||||||
|
_ = d.data(0x71)
|
||||||
|
_ = d.data(0xEF)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
|
||||||
|
_ = d.command(0x63)
|
||||||
|
_ = d.data(0x18)
|
||||||
|
_ = d.data(0x11)
|
||||||
|
_ = d.data(0x71)
|
||||||
|
_ = d.data(0xF1)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x18)
|
||||||
|
_ = d.data(0x13)
|
||||||
|
_ = d.data(0x71)
|
||||||
|
_ = d.data(0xF3)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
_ = d.data(0x70)
|
||||||
|
|
||||||
|
_ = d.command(0x64)
|
||||||
|
_ = d.data(0x28)
|
||||||
|
_ = d.data(0x29)
|
||||||
|
_ = d.data(0xF1)
|
||||||
|
_ = d.data(0x01)
|
||||||
|
_ = d.data(0xF1)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x07)
|
||||||
|
|
||||||
|
_ = d.command(0x66)
|
||||||
|
_ = d.data(0x3C)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0xCD)
|
||||||
|
_ = d.data(0x67)
|
||||||
|
_ = d.data(0x45)
|
||||||
|
_ = d.data(0x45)
|
||||||
|
_ = d.data(0x10)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
|
||||||
|
_ = d.command(0x67)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x3C)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x01)
|
||||||
|
_ = d.data(0x54)
|
||||||
|
_ = d.data(0x10)
|
||||||
|
_ = d.data(0x32)
|
||||||
|
_ = d.data(0x98)
|
||||||
|
|
||||||
|
_ = d.command(0x74)
|
||||||
|
_ = d.data(0x10)
|
||||||
|
_ = d.data(0x85)
|
||||||
|
_ = d.data(0x80)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
_ = d.data(0x4E)
|
||||||
|
_ = d.data(0x00)
|
||||||
|
|
||||||
|
_ = d.command(0x98)
|
||||||
|
_ = d.data(0x3e)
|
||||||
|
_ = d.data(0x07)
|
||||||
|
|
||||||
|
_ = d.command(TEON)
|
||||||
|
_ = d.command(0x21)
|
||||||
|
|
||||||
|
_ = d.command(SLPOUT)
|
||||||
|
time.Sleep(120 * time.Millisecond)
|
||||||
|
_ = d.command(DISPON)
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
|
||||||
|
return d.Backlight(true)
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package gc9a01
|
||||||
|
|
||||||
|
const (
|
||||||
|
NOP = 0x00
|
||||||
|
SWRESET = 0x01
|
||||||
|
RDDIDIF = 0x04
|
||||||
|
RDDST = 0x09
|
||||||
|
SLPIN = 0x10
|
||||||
|
SLPOUT = 0x11
|
||||||
|
PTLON = 0x12
|
||||||
|
NORON = 0x13
|
||||||
|
INVOFF = 0x20
|
||||||
|
INVON = 0x21
|
||||||
|
DISPOFF = 0x28
|
||||||
|
DISPON = 0x29
|
||||||
|
CASET = 0x2A
|
||||||
|
RASET = 0x2B
|
||||||
|
RAMWR = 0x2C
|
||||||
|
PTLAR = 0x30
|
||||||
|
VSCRDEF = 0x33
|
||||||
|
TEOFF = 0x34
|
||||||
|
TEON = 0x35
|
||||||
|
MADCTR = 0x36
|
||||||
|
VSCRSADD = 0x37
|
||||||
|
IDMOFF = 0x38
|
||||||
|
IDMON = 0x39
|
||||||
|
COLMOD = 0x3A
|
||||||
|
RMEMCON = 0x3C
|
||||||
|
STTRSCL = 0x44
|
||||||
|
GTSCL = 0x45
|
||||||
|
WRDISBV = 0x51
|
||||||
|
WRCTRLD = 0x51
|
||||||
|
MADCTL_MY = 0x80
|
||||||
|
MADCTL_MX = 0x40
|
||||||
|
MADCTL_MV = 0x20
|
||||||
|
MADCTL_ML = 0x10
|
||||||
|
MADCTL_RGB = 0x00
|
||||||
|
MADCTL_BGR = 0x08
|
||||||
|
MADCTL_MH = 0x04
|
||||||
|
RDID1 = 0xDA
|
||||||
|
RDID2 = 0xDB
|
||||||
|
RDID3 = 0xDC
|
||||||
|
RGBICTR = 0xB0
|
||||||
|
BLPCHCTRL = 0xB5
|
||||||
|
DISFNCTL = 0xB6
|
||||||
|
TECTL = 0xBA
|
||||||
|
INTCTL = 0xBA
|
||||||
|
FRMCTL = 0xE8
|
||||||
|
SPICTL = 0xE9
|
||||||
|
PWCTR1 = 0xC1
|
||||||
|
PWCTR2 = 0xC2
|
||||||
|
PWCTR3 = 0xC3
|
||||||
|
PWCTR4 = 0xC4
|
||||||
|
PWCTR7 = 0xC7
|
||||||
|
INTEN1 = 0xFE
|
||||||
|
INTEN2 = 0xEF
|
||||||
|
GMSET1 = 0xF0
|
||||||
|
GMSET2 = 0xF1
|
||||||
|
GMSET3 = 0xF2
|
||||||
|
GMSET4 = 0xF3
|
||||||
|
)
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"periph.io/x/conn/v3"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MonochromeDisplayInfo struct {
|
||||||
|
DC gpio.PinOut
|
||||||
|
Reset gpio.PinOut
|
||||||
|
ResetPulseWidth time.Duration
|
||||||
|
ResetWait time.Duration
|
||||||
|
PreChipEnableWait time.Duration
|
||||||
|
PostChipEnableWait time.Duration
|
||||||
|
DataSetupTime time.Duration
|
||||||
|
WritePulseWidth time.Duration
|
||||||
|
Width uint16
|
||||||
|
Height uint16
|
||||||
|
XOffset uint16
|
||||||
|
YOffset uint16
|
||||||
|
Speed physic.Frequency
|
||||||
|
}
|
||||||
|
|
||||||
|
// MonochromeDisplay is the hardware abstraction layer for monochrome displays.
|
||||||
|
type MonochromeDisplay interface {
|
||||||
|
// Init initializes the display.
|
||||||
|
Init() error
|
||||||
|
|
||||||
|
// Halt the display.
|
||||||
|
Halt() error
|
||||||
|
|
||||||
|
// StartTransfer starts a data transfer.
|
||||||
|
StartTransfer() error
|
||||||
|
|
||||||
|
// EndTransfer ends a data transfer.
|
||||||
|
EndTransfer() error
|
||||||
|
|
||||||
|
// Reset the display.
|
||||||
|
Reset(on bool) error
|
||||||
|
|
||||||
|
// SendCommand sends a command to the display.
|
||||||
|
SendCommand([]byte) error
|
||||||
|
|
||||||
|
// SendData sends data to the display.
|
||||||
|
SendData([]byte) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type ssd13xxDisplay struct {
|
||||||
|
conn conn.Conn
|
||||||
|
info MonochromeDisplayInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSSD13xxDisplay(conn conn.Conn, info MonochromeDisplayInfo) *ssd13xxDisplay {
|
||||||
|
return &ssd13xxDisplay{
|
||||||
|
conn: conn,
|
||||||
|
info: info,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) Init() (err error) {
|
||||||
|
if err = d.Reset(true); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(d.info.ResetPulseWidth)
|
||||||
|
if err = d.Reset(false); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(d.info.ResetPulseWidth)
|
||||||
|
if err = d.Reset(true); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(d.info.ResetWait)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) Halt() error {
|
||||||
|
if c, ok := d.conn.(io.Closer); ok {
|
||||||
|
return c.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) Reset(on bool) error {
|
||||||
|
if d.info.Reset == nil {
|
||||||
|
// No reset pin.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
level := gpio.Low
|
||||||
|
if on {
|
||||||
|
level = gpio.High
|
||||||
|
}
|
||||||
|
return d.info.Reset.Out(level)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) StartTransfer() error {
|
||||||
|
switch d.conn.(type) {
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) EndTransfer() error {
|
||||||
|
switch d.conn.(type) {
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) SendCommand(data []byte) error {
|
||||||
|
return d.conn.Tx(append([]byte{0x00}, data...), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ssd13xxDisplay) SendData(data []byte) error {
|
||||||
|
return d.conn.Tx(append([]byte{0x40}, data...), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func LookupPinOut(name string) (gpio.PinOut, error) {
|
||||||
|
pin := gpioreg.ByName(name)
|
||||||
|
if pin == nil || pin == gpio.INVALID {
|
||||||
|
return nil, fmt.Errorf("invalid GPIO pin %q: not found", name)
|
||||||
|
}
|
||||||
|
return pin, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface check.
|
||||||
|
var (
|
||||||
|
_ MonochromeDisplay = &ssd13xxDisplay{}
|
||||||
|
)
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
// Package oled contains common routines for driving OLEDs.
|
||||||
|
package oled
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/i2c"
|
||||||
|
"periph.io/x/conn/v3/i2c/i2creg"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
"periph.io/x/conn/v3/spi/spireg"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Bus interface {
|
||||||
|
// Halt the bus.
|
||||||
|
Halt() error
|
||||||
|
|
||||||
|
// Tx transfers bytes.
|
||||||
|
Tx(data []byte, isCommand bool) error
|
||||||
|
|
||||||
|
String() string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBus(config *config.Display) (Bus, error) {
|
||||||
|
if config.Bus == "" || strings.HasPrefix(config.Bus, "i2c") {
|
||||||
|
return newI2C(config)
|
||||||
|
}
|
||||||
|
return newSPI(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
type I2C struct {
|
||||||
|
bus i2c.BusCloser
|
||||||
|
conn *i2c.Dev
|
||||||
|
}
|
||||||
|
|
||||||
|
func newI2C(config *config.Display) (Bus, error) {
|
||||||
|
addr, err := display.ParseI2CAddress(config.Address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid I2C address %q: %w", config.Address, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bus, err := i2creg.Open(config.Bus)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error opening I2C bus %q: %w", config.Bus, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &I2C{
|
||||||
|
bus: bus,
|
||||||
|
conn: &i2c.Dev{Bus: bus, Addr: addr},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *I2C) Halt() error {
|
||||||
|
return bus.bus.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *I2C) Tx(data []byte, isCommand bool) error {
|
||||||
|
if isCommand {
|
||||||
|
return bus.conn.Tx(append([]byte{0x00}, data...), nil)
|
||||||
|
}
|
||||||
|
return bus.conn.Tx(append([]byte{0x40}, data...), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *I2C) String() string {
|
||||||
|
return "I²C"
|
||||||
|
}
|
||||||
|
|
||||||
|
type SPI struct {
|
||||||
|
Reset gpio.PinOut
|
||||||
|
DC gpio.PinOut
|
||||||
|
CS gpio.PinOut
|
||||||
|
port spi.PortCloser
|
||||||
|
conn spi.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSPI(config *config.Display) (Bus, error) {
|
||||||
|
var (
|
||||||
|
freq physic.Frequency = 800 * physic.KiloHertz
|
||||||
|
reset, dc, cs gpio.PinOut
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if config.Freq != "" {
|
||||||
|
if err = freq.Set(config.Freq); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reset, err = display.LookupPinOut(config.Reset); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid reset pin %q: %w", config.Reset, err)
|
||||||
|
}
|
||||||
|
if dc, err = display.LookupPinOut(config.DC); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid dc pin %q: %w", config.DC, err)
|
||||||
|
}
|
||||||
|
if cs, err = display.LookupPinOut(config.CS); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid cs pin %q: %w", config.CS, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := spireg.Open(config.Port)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("opening SPI port %q failed: %w", config.Port, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := port.Connect(freq, spi.Mode0, 8)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("connecting on SPI port %q failed: %w", config.Port, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bus := &SPI{
|
||||||
|
Reset: reset,
|
||||||
|
DC: dc,
|
||||||
|
CS: cs,
|
||||||
|
port: port,
|
||||||
|
conn: conn,
|
||||||
|
}
|
||||||
|
if err = bus.reset(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bus, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *SPI) Halt() error {
|
||||||
|
return bus.port.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *SPI) reset() (err error) {
|
||||||
|
if err = bus.CS.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.DC.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.Reset.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = bus.Reset.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
if err = bus.Reset.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
if err = bus.Reset.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *SPI) Tx(data []byte, isCommand bool) (err error) {
|
||||||
|
if isCommand {
|
||||||
|
if err = bus.CS.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
if err = bus.DC.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.CS.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.conn.Tx(data, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.CS.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err = bus.CS.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
if err = bus.DC.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.CS.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.conn.Tx(data, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = bus.CS.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bus *SPI) String() string {
|
||||||
|
return "SPI"
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NotFound is an error.
|
||||||
|
type NotFound struct {
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (err NotFound) Error() string {
|
||||||
|
return fmt.Sprintf("display %q is not available", err.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
drivers = new(sync.Map)
|
||||||
|
instances = new(sync.Map)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Factory creates a new display driver.
|
||||||
|
type Factory func(config *config.Display) (Display, error)
|
||||||
|
|
||||||
|
// Register a new display driver.
|
||||||
|
func Register(driver string, f Factory) {
|
||||||
|
if _, loaded := drivers.LoadOrStore(driver, f); loaded {
|
||||||
|
panic(fmt.Sprintf("display driver %q already registered", driver))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// New display driver.
|
||||||
|
func New(config *config.Display) (Display, error) {
|
||||||
|
f, ok := drivers.Load(config.Type)
|
||||||
|
if ok {
|
||||||
|
d, err := f.(Factory)(config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
instances.Store(config.Name, d)
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
return nil, NotFound{Name: config.Type}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup a previously instantiated display driver by name.
|
||||||
|
func Lookup(name string) (Display, error) {
|
||||||
|
d, ok := instances.Load(name)
|
||||||
|
if ok {
|
||||||
|
return d.(Display), nil
|
||||||
|
}
|
||||||
|
return nil, NotFound{Name: name}
|
||||||
|
}
|
||||||
|
|
||||||
|
// List returns all registered drivers.
|
||||||
|
func List() []string {
|
||||||
|
var s []string
|
||||||
|
drivers.Range(func(k, v any) bool {
|
||||||
|
s = append(s, k.(string))
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
sort.Strings(s)
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package sh1106
|
||||||
|
|
||||||
|
// Registers
|
||||||
|
const (
|
||||||
|
Address = 0x3C
|
||||||
|
|
||||||
|
SETCONTRAST = 0x81
|
||||||
|
DISPLAYALLON_RESUME = 0xA4
|
||||||
|
DISPLAYALLON = 0xA5
|
||||||
|
NORMALDISPLAY = 0xA6
|
||||||
|
INVERTDISPLAY = 0xA7
|
||||||
|
DISPLAYOFF = 0xAE
|
||||||
|
DISPLAYON = 0xAF
|
||||||
|
SETDISPLAYOFFSET = 0xD3
|
||||||
|
SETCOMPINS = 0xDA
|
||||||
|
SETVCOMDETECT = 0xDB
|
||||||
|
SETDISPLAYCLOCKDIV = 0xD5
|
||||||
|
SETPRECHARGE = 0xD9
|
||||||
|
SETMULTIPLEX = 0xA8
|
||||||
|
SETLOWCOLUMN = 0x00
|
||||||
|
SETHIGHCOLUMN = 0x10
|
||||||
|
SETSTARTLINE = 0x40
|
||||||
|
MEMORYMODE = 0x20
|
||||||
|
COLUMNADDR = 0x21
|
||||||
|
PAGEADDR = 0x22
|
||||||
|
COMSCANINC = 0xC0
|
||||||
|
COMSCANDEC = 0xC8
|
||||||
|
SEGREMAP = 0xA0
|
||||||
|
CHARGEPUMP = 0x8D
|
||||||
|
ACTIVATE_SCROLL = 0x2F
|
||||||
|
DEACTIVATE_SCROLL = 0x2E
|
||||||
|
SET_VERTICAL_SCROLL_AREA = 0xA3
|
||||||
|
RIGHT_HORIZONTAL_SCROLL = 0x26
|
||||||
|
LEFT_HORIZONTAL_SCROLL = 0x27
|
||||||
|
VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29
|
||||||
|
VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A
|
||||||
|
|
||||||
|
EXTERNALVCC VccMode = 0x1
|
||||||
|
SWITCHCAPVCC VccMode = 0x2
|
||||||
|
)
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
package sh1106
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/draw"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/display/oled"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("sh1106", newDevice)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDevice(config *config.Display) (display.Display, error) {
|
||||||
|
width, height, err := display.ParseSize(config.Size, 128, 0)
|
||||||
|
if err != nil || height == 0 {
|
||||||
|
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
rotation, err := display.ParseRotation(config.Rotate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
bus, err := oled.NewBus(config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dev := &Device{
|
||||||
|
bus: bus,
|
||||||
|
}
|
||||||
|
if err = dev.Configure(Config{
|
||||||
|
Width: int16(width),
|
||||||
|
Height: int16(height),
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dev, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Device wraps an SPI connection.
|
||||||
|
type Device struct {
|
||||||
|
bus oled.Bus
|
||||||
|
buffer pixel.Image[pixel.Monochrome]
|
||||||
|
width int16
|
||||||
|
height int16
|
||||||
|
bufferSize int16
|
||||||
|
vccState VccMode
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config is the configuration for the display
|
||||||
|
type Config struct {
|
||||||
|
Width int16
|
||||||
|
Height int16
|
||||||
|
VccState VccMode
|
||||||
|
}
|
||||||
|
|
||||||
|
type VccMode uint8
|
||||||
|
|
||||||
|
// Configure initializes the display with default configuration
|
||||||
|
func (d *Device) Configure(cfg Config) error {
|
||||||
|
if cfg.Width != 0 {
|
||||||
|
d.width = cfg.Width
|
||||||
|
} else {
|
||||||
|
d.width = 128
|
||||||
|
}
|
||||||
|
if cfg.Height != 0 {
|
||||||
|
d.height = cfg.Height
|
||||||
|
} else {
|
||||||
|
d.height = 64
|
||||||
|
}
|
||||||
|
if cfg.VccState != 0 {
|
||||||
|
d.vccState = cfg.VccState
|
||||||
|
} else {
|
||||||
|
d.vccState = SWITCHCAPVCC
|
||||||
|
}
|
||||||
|
d.bufferSize = d.width * d.height / 8
|
||||||
|
d.buffer = pixel.NewImage[pixel.Monochrome](int(d.width), int(d.height)) //make([]byte, d.bufferSize)
|
||||||
|
|
||||||
|
time.Sleep(100 * time.Nanosecond)
|
||||||
|
d.Command(DISPLAYOFF)
|
||||||
|
d.Command(SETDISPLAYCLOCKDIV)
|
||||||
|
d.Command(0x80)
|
||||||
|
d.Command(SETMULTIPLEX)
|
||||||
|
d.Command(uint8(d.height - 1))
|
||||||
|
d.Command(SETDISPLAYOFFSET)
|
||||||
|
d.Command(0x0)
|
||||||
|
d.Command(SETSTARTLINE | 0x0)
|
||||||
|
d.Command(CHARGEPUMP)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x10)
|
||||||
|
} else {
|
||||||
|
d.Command(0x14)
|
||||||
|
}
|
||||||
|
d.Command(MEMORYMODE)
|
||||||
|
d.Command(0x00)
|
||||||
|
d.Command(SEGREMAP | 0x1)
|
||||||
|
d.Command(COMSCANDEC)
|
||||||
|
|
||||||
|
if (d.width == 128 && d.height == 64) || (d.width == 64 && d.height == 48) { // 128x64 or 64x48
|
||||||
|
d.Command(SETCOMPINS)
|
||||||
|
d.Command(0x12)
|
||||||
|
d.Command(SETCONTRAST)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x9F)
|
||||||
|
} else {
|
||||||
|
d.Command(0xCF)
|
||||||
|
}
|
||||||
|
} else if d.width == 128 && d.height == 32 { // 128x32
|
||||||
|
d.Command(SETCOMPINS)
|
||||||
|
d.Command(0x02)
|
||||||
|
d.Command(SETCONTRAST)
|
||||||
|
d.Command(0x8F)
|
||||||
|
} else if d.width == 96 && d.height == 16 { // 96x16
|
||||||
|
d.Command(SETCOMPINS)
|
||||||
|
d.Command(0x2)
|
||||||
|
d.Command(SETCONTRAST)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x10)
|
||||||
|
} else {
|
||||||
|
d.Command(0xAF)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("sh1106: no configuration for %dx%d", d.width, d.height)
|
||||||
|
}
|
||||||
|
|
||||||
|
d.Command(SETPRECHARGE)
|
||||||
|
if d.vccState == EXTERNALVCC {
|
||||||
|
d.Command(0x22)
|
||||||
|
} else {
|
||||||
|
d.Command(0xF1)
|
||||||
|
}
|
||||||
|
d.Command(SETVCOMDETECT)
|
||||||
|
d.Command(0x40)
|
||||||
|
d.Command(DISPLAYALLON_RESUME)
|
||||||
|
d.Command(NORMALDISPLAY)
|
||||||
|
d.Command(DEACTIVATE_SCROLL)
|
||||||
|
d.Command(DISPLAYON)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearBuffer clears the image buffer
|
||||||
|
func (d *Device) ClearBuffer() {
|
||||||
|
d.buffer.Clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearDisplay clears the image buffer and clear the display
|
||||||
|
func (d *Device) ClearDisplay() {
|
||||||
|
d.buffer.Clear()
|
||||||
|
d.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh sends the whole buffer to the screen
|
||||||
|
func (d *Device) Refresh() error {
|
||||||
|
// In the 128x64 (SPI) screen resetting to 0x0 after 128 times corrupt the buffer
|
||||||
|
// Since we're printing the whole buffer, avoid resetting it
|
||||||
|
if d.width != 128 || d.height != 64 {
|
||||||
|
d.Command(COLUMNADDR)
|
||||||
|
d.Command(0)
|
||||||
|
d.Command(uint8(d.width - 1))
|
||||||
|
d.Command(PAGEADDR)
|
||||||
|
d.Command(0)
|
||||||
|
d.Command(uint8(d.height/8) - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := d.buffer.RawBuffer()
|
||||||
|
for pg := uint8(0); pg < uint8(d.height/8); pg++ {
|
||||||
|
d.Command(0xB0 | (pg & 0x07)) // SET_PAGE_ADDR
|
||||||
|
d.Command(SETLOWCOLUMN | 2)
|
||||||
|
d.Command(SETHIGHCOLUMN | 0)
|
||||||
|
d.Tx(raw[uint16(pg)*0x80:uint16(pg+1)*0x80], false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPixel enables or disables a pixel in the buffer
|
||||||
|
// color.RGBA{0, 0, 0, 255} is consider transparent, anything else
|
||||||
|
// with enable a pixel on the screen
|
||||||
|
func (d *Device) SetPixel(x int16, y int16, c color.Color) {
|
||||||
|
/*
|
||||||
|
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
byteIndex := x + (y/8)*d.width
|
||||||
|
if c.R != 0 || c.G != 0 || c.B != 0 {
|
||||||
|
d.buffer[byteIndex] |= 1 << uint8(y%8)
|
||||||
|
} else {
|
||||||
|
d.buffer[byteIndex] &^= 1 << uint8(y%8)
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
c = pixel.MonochromeModel.Convert(c)
|
||||||
|
d.buffer.SetPixel(int(x), int(y), c.(pixel.Monochrome))
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPixel returns if the specified pixel is on (true) or off (false)
|
||||||
|
func (d *Device) GetPixel(x int16, y int16) color.Color {
|
||||||
|
/*
|
||||||
|
if x < 0 || x >= d.width || y < 0 || y >= d.height {
|
||||||
|
return pixel.Off
|
||||||
|
}
|
||||||
|
byteIndex := x + (y/8)*d.width
|
||||||
|
return (d.buffer[byteIndex] >> uint8(y%8) & 0x1) == 1
|
||||||
|
*/
|
||||||
|
return d.buffer.GetPixel(int(x), int(y))
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// SetBuffer changes the whole buffer at once
|
||||||
|
func (d *Device) SetBuffer(buffer []byte) error {
|
||||||
|
if int16(len(buffer)) != d.bufferSize {
|
||||||
|
//return ErrBuffer
|
||||||
|
return errors.New("wrong size buffer")
|
||||||
|
}
|
||||||
|
for i := int16(0); i < d.bufferSize; i++ {
|
||||||
|
d.buffer[i] = buffer[i]
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Command sends a command to the display
|
||||||
|
func (d *Device) Command(command uint8) error {
|
||||||
|
return d.bus.Tx([]byte{command}, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tx sends data to the display
|
||||||
|
func (d *Device) Tx(data []byte, isCommand bool) error {
|
||||||
|
return d.bus.Tx(data, isCommand)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* display.Image interface methods */
|
||||||
|
|
||||||
|
func (d *Device) At(x, y int) color.Color {
|
||||||
|
return d.buffer.At(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Bounds() image.Rectangle {
|
||||||
|
return d.buffer.Bounds()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (Device) ColorModel() color.Model {
|
||||||
|
return pixel.MonochromeModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Halt() error {
|
||||||
|
return d.bus.Halt()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Set(x, y int, c color.Color) {
|
||||||
|
d.buffer.Set(x, y, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the current size of the display.
|
||||||
|
func (d *Device) Size() image.Point {
|
||||||
|
return image.Pt(int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) String() string {
|
||||||
|
return "sh1106@" + d.bus.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
/* display.imageDrawer interface methods */
|
||||||
|
|
||||||
|
func (d *Device) DrawImage(img image.Image) error {
|
||||||
|
draw.Draw(d.buffer, d.buffer.Bounds(), img, image.Point{}, draw.Src)
|
||||||
|
return d.Refresh()
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Package ssd1305 provides a driver for the SSD1305 OLED controller.
|
||||||
|
package ssd1305
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/i2c"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
var defaultInfo = display.MonochromeDisplayInfo{
|
||||||
|
ResetPulseWidth: 100 * time.Millisecond,
|
||||||
|
ResetWait: 100 * time.Millisecond,
|
||||||
|
PreChipEnableWait: 10 * time.Nanosecond,
|
||||||
|
PostChipEnableWait: 20 * time.Nanosecond,
|
||||||
|
DataSetupTime: 40 * time.Nanosecond,
|
||||||
|
WritePulseWidth: 150 * time.Nanosecond,
|
||||||
|
Width: 128,
|
||||||
|
Height: 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
spiMode spi.Mode = spi.Mode0
|
||||||
|
spiSpeed physic.Frequency = 4 * 1000 * 1000
|
||||||
|
maxPixels = 256 * 32
|
||||||
|
)
|
||||||
|
|
||||||
|
var emptyBuf [maxPixels >> 3]byte
|
||||||
|
|
||||||
|
type Device struct {
|
||||||
|
hal display.MonochromeDisplay
|
||||||
|
info display.MonochromeDisplayInfo
|
||||||
|
buf pixel.Image[pixel.Monochrome]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewI2C(bus i2c.Bus, addr uint16, width, height int) (*Device, error) {
|
||||||
|
if addr == 0 {
|
||||||
|
addr = 0x3c
|
||||||
|
}
|
||||||
|
|
||||||
|
if width <= 0 {
|
||||||
|
width = int(defaultInfo.Width)
|
||||||
|
}
|
||||||
|
if height <= 0 {
|
||||||
|
height = int(defaultInfo.Height)
|
||||||
|
}
|
||||||
|
|
||||||
|
var info = new(display.MonochromeDisplayInfo)
|
||||||
|
*info = defaultInfo
|
||||||
|
info.Width = uint16(width)
|
||||||
|
info.Height = uint16(height)
|
||||||
|
|
||||||
|
c := &i2c.Dev{Bus: bus, Addr: addr}
|
||||||
|
d := &Device{
|
||||||
|
hal: display.NewSSD13xxDisplay(c, *info),
|
||||||
|
info: *info,
|
||||||
|
buf: pixel.NewImage[pixel.Monochrome](width, height),
|
||||||
|
}
|
||||||
|
if err := d.configure(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSPI(port spi.Port, reset gpio.PinOut, width, height uint8) (*Device, error) {
|
||||||
|
var info = new(display.MonochromeDisplayInfo)
|
||||||
|
*info = defaultInfo
|
||||||
|
info.Reset = reset
|
||||||
|
|
||||||
|
c, err := port.Connect(spiSpeed, spiMode, 8)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := &Device{
|
||||||
|
hal: display.NewSSD13xxDisplay(c, *info),
|
||||||
|
}
|
||||||
|
if err := d.configure(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) configure() (err error) {
|
||||||
|
if err = d.hal.Init(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = d.hal.StartTransfer(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = d.hal.SendCommand([]byte{
|
||||||
|
0xae, // Set display off
|
||||||
|
0xd5, 0x80, // Set display clock divide ratio/oscillator frequency
|
||||||
|
0xa8, 0x3f, // Set multiplex ratio
|
||||||
|
0xd3, uint8(d.info.Width), // Set display offset
|
||||||
|
0x40, // Set display start line to 0
|
||||||
|
0x20, 0x00, // Set horizontal addressing mode
|
||||||
|
0xa1, // Set segment remap a0/a1
|
||||||
|
0xc8, // Set scan direction (c0: normal, c8: reverse,
|
||||||
|
0xda, 0x12, // Set com pins hardware configuration
|
||||||
|
0x81, 0xcf, // Set contrast control
|
||||||
|
0xd9, 0xf1, // Set pre-charge period
|
||||||
|
0xdb, 0x40, // Set VCOMH deselect level
|
||||||
|
0x2e, // Deactivate scroll
|
||||||
|
0xa4, // Set display output RAM to display
|
||||||
|
0xa6, // Set normal display mode
|
||||||
|
}); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.hal.EndTransfer()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Clear() error {
|
||||||
|
d.buf.FillSolidColor(pixel.Off)
|
||||||
|
return d.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Refresh() (err error) {
|
||||||
|
_ = d.hal.SendCommand([]byte{0x15, 0, byte(defaultInfo.Width) - 1}) // Set column address
|
||||||
|
_ = d.hal.SendCommand([]byte{0x75, 0, byte(defaultInfo.Height) - 1}) // Set row address
|
||||||
|
buf := d.buf.RawBuffer()
|
||||||
|
for i := 0; i < len(buf); i += 16 {
|
||||||
|
if err = d.hal.SendData(buf[i : i+16]); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Size() (width, height int) {
|
||||||
|
return d.buf.Bounds().Dx(), d.buf.Bounds().Dy()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Bounds() image.Rectangle {
|
||||||
|
return d.buf.Bounds()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) ColorModel() color.Model {
|
||||||
|
return pixel.MonochromeModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) At(x, y int) color.Color {
|
||||||
|
return d.buf.At(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Set(x, y int, c color.Color) {
|
||||||
|
d.buf.Set(x, y, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface check
|
||||||
|
var (
|
||||||
|
// _ display.Display = &Device{}
|
||||||
|
// _ display.Image = &Device{}
|
||||||
|
)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package ssd1306
|
||||||
|
|
||||||
|
const (
|
||||||
|
_CHARGEPUMP = 0x8D
|
||||||
|
_COLUMNADDR = 0x21
|
||||||
|
_COMSCANDEC = 0xC8
|
||||||
|
_COMSCANINC = 0xC0
|
||||||
|
_DISPLAYALLON = 0xA5
|
||||||
|
_DISPLAYALLON_RESUME = 0xA4
|
||||||
|
_DISPLAYOFF = 0xAE
|
||||||
|
_DISPLAYON = 0xAF
|
||||||
|
_EXTERNALVCC = 0x1
|
||||||
|
_INVERTDISPLAY = 0xA7
|
||||||
|
_MEMORYMODE = 0x20
|
||||||
|
_NORMALDISPLAY = 0xA6
|
||||||
|
_PAGEADDR = 0x22
|
||||||
|
_PAGESTARTADDRESS = 0xB0
|
||||||
|
_SEGREMAP = 0xA0
|
||||||
|
_SETCOMPINS = 0xDA
|
||||||
|
_SETCONTRAST = 0x81
|
||||||
|
_SETDISPLAYCLOCKDIV = 0xD5
|
||||||
|
_SETDISPLAYOFFSET = 0xD3
|
||||||
|
_SETHIGHCOLUMN = 0x10
|
||||||
|
_SETLOWCOLUMN = 0x00
|
||||||
|
_SETMULTIPLEX = 0xA8
|
||||||
|
_SETPRECHARGE = 0xD9
|
||||||
|
_SETSEGMENTREMAP = 0xA1
|
||||||
|
_SETSTARTLINE = 0x40
|
||||||
|
_SETVCOMDETECT = 0xDB
|
||||||
|
_SWITCHCAPVCC = 0x2
|
||||||
|
)
|
||||||
|
|
||||||
|
// FrameRate determines scrolling speed.
|
||||||
|
type FrameRate byte
|
||||||
|
|
||||||
|
// Possible frame rates. The value determines the number of refreshes between
|
||||||
|
// movement. The lower value, the higher speed.
|
||||||
|
const (
|
||||||
|
FrameRate2 FrameRate = 7
|
||||||
|
FrameRate3 FrameRate = 4
|
||||||
|
FrameRate4 FrameRate = 5
|
||||||
|
FrameRate5 FrameRate = 0
|
||||||
|
FrameRate25 FrameRate = 6
|
||||||
|
FrameRate64 FrameRate = 1
|
||||||
|
FrameRate128 FrameRate = 2
|
||||||
|
FrameRate256 FrameRate = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
// Orientation is used for scrolling.
|
||||||
|
type Orientation byte
|
||||||
|
|
||||||
|
// Possible orientations for scrolling.
|
||||||
|
const (
|
||||||
|
Left Orientation = 0x27
|
||||||
|
Right Orientation = 0x26
|
||||||
|
UpRight Orientation = 0x29
|
||||||
|
UpLeft Orientation = 0x2A
|
||||||
|
)
|
||||||
@@ -0,0 +1,562 @@
|
|||||||
|
package ssd1306
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/draw"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"periph.io/x/conn/v3"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/gpio/gpioreg"
|
||||||
|
"periph.io/x/conn/v3/i2c"
|
||||||
|
"periph.io/x/conn/v3/i2c/i2creg"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
"periph.io/x/conn/v3/spi/spireg"
|
||||||
|
"periph.io/x/devices/v3/ssd1306/image1bit"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("ssd1306", newDevice)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultOpts is the recommended default options.
|
||||||
|
var DefaultOpts = Opts{
|
||||||
|
W: 128,
|
||||||
|
H: 64,
|
||||||
|
Addr: 0x3c,
|
||||||
|
Rotated: false,
|
||||||
|
MirrorVertical: false,
|
||||||
|
MirrorHorizontal: false,
|
||||||
|
Sequential: false,
|
||||||
|
SwapTopBottom: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opts defines the options for the device.
|
||||||
|
type Opts struct {
|
||||||
|
W int
|
||||||
|
H int
|
||||||
|
|
||||||
|
// Addr is the I2C address.
|
||||||
|
Addr uint16
|
||||||
|
|
||||||
|
// Rotated determines if the display is rotated by 180°.
|
||||||
|
//
|
||||||
|
// Deprecated: Use MirrorVertical and MirrorHorizontal instead.
|
||||||
|
Rotated bool
|
||||||
|
|
||||||
|
// Sequential corresponds to the Sequential/Alternative COM pin configuration
|
||||||
|
// in the OLED panel hardware. Try toggling this if half the rows appear to be
|
||||||
|
// missing on your display.
|
||||||
|
Sequential bool
|
||||||
|
|
||||||
|
// MirrorVertical corresponds to the COM remap configuration in the OLED panel
|
||||||
|
// hardware. Try toggling this if the display is flipped vertically.
|
||||||
|
// Overwrites Rotated.
|
||||||
|
MirrorVertical bool
|
||||||
|
|
||||||
|
// MirrorHorizontal corresponds to the SEG remap configuration in the OLED panel
|
||||||
|
// hardware. Try toggling this if the display is flipped horizontally.
|
||||||
|
// Overwrites Rotated.
|
||||||
|
MirrorHorizontal bool
|
||||||
|
|
||||||
|
// SwapTopBottom corresponds to the Left/Right remap COM pin configuration in
|
||||||
|
// the OLED panel hardware. Try toggling this if the top and bottom halves of
|
||||||
|
// your display are swapped.
|
||||||
|
SwapTopBottom bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Dev struct {
|
||||||
|
// Communication
|
||||||
|
c conn.Conn
|
||||||
|
dc gpio.PinOut
|
||||||
|
spi bool
|
||||||
|
|
||||||
|
// Display size controlled by the SSD1306.
|
||||||
|
rect image.Rectangle
|
||||||
|
|
||||||
|
// Mutable
|
||||||
|
// See page 25 for the GDDRAM pages structure.
|
||||||
|
// Narrow screen will waste the end of each page.
|
||||||
|
// Short screen will ignore the lower pages.
|
||||||
|
// There is 8 pages, each covering an horizontal band of 8 pixels high (1
|
||||||
|
// byte) for 128 bytes.
|
||||||
|
// 8*128 = 1024 bytes total for 128x64 display.
|
||||||
|
buffer []byte
|
||||||
|
// next is lazy initialized on first Draw(). Write() skips this buffer.
|
||||||
|
next *image1bit.VerticalLSB
|
||||||
|
startPage, endPage int
|
||||||
|
startCol, endCol int
|
||||||
|
scrolled bool
|
||||||
|
halted bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDevice(config *config.Display) (display.Display, error) {
|
||||||
|
width, height, err := display.ParseSize(config.Size, DefaultOpts.W, DefaultOpts.H)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid size %q: %w", config.Size, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := new(Opts)
|
||||||
|
*opts = DefaultOpts
|
||||||
|
opts.W = width
|
||||||
|
opts.H = height
|
||||||
|
|
||||||
|
if config.Bus == "" || strings.HasPrefix(config.Bus, "i2c") {
|
||||||
|
return newI2C(config, opts)
|
||||||
|
}
|
||||||
|
return newSPI(config, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newI2C(config *config.Display, opts *Opts) (display.Display, error) {
|
||||||
|
addr, err := display.ParseI2CAddress(config.Address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid I2C address %q: %w", config.Address, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log := logrus.WithFields(logrus.Fields{
|
||||||
|
"type": "ssd1306",
|
||||||
|
"size": fmt.Sprintf("%dx%d", opts.W, opts.H),
|
||||||
|
"mode": "i2c",
|
||||||
|
})
|
||||||
|
log.WithField("bus", config.Bus).Debug("opening I2C bus")
|
||||||
|
|
||||||
|
bus, err := i2creg.Open(config.Bus)
|
||||||
|
if err != nil {
|
||||||
|
log.WithField("bus", config.Bus).WithError(err).Warn("opening I2C bus failed")
|
||||||
|
return nil, fmt.Errorf("error opening I2C bus %q: %w", config.Bus, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log = log.WithFields(logrus.Fields{
|
||||||
|
"i2c_bus": bus.String(),
|
||||||
|
"i2c_addr": fmt.Sprintf("%#02x", addr),
|
||||||
|
})
|
||||||
|
log.Debug("starting display")
|
||||||
|
return newDev(&i2c.Dev{Bus: bus, Addr: addr}, opts, false, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSPI(config *config.Display, opts *Opts) (display.Display, error) {
|
||||||
|
var (
|
||||||
|
dc gpio.PinOut
|
||||||
|
bits = 9
|
||||||
|
)
|
||||||
|
if config.DC != "" {
|
||||||
|
if dc = gpioreg.ByName(config.DC); dc == gpio.INVALID {
|
||||||
|
return nil, fmt.Errorf("invalid dc pin %q", config.DC)
|
||||||
|
}
|
||||||
|
bits = 8
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := spireg.Open(config.Port)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("opening SPI port %q failed: %w", config.Port, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := port.Connect(3300*physic.KiloHertz, spi.Mode0, bits)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("connecting on SPI port %q failed: %w", config.Port, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return newDev(c, opts, true, dc)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) String() string {
|
||||||
|
if d.spi {
|
||||||
|
return fmt.Sprintf("ssd1360.Dev{%s, %s, %s}", d.c, d.dc, d.rect.Max)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("ssd1360.Dev{%s, %s}", d.c, d.rect.Max)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ColorModel implements display.Drawer.
|
||||||
|
//
|
||||||
|
// It is a one bit color model, as implemented by image1bit.Bit.
|
||||||
|
func (d *Dev) ColorModel() color.Model {
|
||||||
|
return image1bit.BitModel
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bounds implements display.Drawer. Min is guaranteed to be {0, 0}.
|
||||||
|
func (d *Dev) Bounds() image.Rectangle {
|
||||||
|
return d.rect
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draw implements display.Drawer.
|
||||||
|
//
|
||||||
|
// It draws synchronously, once this function returns, the display is updated.
|
||||||
|
// It means that on slow bus (I²C), it may be preferable to defer Draw() calls
|
||||||
|
// to a background goroutine.
|
||||||
|
func (d *Dev) Draw(r image.Rectangle, src image.Image, sp image.Point) error {
|
||||||
|
var next []byte
|
||||||
|
if img, ok := src.(*image1bit.VerticalLSB); ok && r == d.rect && img.Rect == d.rect && sp.X == 0 && sp.Y == 0 {
|
||||||
|
// Exact size, full frame, image1bit encoding: fast path!
|
||||||
|
next = img.Pix
|
||||||
|
} else {
|
||||||
|
// Double buffering.
|
||||||
|
if d.next == nil {
|
||||||
|
d.next = image1bit.NewVerticalLSB(d.rect)
|
||||||
|
}
|
||||||
|
next = d.next.Pix
|
||||||
|
draw.Src.Draw(d.next, r, src, sp)
|
||||||
|
}
|
||||||
|
return d.drawInternal(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawImage implements display.imageDrawer.
|
||||||
|
func (d *Dev) DrawImage(src image.Image) error {
|
||||||
|
return d.Draw(d.Bounds(), src, image.Point{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes a buffer of pixels to the display.
|
||||||
|
//
|
||||||
|
// The format is unsual as each byte represent 8 vertical pixels at a time. The
|
||||||
|
// format is horizontal bands of 8 pixels high.
|
||||||
|
//
|
||||||
|
// This function accepts the content of image1bit.VerticalLSB.Pix.
|
||||||
|
func (d *Dev) Write(pixels []byte) (int, error) {
|
||||||
|
if len(pixels) != len(d.buffer) {
|
||||||
|
return 0, fmt.Errorf("ssd1306: invalid pixel stream length; expected %d bytes, got %d bytes", len(d.buffer), len(pixels))
|
||||||
|
}
|
||||||
|
// Write() skips d.next so it saves 1kb of RAM.
|
||||||
|
if err := d.drawInternal(pixels); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(pixels), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scroll scrolls an horizontal band.
|
||||||
|
//
|
||||||
|
// Only one scrolling operation can happen at a time.
|
||||||
|
//
|
||||||
|
// Both startLine and endLine must be multiples of 8.
|
||||||
|
//
|
||||||
|
// Use -1 for endLine to extend to the bottom of the display.
|
||||||
|
func (d *Dev) Scroll(o Orientation, rate FrameRate, startLine, endLine int) error {
|
||||||
|
h := d.rect.Dy()
|
||||||
|
if endLine == -1 {
|
||||||
|
endLine = h
|
||||||
|
}
|
||||||
|
if startLine >= endLine {
|
||||||
|
return fmt.Errorf("startLine (%d) must be lower than endLine (%d)", startLine, endLine)
|
||||||
|
}
|
||||||
|
if startLine&7 != 0 || startLine < 0 || startLine >= h {
|
||||||
|
return fmt.Errorf("invalid startLine %d", startLine)
|
||||||
|
}
|
||||||
|
if endLine&7 != 0 || endLine < 0 || endLine > h {
|
||||||
|
return fmt.Errorf("invalid endLine %d", endLine)
|
||||||
|
}
|
||||||
|
|
||||||
|
startPage := uint8(startLine / 8)
|
||||||
|
endPage := uint8(endLine / 8)
|
||||||
|
d.scrolled = true
|
||||||
|
if o == Left || o == Right {
|
||||||
|
// page 28
|
||||||
|
// <op>, dummy, <start page>, <rate>, <end page>, <dummy>, <dummy>, <ENABLE>
|
||||||
|
return d.sendCommand([]byte{byte(o), 0x00, startPage, byte(rate), endPage - 1, 0x00, 0xFF, 0x2F})
|
||||||
|
}
|
||||||
|
// page 29
|
||||||
|
// <op>, dummy, <start page>, <rate>, <end page>, <offset>, <ENABLE>
|
||||||
|
// page 30: 0xA3 permits to set rows for scroll area.
|
||||||
|
return d.sendCommand([]byte{byte(o), 0x00, startPage, byte(rate), endPage - 1, 0x01, 0x2F})
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopScroll stops any scrolling previously set and resets the screen.
|
||||||
|
func (d *Dev) StopScroll() error {
|
||||||
|
return d.sendCommand([]byte{0x2E})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetContrast changes the screen contrast.
|
||||||
|
//
|
||||||
|
// Note: values other than 0xff do not seem useful...
|
||||||
|
func (d *Dev) SetContrast(level byte) error {
|
||||||
|
return d.sendCommand([]byte{0x81, level})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDisplayStartLine causes the display to start from startLine, effectively
|
||||||
|
// scrolling the screen to that position.
|
||||||
|
//
|
||||||
|
// startLine must be between 0 and 63.
|
||||||
|
func (d *Dev) SetDisplayStartLine(startLine byte) error {
|
||||||
|
if startLine > 63 {
|
||||||
|
return fmt.Errorf("ssd1306: invalid startLine %d", startLine)
|
||||||
|
}
|
||||||
|
return d.sendCommand([]byte{_SETSTARTLINE | startLine})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Halt turns off the display.
|
||||||
|
//
|
||||||
|
// Sending any other command afterward reenables the display.
|
||||||
|
func (d *Dev) Halt() error {
|
||||||
|
d.halted = false
|
||||||
|
err := d.sendCommand([]byte{0xAE})
|
||||||
|
if err == nil {
|
||||||
|
d.halted = true
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invert the display (black on white vs white on black).
|
||||||
|
func (d *Dev) Invert(blackOnWhite bool) error {
|
||||||
|
b := []byte{0xA6}
|
||||||
|
if blackOnWhite {
|
||||||
|
b[0] = 0xA7
|
||||||
|
}
|
||||||
|
return d.sendCommand(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
// newDev is the common initialization code that is independent of the
|
||||||
|
// communication protocol (I²C or SPI) being used.
|
||||||
|
func newDev(c conn.Conn, opts *Opts, usingSPI bool, dc gpio.PinOut) (*Dev, error) {
|
||||||
|
if opts.W < 8 || opts.W > 128 || opts.W&7 != 0 {
|
||||||
|
return nil, fmt.Errorf("ssd1306: invalid width %d", opts.W)
|
||||||
|
}
|
||||||
|
if opts.H < 8 || opts.H > 64 || opts.H&7 != 0 {
|
||||||
|
return nil, fmt.Errorf("ssd1306: invalid height %d", opts.H)
|
||||||
|
}
|
||||||
|
|
||||||
|
nbPages := opts.H / 8
|
||||||
|
pageSize := opts.W
|
||||||
|
d := &Dev{
|
||||||
|
c: c,
|
||||||
|
spi: usingSPI,
|
||||||
|
dc: dc,
|
||||||
|
rect: image.Rect(0, 0, opts.W, opts.H),
|
||||||
|
buffer: make([]byte, nbPages*pageSize),
|
||||||
|
startPage: 0,
|
||||||
|
endPage: nbPages,
|
||||||
|
startCol: 0,
|
||||||
|
endCol: opts.W,
|
||||||
|
// Signal that the screen must be redrawn on first draw().
|
||||||
|
scrolled: true,
|
||||||
|
}
|
||||||
|
if err := d.sendCommand(getInitCmd(opts)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getInitCmd(opts *Opts) []byte {
|
||||||
|
// Set COM output scan direction; C0 means normal; C8 means reversed
|
||||||
|
comScan := byte(0xC8)
|
||||||
|
// See page 40.
|
||||||
|
columnAddr := byte(0xA1)
|
||||||
|
if opts.Rotated {
|
||||||
|
// Change order both horizontally and vertically.
|
||||||
|
comScan = 0xC0
|
||||||
|
columnAddr = byte(0xA0)
|
||||||
|
}
|
||||||
|
if opts.MirrorVertical {
|
||||||
|
comScan = byte(0xC0)
|
||||||
|
}
|
||||||
|
if opts.MirrorHorizontal {
|
||||||
|
columnAddr = byte(0xA0)
|
||||||
|
}
|
||||||
|
// See page 40.
|
||||||
|
hwLayout := byte(0x02)
|
||||||
|
if !opts.Sequential {
|
||||||
|
hwLayout |= 0x10
|
||||||
|
}
|
||||||
|
if opts.SwapTopBottom {
|
||||||
|
hwLayout |= 0x20
|
||||||
|
}
|
||||||
|
// Set the max frequency. The problem with I²C is that it creates visible
|
||||||
|
// tear down. On SPI at high speed this is not visible. Page 23 pictures how
|
||||||
|
// to avoid tear down. For now default to max frequency.
|
||||||
|
freq := byte(0xF0)
|
||||||
|
|
||||||
|
// Initialize the device by fully resetting all values.
|
||||||
|
// Page 64 has the full recommended flow.
|
||||||
|
// Page 28 lists all the commands.
|
||||||
|
return []byte{
|
||||||
|
0xAE, // Display off
|
||||||
|
0xD3, 0x00, // Set display offset; 0
|
||||||
|
0x40, // Start display start line; 0
|
||||||
|
columnAddr, // Set segment remap; RESET is column 127.
|
||||||
|
comScan, //
|
||||||
|
0xDA, hwLayout, // Set COM pins hardware configuration; see page 40
|
||||||
|
0x81, 0xFF, // Set max contrast
|
||||||
|
0xA4, // Set display to use GDDRAM content
|
||||||
|
0xA6, // Set normal display (0xA7 for inverted 0=lit, 1=dark)
|
||||||
|
0xD5, freq, // Set osc frequency and divide ratio; power on reset value is 0x80.
|
||||||
|
0x8D, 0x14, // Enable charge pump regulator; page 62
|
||||||
|
0xD9, 0xF1, // Set pre-charge period; from adafruit driver
|
||||||
|
0xDB, 0x40, // Set Vcomh deselect level; page 32
|
||||||
|
0x2E, // Deactivate scroll
|
||||||
|
0xA8, byte(opts.H - 1), // Set multiplex ratio (number of lines to display)
|
||||||
|
0x20, 0x00, // Set memory addressing mode to horizontal
|
||||||
|
0x21, 0, uint8(opts.W - 1), // Set column address (Width)
|
||||||
|
0x22, 0, uint8(opts.H/8 - 1), // Set page address (Pages)
|
||||||
|
0xAF, // Display on
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) calculateSubset(next []byte) (int, int, int, int, bool) {
|
||||||
|
w := d.rect.Dx()
|
||||||
|
h := d.rect.Dy()
|
||||||
|
startPage := 0
|
||||||
|
endPage := h / 8
|
||||||
|
startCol := 0
|
||||||
|
endCol := w
|
||||||
|
if d.scrolled {
|
||||||
|
// Painting disable scrolling but if scrolling was enabled, this requires a
|
||||||
|
// full screen redraw.
|
||||||
|
d.scrolled = false
|
||||||
|
} else {
|
||||||
|
// Calculate the smallest square that need to be sent.
|
||||||
|
pageSize := w
|
||||||
|
|
||||||
|
// Top.
|
||||||
|
for ; startPage < endPage; startPage++ {
|
||||||
|
x := pageSize * startPage
|
||||||
|
y := pageSize * (startPage + 1)
|
||||||
|
if !bytes.Equal(d.buffer[x:y], next[x:y]) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Bottom.
|
||||||
|
for ; endPage > startPage; endPage-- {
|
||||||
|
x := pageSize * (endPage - 1)
|
||||||
|
y := pageSize * endPage
|
||||||
|
if !bytes.Equal(d.buffer[x:y], next[x:y]) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if startPage == endPage {
|
||||||
|
// Early exit, the image is exactly the same.
|
||||||
|
return 0, 0, 0, 0, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Left.
|
||||||
|
for ; startCol < endCol; startCol++ {
|
||||||
|
for i := startPage; i < endPage; i++ {
|
||||||
|
x := i*pageSize + startCol
|
||||||
|
if d.buffer[x] != next[x] {
|
||||||
|
goto breakLeft
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
breakLeft:
|
||||||
|
|
||||||
|
// Right.
|
||||||
|
for ; endCol > startCol; endCol-- {
|
||||||
|
for i := startPage; i < endPage; i++ {
|
||||||
|
x := i*pageSize + endCol - 1
|
||||||
|
if d.buffer[x] != next[x] {
|
||||||
|
goto breakRight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
breakRight:
|
||||||
|
}
|
||||||
|
return startPage, endPage, startCol, endCol, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawInternal sends image data to the controller.
|
||||||
|
func (d *Dev) drawInternal(next []byte) error {
|
||||||
|
startPage, endPage, startCol, endCol, skip := d.calculateSubset(next)
|
||||||
|
if skip {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
copy(d.buffer, next)
|
||||||
|
|
||||||
|
if d.startPage != startPage || d.endPage != endPage || d.startCol != startCol || d.endCol != endCol {
|
||||||
|
d.startPage = startPage
|
||||||
|
d.endPage = endPage
|
||||||
|
d.startCol = startCol
|
||||||
|
d.endCol = endCol
|
||||||
|
}
|
||||||
|
|
||||||
|
pageSize := d.rect.Dx()
|
||||||
|
for page := d.startPage; page < d.endPage; page++ {
|
||||||
|
err := d.sendCommand([]byte{
|
||||||
|
_PAGESTARTADDRESS | byte(page),
|
||||||
|
_SETLOWCOLUMN | (byte(d.startCol) & 0x0F),
|
||||||
|
_SETHIGHCOLUMN | (byte(d.startCol) >> 4),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pageStart := page * pageSize
|
||||||
|
err = d.sendData(d.buffer[pageStart+d.startCol : pageStart+d.endCol])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) sendData(c []byte) error {
|
||||||
|
if d.halted {
|
||||||
|
// Transparently enable the display.
|
||||||
|
if err := d.sendCommand(nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d.spi {
|
||||||
|
// 4-wire SPI.
|
||||||
|
if err := d.dc.Out(gpio.High); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return d.c.Tx(c, nil)
|
||||||
|
}
|
||||||
|
return d.c.Tx(append([]byte{i2cData}, c...), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) sendCommand(c []byte) error {
|
||||||
|
if d.halted {
|
||||||
|
// Transparently enable the display.
|
||||||
|
c = append([]byte{0xAF}, c...)
|
||||||
|
d.halted = false
|
||||||
|
}
|
||||||
|
if d.spi {
|
||||||
|
if d.dc == nil {
|
||||||
|
// 3-wire SPI.
|
||||||
|
return errors.New("ssd1306: 3-wire SPI mode is not yet implemented")
|
||||||
|
}
|
||||||
|
// 4-wire SPI.
|
||||||
|
if err := d.dc.Out(gpio.Low); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return d.c.Tx(c, nil)
|
||||||
|
}
|
||||||
|
return d.c.Tx(append([]byte{i2cCmd}, c...), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) At(x, y int) color.Color {
|
||||||
|
if d.next == nil {
|
||||||
|
return pixel.Off
|
||||||
|
}
|
||||||
|
return d.next.At(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) Set(x, y int, c color.Color) {
|
||||||
|
if d.next == nil {
|
||||||
|
d.next = image1bit.NewVerticalLSB(d.rect)
|
||||||
|
}
|
||||||
|
d.next.Set(x, y, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) Refresh() error {
|
||||||
|
if d.next == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return d.drawInternal(d.next.Pix)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dev) Size() image.Point {
|
||||||
|
return d.rect.Max
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
i2cCmd = 0x00 // I²C transaction has stream of command bytes
|
||||||
|
i2cData = 0x40 // I²C transaction has stream of data bytes
|
||||||
|
)
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
// Package ssd1326 provides a driver for the SSD1326 OLED controller.
|
||||||
|
package ssd1326
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"periph.io/x/conn/v3"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/i2c"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/display/ssd1xxx"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("ssd1326", New)
|
||||||
|
}
|
||||||
|
|
||||||
|
var defaultInfo = display.MonochromeDisplayInfo{
|
||||||
|
ResetPulseWidth: 100 * time.Millisecond,
|
||||||
|
ResetWait: 100 * time.Millisecond,
|
||||||
|
PreChipEnableWait: 15 * time.Nanosecond,
|
||||||
|
PostChipEnableWait: 20 * time.Nanosecond,
|
||||||
|
DataSetupTime: 40 * time.Nanosecond,
|
||||||
|
WritePulseWidth: 60 * time.Nanosecond,
|
||||||
|
Width: 256,
|
||||||
|
Height: 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
spiMode spi.Mode = spi.Mode0
|
||||||
|
spiSpeed physic.Frequency = 4 * 1000 * 1000
|
||||||
|
maxPixels = 256 * 32
|
||||||
|
)
|
||||||
|
|
||||||
|
var emptyBuf [maxPixels >> 3]byte
|
||||||
|
|
||||||
|
type Device struct {
|
||||||
|
name string
|
||||||
|
hal display.MonochromeDisplay
|
||||||
|
buf pixel.Image[pixel.Monochrome]
|
||||||
|
info display.MonochromeDisplayInfo
|
||||||
|
config *config.Display
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(config *config.Display) (display.Display, error) {
|
||||||
|
log := logrus.WithFields(logrus.Fields{
|
||||||
|
"type": "ssd1306",
|
||||||
|
"name": config.Name,
|
||||||
|
})
|
||||||
|
|
||||||
|
bus, err := ssd1xxx.NewBus(config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.WithField("connection", conn.String()).Debug("opening display connection")
|
||||||
|
return newDevice(config, conn, log)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDevice(config *config.Display, conn conn.Conn, log *logrus.Entry) (d *Device, err error) {
|
||||||
|
var info = new(display.MonochromeDisplayInfo)
|
||||||
|
*info = defaultInfo
|
||||||
|
|
||||||
|
d = &Device{
|
||||||
|
hal: display.NewSSD13xxDisplay(conn, *info),
|
||||||
|
info: *info,
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
|
||||||
|
switch conn := conn.(type) {
|
||||||
|
case i2c.Bus:
|
||||||
|
d.name = "SSD1306 I²C@" + conn.String()
|
||||||
|
case i2c.BusCloser:
|
||||||
|
d.name = "SSD1306 I²C@" + conn.String()
|
||||||
|
case spi.Conn:
|
||||||
|
d.name = "SSD1306 SPI@" + conn.String()
|
||||||
|
default:
|
||||||
|
d.name = "SSD1306"
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Trace("configuring display")
|
||||||
|
if err := d.configure(); err != nil {
|
||||||
|
return nil, fmt.Errorf("ssd1306: initial configuration failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewI2C(bus i2c.Bus, addr uint16) (*Device, error) {
|
||||||
|
if addr == 0 {
|
||||||
|
addr = 0x3c
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &i2c.Dev{Bus: bus, Addr: addr}
|
||||||
|
d := &Device{
|
||||||
|
hal: display.NewSSD13xxDisplay(c, defaultInfo),
|
||||||
|
buf: pixel.NewImage[pixel.Monochrome](int(defaultInfo.Width), int(defaultInfo.Height)),
|
||||||
|
}
|
||||||
|
if err := d.configure(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSPI(port spi.Port, reset gpio.PinOut) (*Device, error) {
|
||||||
|
var info = new(display.MonochromeDisplayInfo)
|
||||||
|
*info = defaultInfo
|
||||||
|
info.Reset = reset
|
||||||
|
|
||||||
|
c, err := port.Connect(spiSpeed, spiMode, 8)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := &Device{
|
||||||
|
hal: display.NewSSD13xxDisplay(c, *info),
|
||||||
|
}
|
||||||
|
if err := d.configure(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) configure() (err error) {
|
||||||
|
if err = d.hal.Init(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = d.hal.StartTransfer(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
0xa0 command: 0x0a0 ***abcde
|
||||||
|
a: 1: mono mode
|
||||||
|
b: 0: horizontal (1: vertical) address increment
|
||||||
|
c: 1: enable bit remap
|
||||||
|
d: 1: COM remap
|
||||||
|
e: 1: Column remap
|
||||||
|
*/
|
||||||
|
|
||||||
|
if err = d.hal.SendCommand([]byte{
|
||||||
|
0xfd, 0x12, // Unlock OLED driver IC MCU interface from entering command. i.e: Accept commands
|
||||||
|
0xae, // Set display off
|
||||||
|
0xa8, 0x1f, // Set multiplex ratio(1 to 64)
|
||||||
|
0xa1, 0x00, // Set display start line
|
||||||
|
0xa2, 0x00, // Set display offset, shift mapping RAM counter
|
||||||
|
0xad, 0x02, // Set master configuration: disable embedded DC-DC, enable internal VCOMH
|
||||||
|
0xa0, 0x06, // Set remap and data format
|
||||||
|
0x86, 0x00, // Set current range
|
||||||
|
0xb7, // Set default gray scale table
|
||||||
|
0x81, 0x27, // Contrast, brightness 0..128
|
||||||
|
0xb1, 0x71, // Phase length
|
||||||
|
0xb3, 0xf0, // Set display clock divide ratio/oscillator frequency (set clock as 135 frames/sec)
|
||||||
|
0xbb, 0x35, 0xff, // Set pre-charge
|
||||||
|
0xbc, 0x1f, // Pre-charge voltage level
|
||||||
|
0xbe, 0x0f, // VCOMH voltage
|
||||||
|
0xbf, 0x02 | 0x0d, // VSL voltage level
|
||||||
|
0xa4, // Normal display mode
|
||||||
|
}); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.hal.EndTransfer()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) String() string {
|
||||||
|
return d.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Halt() error {
|
||||||
|
return d.hal.Halt()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Clear() error {
|
||||||
|
d.buf.FillSolidColor(pixel.Off)
|
||||||
|
//copy(d.buf.Pix[:], emptyBuf[:])
|
||||||
|
return d.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Refresh() (err error) {
|
||||||
|
_ = d.hal.SendCommand([]byte{0x15, 0, byte(defaultInfo.Width) - 1}) // Set column address
|
||||||
|
_ = d.hal.SendCommand([]byte{0x75, 0, byte(defaultInfo.Height) - 1}) // Set row address
|
||||||
|
buf := d.buf.RawBuffer()
|
||||||
|
for i := 0; i < len(buf); i += 16 {
|
||||||
|
if err = d.hal.SendData(buf[i : i+16]); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Size() image.Point {
|
||||||
|
return d.buf.Bounds().Size()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Bounds() image.Rectangle {
|
||||||
|
return d.buf.Bounds()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (Device) ColorModel() color.Model {
|
||||||
|
return pixel.MonochromeModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) At(x, y int) color.Color {
|
||||||
|
return d.buf.At(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Device) Set(x, y int, c color.Color) {
|
||||||
|
d.buf.Set(x, y, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface check
|
||||||
|
var (
|
||||||
|
// _ display.Display = &Device{}
|
||||||
|
// _ display.Image = &Device{}
|
||||||
|
)
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package st7789
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Registers
|
||||||
|
const (
|
||||||
|
NOP = 0x00
|
||||||
|
SWRESET = 0x01
|
||||||
|
RDDID = 0x04
|
||||||
|
RDDST = 0x09
|
||||||
|
SLPIN = 0x10
|
||||||
|
SLPOUT = 0x11
|
||||||
|
PTLON = 0x12
|
||||||
|
NORON = 0x13
|
||||||
|
INVOFF = 0x20
|
||||||
|
INVON = 0x21
|
||||||
|
DISPOFF = 0x28
|
||||||
|
DISPON = 0x29
|
||||||
|
CASET = 0x2A
|
||||||
|
RASET = 0x2B
|
||||||
|
RAMWR = 0x2C
|
||||||
|
RAMRD = 0x2E
|
||||||
|
PTLAR = 0x30
|
||||||
|
COLMOD = 0x3A
|
||||||
|
MADCTL = 0x36
|
||||||
|
MADCTL_MY = 0x80
|
||||||
|
MADCTL_MX = 0x40
|
||||||
|
MADCTL_MV = 0x20
|
||||||
|
MADCTL_ML = 0x10
|
||||||
|
MADCTL_RGB = 0x00
|
||||||
|
MADCTL_BGR = 0x08
|
||||||
|
MADCTL_MH = 0x04
|
||||||
|
RDID1 = 0xDA
|
||||||
|
RDID2 = 0xDB
|
||||||
|
RDID3 = 0xDC
|
||||||
|
RDID4 = 0xDD
|
||||||
|
FRMCTR1 = 0xB1
|
||||||
|
RGBCTRL = 0xB1
|
||||||
|
FRMCTR2 = 0xB2
|
||||||
|
PORCTRL = 0xB2
|
||||||
|
FRMCTR3 = 0xB3
|
||||||
|
INVCTR = 0xB4
|
||||||
|
DISSET5 = 0xB6
|
||||||
|
PWCTR1 = 0xC0
|
||||||
|
PWCTR2 = 0xC1
|
||||||
|
PWCTR3 = 0xC2
|
||||||
|
PWCTR4 = 0xC3
|
||||||
|
PWCTR5 = 0xC4
|
||||||
|
VMCTR1 = 0xC5
|
||||||
|
FRCTRL2 = 0xC6
|
||||||
|
PWCTR6 = 0xFC
|
||||||
|
GMCTRP1 = 0xE0
|
||||||
|
GMCTRN1 = 0xE1
|
||||||
|
GSCAN = 0x45
|
||||||
|
VSCRDEF = 0x33
|
||||||
|
VSCRSADD = 0x37
|
||||||
|
|
||||||
|
ColorRGB444 ColorFormat = 0b011
|
||||||
|
ColorRGB565 ColorFormat = 0b101
|
||||||
|
ColorRGB666 ColorFormat = 0b111
|
||||||
|
|
||||||
|
NO_ROTATION = display.NoRotation
|
||||||
|
ROTATION_90 = display.Rotate90 // 90 degrees clock-wise rotation
|
||||||
|
ROTATION_180 = display.Rotate180
|
||||||
|
ROTATION_270 = display.Rotate270
|
||||||
|
|
||||||
|
// Allowable frame rate codes for FRCTRL2 (Identifier is in Hz)
|
||||||
|
FRAMERATE_111 FrameRate = 0x01
|
||||||
|
FRAMERATE_105 FrameRate = 0x02
|
||||||
|
FRAMERATE_99 FrameRate = 0x03
|
||||||
|
FRAMERATE_94 FrameRate = 0x04
|
||||||
|
FRAMERATE_90 FrameRate = 0x05
|
||||||
|
FRAMERATE_86 FrameRate = 0x06
|
||||||
|
FRAMERATE_82 FrameRate = 0x07
|
||||||
|
FRAMERATE_78 FrameRate = 0x08
|
||||||
|
FRAMERATE_75 FrameRate = 0x09
|
||||||
|
FRAMERATE_72 FrameRate = 0x0A
|
||||||
|
FRAMERATE_69 FrameRate = 0x0B
|
||||||
|
FRAMERATE_67 FrameRate = 0x0C
|
||||||
|
FRAMERATE_64 FrameRate = 0x0D
|
||||||
|
FRAMERATE_62 FrameRate = 0x0E
|
||||||
|
FRAMERATE_60 FrameRate = 0x0F // 60 is default
|
||||||
|
FRAMERATE_58 FrameRate = 0x10
|
||||||
|
FRAMERATE_57 FrameRate = 0x11
|
||||||
|
FRAMERATE_55 FrameRate = 0x12
|
||||||
|
FRAMERATE_53 FrameRate = 0x13
|
||||||
|
FRAMERATE_52 FrameRate = 0x14
|
||||||
|
FRAMERATE_50 FrameRate = 0x15
|
||||||
|
FRAMERATE_49 FrameRate = 0x16
|
||||||
|
FRAMERATE_48 FrameRate = 0x17
|
||||||
|
FRAMERATE_46 FrameRate = 0x18
|
||||||
|
FRAMERATE_45 FrameRate = 0x19
|
||||||
|
FRAMERATE_44 FrameRate = 0x1A
|
||||||
|
FRAMERATE_43 FrameRate = 0x1B
|
||||||
|
FRAMERATE_42 FrameRate = 0x1C
|
||||||
|
FRAMERATE_41 FrameRate = 0x1D
|
||||||
|
FRAMERATE_40 FrameRate = 0x1E
|
||||||
|
FRAMERATE_39 FrameRate = 0x1F
|
||||||
|
|
||||||
|
MAX_VSYNC_SCANLINES = 254
|
||||||
|
)
|
||||||
@@ -0,0 +1,888 @@
|
|||||||
|
// Package st7789 implements a driver for the ST7789 TFT displays, it comes in various screen sizes.
|
||||||
|
//
|
||||||
|
// Datasheets: https://cdn-shop.adafruit.com/product-files/3787/3787_tft_QT154H2201__________20190228182902.pdf
|
||||||
|
//
|
||||||
|
// http://www.newhavendisplay.com/appnotes/datasheets/LCDs/ST7789V.pdf
|
||||||
|
package st7789
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"math"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"periph.io/x/conn/v3/gpio"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
"periph.io/x/conn/v3/spi"
|
||||||
|
"periph.io/x/conn/v3/spi/spireg"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/hardware"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Rotation controls the rotation used by the display.
|
||||||
|
//
|
||||||
|
// Deprecated: use drivers.Rotation instead.
|
||||||
|
type Rotation = display.Rotation
|
||||||
|
|
||||||
|
// The color format used on the display, like RGB565, RGB666, and RGB444.
|
||||||
|
type ColorFormat uint8
|
||||||
|
|
||||||
|
// Pixel formats supported by the st7789 driver.
|
||||||
|
type Color interface {
|
||||||
|
pixel.RGB444BE | pixel.RGB565BE
|
||||||
|
|
||||||
|
pixel.BaseColor
|
||||||
|
}
|
||||||
|
|
||||||
|
// FrameRate controls the frame rate used by the display.
|
||||||
|
type FrameRate uint8
|
||||||
|
|
||||||
|
var (
|
||||||
|
errOutOfBounds = errors.New("rectangle coordinates outside display area")
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("st7789", func(config *config.Display) (display.Display, error) {
|
||||||
|
log := logrus.WithFields(logrus.Fields{
|
||||||
|
"type": "st7789",
|
||||||
|
"name": config.Name,
|
||||||
|
})
|
||||||
|
|
||||||
|
width, height, err := display.ParseSize(config.Size, 240, 320)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rotation, err := display.ParseRotation(config.Rotate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.WithField("port", config.Port).Trace("opening SPI port")
|
||||||
|
port, err := spireg.Open(config.Port)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
bits = 8
|
||||||
|
reset gpio.PinOut
|
||||||
|
dc gpio.PinOut
|
||||||
|
cs gpio.PinOut
|
||||||
|
bl gpio.PinOut
|
||||||
|
)
|
||||||
|
if dc, err = hardware.LookupPinOut(config.DC); err != nil {
|
||||||
|
if !hardware.IsNotFound(err) {
|
||||||
|
return nil, fmt.Errorf("invalid dc pin: %w", err)
|
||||||
|
}
|
||||||
|
bits = 9 // no DC pin
|
||||||
|
}
|
||||||
|
if reset, err = hardware.LookupPinOut(config.Reset); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid reset pin: %w", err)
|
||||||
|
}
|
||||||
|
if cs, err = hardware.LookupPinOut(config.CS); err != nil && !hardware.IsNotFound(err) {
|
||||||
|
return nil, fmt.Errorf("invalid cs pin: %w", err)
|
||||||
|
} else {
|
||||||
|
cs = gpio.INVALID
|
||||||
|
}
|
||||||
|
if bl, err = hardware.LookupPinOut(config.BL); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid bl pin: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.WithFields(logrus.Fields{
|
||||||
|
"mode": spi.Mode0,
|
||||||
|
"bits": bits,
|
||||||
|
"pin_reset": reset,
|
||||||
|
"pin_dc": dc,
|
||||||
|
"pin_cs": cs,
|
||||||
|
"pin_bl": bl,
|
||||||
|
}).Debug("connecting on SPI port")
|
||||||
|
conn, err := port.Connect(75*physic.MegaHertz, spi.Mode0, bits)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := New[pixel.RGB565BE](conn, reset, dc, cs, bl)
|
||||||
|
d.log = log
|
||||||
|
|
||||||
|
if err = d.Configure(Config{
|
||||||
|
Width: int16(width),
|
||||||
|
Height: int16(height),
|
||||||
|
Rotation: rotation,
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return d, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Device wraps an SPI connection.
|
||||||
|
type Device = DeviceOf[pixel.RGB565BE]
|
||||||
|
|
||||||
|
// DeviceOf is a generic version of Device. It supports multiple different pixel
|
||||||
|
// formats.
|
||||||
|
type DeviceOf[T Color] struct {
|
||||||
|
log *logrus.Entry
|
||||||
|
bus spi.Conn
|
||||||
|
dcPin gpio.PinOut
|
||||||
|
resetPin gpio.PinOut
|
||||||
|
csPin gpio.PinOut
|
||||||
|
blPin gpio.PinOut
|
||||||
|
width int16
|
||||||
|
height int16
|
||||||
|
columnOffsetCfg int16
|
||||||
|
rowOffsetCfg int16
|
||||||
|
columnOffset int16
|
||||||
|
rowOffset int16
|
||||||
|
rotation display.Rotation
|
||||||
|
frameRate FrameRate
|
||||||
|
batchLength int32
|
||||||
|
batchData pixel.Image[T] // "image" with (width, height) of (batchLength, 1)
|
||||||
|
isBGR bool
|
||||||
|
vSyncLines int16
|
||||||
|
cmdBuf [1]byte
|
||||||
|
buf [6]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config is the configuration for the display
|
||||||
|
type Config struct {
|
||||||
|
Width int16
|
||||||
|
Height int16
|
||||||
|
Rotation display.Rotation
|
||||||
|
RowOffset int16
|
||||||
|
ColumnOffset int16
|
||||||
|
FrameRate FrameRate
|
||||||
|
VSyncLines int16
|
||||||
|
|
||||||
|
// Gamma control. Look in the LCD panel datasheet or provided example code
|
||||||
|
// to find these values. If not set, the defaults will be used.
|
||||||
|
PVGAMCTRL []uint8 // Positive voltage gamma control (14 bytes)
|
||||||
|
NVGAMCTRL []uint8 // Negative voltage gamma control (14 bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a new ST7789 connection. The SPI wire must already be configured.
|
||||||
|
//func New(bus spi.Conn, resetPin, dcPin, csPin, blPin gpio.PinOut) *Device {
|
||||||
|
// return NewOf[pixel.RGB565BE](bus, resetPin, dcPin, csPin, blPin)
|
||||||
|
//}
|
||||||
|
|
||||||
|
// NewOf creates a new ST7789 connection with a particular pixel format. The SPI
|
||||||
|
// wire must already be configured.
|
||||||
|
func New[T Color](bus spi.Conn, reset, dc, cs, bl gpio.PinOut) *DeviceOf[T] {
|
||||||
|
return &DeviceOf[T]{
|
||||||
|
log: logrus.WithFields(logrus.Fields{
|
||||||
|
"display": "st7789",
|
||||||
|
"pin_reset": reset,
|
||||||
|
"pin_dc": dc,
|
||||||
|
"pin_cs": cs,
|
||||||
|
"pin_bl": bl,
|
||||||
|
}),
|
||||||
|
bus: bus,
|
||||||
|
dcPin: dc,
|
||||||
|
resetPin: reset,
|
||||||
|
csPin: cs,
|
||||||
|
blPin: bl,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure initializes the display with default configuration
|
||||||
|
func (d *DeviceOf[T]) Configure(cfg Config) (err error) {
|
||||||
|
start := time.Now()
|
||||||
|
d.log.Trace("start display configuration")
|
||||||
|
defer func() {
|
||||||
|
ago := time.Since(start)
|
||||||
|
d.log.WithField("duration", ago).Trace("ended display configuration")
|
||||||
|
}()
|
||||||
|
|
||||||
|
if cfg.Width != 0 {
|
||||||
|
d.width = cfg.Width
|
||||||
|
} else {
|
||||||
|
d.width = 240
|
||||||
|
}
|
||||||
|
if cfg.Height != 0 {
|
||||||
|
d.height = cfg.Height
|
||||||
|
} else {
|
||||||
|
d.height = 240
|
||||||
|
}
|
||||||
|
|
||||||
|
d.rotation = cfg.Rotation
|
||||||
|
d.rowOffsetCfg = cfg.RowOffset
|
||||||
|
d.columnOffsetCfg = cfg.ColumnOffset
|
||||||
|
|
||||||
|
if cfg.FrameRate != 0 {
|
||||||
|
d.frameRate = cfg.FrameRate
|
||||||
|
} else {
|
||||||
|
d.frameRate = FRAMERATE_60
|
||||||
|
}
|
||||||
|
d.log.Tracef("%d frame rate", d.frameRate)
|
||||||
|
|
||||||
|
if cfg.VSyncLines >= 2 && cfg.VSyncLines <= 254 {
|
||||||
|
d.vSyncLines = cfg.VSyncLines
|
||||||
|
} else {
|
||||||
|
d.vSyncLines = 16
|
||||||
|
}
|
||||||
|
d.log.Tracef("%d vsync lines", d.vSyncLines)
|
||||||
|
|
||||||
|
d.batchLength = int32(d.width)
|
||||||
|
if d.height > d.width {
|
||||||
|
d.batchLength = int32(d.height)
|
||||||
|
}
|
||||||
|
d.batchLength += d.batchLength & 1
|
||||||
|
d.log.Tracef("%d batch length", d.batchLength)
|
||||||
|
|
||||||
|
// Reset the device
|
||||||
|
d.log.Debug("reset device")
|
||||||
|
if err = d.resetPin.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
if err = d.resetPin.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
if err = d.resetPin.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
|
||||||
|
// Common initialization
|
||||||
|
d.startWrite()
|
||||||
|
d.sendCommand(SWRESET, nil) // Soft reset
|
||||||
|
d.endWrite()
|
||||||
|
time.Sleep(150 * time.Millisecond) //
|
||||||
|
d.startWrite()
|
||||||
|
|
||||||
|
d.sendCommand(SLPOUT, nil) // Exit sleep mode
|
||||||
|
|
||||||
|
// Memory initialization
|
||||||
|
var zeroColor T
|
||||||
|
switch any(zeroColor).(type) {
|
||||||
|
case pixel.RGB444BE:
|
||||||
|
d.setColorFormat(ColorRGB444) // 12 bits per pixel
|
||||||
|
default:
|
||||||
|
// Use default RGB565 color format.
|
||||||
|
d.setColorFormat(ColorRGB565) // 16 bits per pixel
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
|
||||||
|
d.setRotation(d.rotation) // Memory orientation
|
||||||
|
|
||||||
|
d.setWindow(0, 0, d.width, d.height) // Full draw window
|
||||||
|
var black T
|
||||||
|
d.fillScreen(black) // Clear screen
|
||||||
|
|
||||||
|
// Framerate
|
||||||
|
d.sendCommand(FRCTRL2, []byte{byte(d.frameRate)}) // Frame rate for normal mode (default 60Hz)
|
||||||
|
|
||||||
|
// Frame vertical sync and "porch"
|
||||||
|
//
|
||||||
|
// Front and back porch controls vertical scanline sync time before and after
|
||||||
|
// a frame, where memory can be safely written without tearing.
|
||||||
|
//
|
||||||
|
fp := uint8(d.vSyncLines / 2) // Split the desired pause half and half
|
||||||
|
bp := uint8(d.vSyncLines - int16(fp)) // between front and back porch.
|
||||||
|
|
||||||
|
d.sendCommand(PORCTRL, []byte{
|
||||||
|
bp, // Back porch 5bit (0x7F max 0x08 default)
|
||||||
|
fp, // Front porch 5bit (0x7F max 0x08 default)
|
||||||
|
0x00, // Seprarate porch (TODO: what is this?)
|
||||||
|
0x22, // Idle mode porch (4bit-back 4bit-front 0x22 default)
|
||||||
|
0x22, // Partial mode porch (4bit-back 4bit-front 0x22 default)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Ready to display
|
||||||
|
d.sendCommand(INVON, nil) // Inversion ON
|
||||||
|
time.Sleep(10 * time.Millisecond) //
|
||||||
|
|
||||||
|
// Set gamma tables, if configured.
|
||||||
|
if len(cfg.PVGAMCTRL) == 14 {
|
||||||
|
d.sendCommand(GMCTRP1, cfg.PVGAMCTRL) // PVGAMCTRL: Positive Voltage Gamma Control
|
||||||
|
}
|
||||||
|
if len(cfg.NVGAMCTRL) == 14 {
|
||||||
|
d.sendCommand(GMCTRN1, cfg.NVGAMCTRL) // NVGAMCTRL: Negative Voltage Gamma Control
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal mode ON
|
||||||
|
if err = d.sendCommand(NORON, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
|
||||||
|
// Screen ON
|
||||||
|
if err = d.sendCommand(DISPON, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
|
||||||
|
if err = d.endWrite(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backlight ON
|
||||||
|
if err = d.blPin.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send a command with data to the display. It does not change the chip select
|
||||||
|
// pin (it must be low when calling). The DC pin is left high after return,
|
||||||
|
// meaning that data can be sent right away.
|
||||||
|
func (d *DeviceOf[T]) sendCommand(command uint8, data []byte) (err error) {
|
||||||
|
//d.log.WithFields(logrus.Fields{"command": command, "data": data}).Trace("send command")
|
||||||
|
d.cmdBuf[0] = command
|
||||||
|
if hardware.IsValidPinOut(d.dcPin) {
|
||||||
|
if err = d.dcPin.Out(gpio.Low); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = d.bus.Tx(d.cmdBuf[:1], nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if hardware.IsValidPinOut(d.dcPin) {
|
||||||
|
if err = d.dcPin.Out(gpio.High); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(data) != 0 {
|
||||||
|
err = d.bus.Tx(data, nil)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// startWrite must be called at the beginning of all exported methods to set the
|
||||||
|
// chip select pin low.
|
||||||
|
func (d *DeviceOf[T]) startWrite() error {
|
||||||
|
if hardware.IsValidPinOut(d.csPin) {
|
||||||
|
return d.csPin.Out(gpio.Low)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// endWrite must be called at the end of all exported methods to set the chip
|
||||||
|
// select pin high.
|
||||||
|
func (d *DeviceOf[T]) endWrite() error {
|
||||||
|
if hardware.IsValidPinOut(d.csPin) {
|
||||||
|
return d.csPin.Out(gpio.High)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// getBuffer returns the image buffer, that's always d.batchLength wide and 1
|
||||||
|
// pixel high. It can be used as a temporary buffer to transmit image data.
|
||||||
|
func (d *DeviceOf[T]) getBuffer() pixel.Image[T] {
|
||||||
|
if d.batchData.Len() == 0 {
|
||||||
|
d.batchData = pixel.NewImage[T](int(d.batchLength), 1)
|
||||||
|
}
|
||||||
|
return d.batchData
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync waits for the display to hit the next VSYNC pause
|
||||||
|
func (d *DeviceOf[T]) Sync() {
|
||||||
|
d.SyncToScanLine(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncToScanLine waits for the display to hit a specific scanline
|
||||||
|
//
|
||||||
|
// A scanline value of 0 will forward to the beginning of the next VSYNC,
|
||||||
|
// even if the display is currently in a VSYNC pause.
|
||||||
|
//
|
||||||
|
// Syncline values appear to increment once for every two vertical
|
||||||
|
// lines on the display.
|
||||||
|
//
|
||||||
|
// NOTE: Use GetHighestScanLine and GetLowestScanLine to obtain the highest
|
||||||
|
// and lowest useful values. Values are affected by front and back porch
|
||||||
|
// vsync settings (derived from VSyncLines configuration option).
|
||||||
|
func (d *DeviceOf[T]) SyncToScanLine(scanline uint16) {
|
||||||
|
scan := d.GetScanLine()
|
||||||
|
|
||||||
|
// Sometimes GetScanLine returns erroneous 0 on first call after draw, so double check
|
||||||
|
if scan == 0 {
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
|
||||||
|
if scanline == 0 {
|
||||||
|
// we dont know where we are in an ongoing vsync so go around
|
||||||
|
for scan < 1 {
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
for scan > 0 {
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// go around unless we're very close to the target
|
||||||
|
for scan > scanline+4 {
|
||||||
|
time.Sleep(1 * time.Millisecond)
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
for scan < scanline {
|
||||||
|
scan = d.GetScanLine()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScanLine reads the current scanline value from the display
|
||||||
|
func (d *DeviceOf[T]) GetScanLine() uint16 {
|
||||||
|
d.startWrite()
|
||||||
|
data := []uint8{0x00, 0x00}
|
||||||
|
if hardware.IsValidPinOut(d.dcPin) {
|
||||||
|
d.dcPin.Out(gpio.Low)
|
||||||
|
}
|
||||||
|
//d.bus.Transfer(GSCAN)
|
||||||
|
d.bus.Tx([]byte{GSCAN}, nil)
|
||||||
|
if hardware.IsValidPinOut(d.dcPin) {
|
||||||
|
d.dcPin.Out(gpio.High)
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
for i := range data {
|
||||||
|
data[i], _ = d.bus.Transfer(0xFF)
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
d.bus.Tx(data, data)
|
||||||
|
scanline := uint16(data[0])<<8 + uint16(data[1])
|
||||||
|
d.endWrite()
|
||||||
|
return scanline
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetHighestScanLine calculates the last scanline id in the frame before VSYNC pause
|
||||||
|
func (d *DeviceOf[T]) GetHighestScanLine() uint16 {
|
||||||
|
// Last scanline id appears to be backporch/2 + 320/2
|
||||||
|
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 160
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLowestScanLine calculate the first scanline id to appear after VSYNC pause
|
||||||
|
func (d *DeviceOf[T]) GetLowestScanLine() uint16 {
|
||||||
|
// First scanline id appears to be backporch/2 + 1
|
||||||
|
return uint16(math.Ceil(float64(d.vSyncLines)/2)/2) + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Display does nothing, there's no buffer as it might be too big for some boards
|
||||||
|
func (d *DeviceOf[T]) Display() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPixel sets a pixel in the screen
|
||||||
|
// func (d *DeviceOf[T]) SetPixel(x int16, y int16, c color.RGBA) {
|
||||||
|
func (d *DeviceOf[T]) SetPixel(x int16, y int16, c T) {
|
||||||
|
if x < 0 || y < 0 ||
|
||||||
|
(((d.rotation == display.NoRotation || d.rotation == display.Rotate180) && (x >= d.width || y >= d.height)) ||
|
||||||
|
((d.rotation == display.Rotate90 || d.rotation == display.Rotate270) && (x >= d.height || y >= d.width))) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.FillRectangle(x, y, 1, 1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// setWindow prepares the screen to be modified at a given rectangle
|
||||||
|
func (d *DeviceOf[T]) setWindow(x, y, w, h int16) {
|
||||||
|
//d.log.WithFields(logrus.Fields{"x": x, "y": y, "w": w, "h": h}).Debug("updating drawing window")
|
||||||
|
x += d.columnOffset
|
||||||
|
y += d.rowOffset
|
||||||
|
copy(d.buf[:4], []uint8{uint8(x >> 8), uint8(x), uint8((x + w - 1) >> 8), uint8(x + w - 1)})
|
||||||
|
d.sendCommand(CASET, d.buf[:4])
|
||||||
|
copy(d.buf[:4], []uint8{uint8(y >> 8), uint8(y), uint8((y + h - 1) >> 8), uint8(y + h - 1)})
|
||||||
|
d.sendCommand(RASET, d.buf[:4])
|
||||||
|
d.sendCommand(RAMWR, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillRectangle fills a rectangle at a given coordinates with a color
|
||||||
|
// func (d *DeviceOf[T]) FillRectangle(x, y, width, height int16, c color.RGBA) error {
|
||||||
|
func (d *DeviceOf[T]) FillRectangle(x, y, width, height int16, c T) error {
|
||||||
|
d.startWrite()
|
||||||
|
err := d.fillRectangle(x, y, width, height, c)
|
||||||
|
d.endWrite()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (d *DeviceOf[T]) fillRectangle(x, y, width, height int16, c color.RGBA) error {
|
||||||
|
func (d *DeviceOf[T]) fillRectangle(x, y, width, height int16, c T) error {
|
||||||
|
k, i := d.Size16()
|
||||||
|
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||||
|
x >= k || (x+width) > k || y >= i || (y+height) > i {
|
||||||
|
return errors.New("rectangle coordinates outside display area")
|
||||||
|
}
|
||||||
|
d.setWindow(x, y, width, height)
|
||||||
|
|
||||||
|
image := d.getBuffer()
|
||||||
|
image.FillSolidColor(c)
|
||||||
|
//image.FillSolidColor(pixel.NewColor[T](c.R, c.G, c.B))
|
||||||
|
j := int(width) * int(height)
|
||||||
|
for j > 0 {
|
||||||
|
// The DC pin is already set to data in the setWindow call, so we can
|
||||||
|
// just write bytes on the SPI bus.
|
||||||
|
if j >= image.Len() {
|
||||||
|
d.bus.Tx(image.RawBuffer(), nil)
|
||||||
|
} else {
|
||||||
|
d.bus.Tx(image.Rescale(j, 1).RawBuffer(), nil)
|
||||||
|
}
|
||||||
|
j -= image.Len()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawRGBBitmap8 copies an RGB bitmap to the internal buffer at given coordinates
|
||||||
|
//
|
||||||
|
// Deprecated: use DrawBitmap instead.
|
||||||
|
func (d *DeviceOf[T]) DrawRGBBitmap8(x, y int16, data []uint8, w, h int16) error {
|
||||||
|
k, i := d.Size16()
|
||||||
|
if x < 0 || y < 0 || w <= 0 || h <= 0 ||
|
||||||
|
x >= k || (x+w) > k || y >= i || (y+h) > i {
|
||||||
|
return errOutOfBounds
|
||||||
|
}
|
||||||
|
d.startWrite()
|
||||||
|
d.setWindow(x, y, w, h)
|
||||||
|
d.bus.Tx(data, nil)
|
||||||
|
d.endWrite()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawBitmap copies the bitmap to the internal buffer on the screen at the
|
||||||
|
// given coordinates. It returns once the image data has been sent completely.
|
||||||
|
func (d *DeviceOf[T]) DrawBitmap(x, y int16, bitmap pixel.Image[T]) error {
|
||||||
|
width, height := bitmap.Size()
|
||||||
|
return d.DrawRGBBitmap8(x, y, bitmap.RawBuffer(), int16(width), int16(height))
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillRectangleWithBuffer fills buffer with a rectangle at a given coordinates.
|
||||||
|
func (d *DeviceOf[T]) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {
|
||||||
|
i, j := d.Size16()
|
||||||
|
if x < 0 || y < 0 || width <= 0 || height <= 0 ||
|
||||||
|
x >= i || (x+width) > i || y >= j || (y+height) > j {
|
||||||
|
return errors.New("rectangle coordinates outside display area")
|
||||||
|
}
|
||||||
|
if int32(width)*int32(height) != int32(len(buffer)) {
|
||||||
|
return errors.New("buffer length does not match with rectangle size")
|
||||||
|
}
|
||||||
|
d.startWrite()
|
||||||
|
d.setWindow(x, y, width, height)
|
||||||
|
|
||||||
|
k := int(width) * int(height)
|
||||||
|
image := d.getBuffer()
|
||||||
|
offset := 0
|
||||||
|
for k > 0 {
|
||||||
|
for i := 0; i < image.Len(); i++ {
|
||||||
|
if offset+i < len(buffer) {
|
||||||
|
c := buffer[offset+i]
|
||||||
|
image.Set(i, 0, pixel.NewColor[T](c.R, c.G, c.B))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The DC pin is already set to data in the setWindow call, so we don't
|
||||||
|
// have to set it here.
|
||||||
|
if k >= image.Len() {
|
||||||
|
d.bus.Tx(image.RawBuffer(), nil)
|
||||||
|
} else {
|
||||||
|
d.bus.Tx(image.Rescale(k, 1).RawBuffer(), nil)
|
||||||
|
}
|
||||||
|
k -= image.Len()
|
||||||
|
offset += image.Len()
|
||||||
|
}
|
||||||
|
d.endWrite()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawFastVLine draws a vertical line faster than using SetPixel
|
||||||
|
func (d *DeviceOf[T]) DrawFastVLine(x, y0, y1 int16, c T) {
|
||||||
|
if y0 > y1 {
|
||||||
|
y0, y1 = y1, y0
|
||||||
|
}
|
||||||
|
d.FillRectangle(x, y0, 1, y1-y0+1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawFastHLine draws a horizontal line faster than using SetPixel
|
||||||
|
func (d *DeviceOf[T]) DrawFastHLine(x0, x1, y int16, c T) {
|
||||||
|
if x0 > x1 {
|
||||||
|
x0, x1 = x1, x0
|
||||||
|
}
|
||||||
|
d.FillRectangle(x0, y, x1-x0+1, 1, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillScreen fills the screen with a given color
|
||||||
|
func (d *DeviceOf[T]) FillScreen(c T) {
|
||||||
|
d.startWrite()
|
||||||
|
d.fillScreen(c)
|
||||||
|
d.endWrite()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) fillScreen(c T) {
|
||||||
|
if d.rotation == NO_ROTATION || d.rotation == ROTATION_180 {
|
||||||
|
d.fillRectangle(0, 0, d.width, d.height, c)
|
||||||
|
} else {
|
||||||
|
d.fillRectangle(0, 0, d.height, d.width, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Control the color format that is used when writing to the screen.
|
||||||
|
// The default is RGB565, setting it to any other value will break functions
|
||||||
|
// like SetPixel, FillRectangle, etc. Instead, you can write color data in the
|
||||||
|
// specified color format using DrawRGBBitmap8.
|
||||||
|
func (d *DeviceOf[T]) SetColorFormat(format ColorFormat) {
|
||||||
|
d.startWrite()
|
||||||
|
d.setColorFormat(format)
|
||||||
|
d.endWrite()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) setColorFormat(format ColorFormat) {
|
||||||
|
// Lower 4 bits set the color format used in SPI.
|
||||||
|
// Upper 4 bits set the color format used in the direct RGB interface.
|
||||||
|
// The RGB interface is not currently supported, so it is left at a
|
||||||
|
// reasonable default. Also, the RGB interface doesn't support RGB444.
|
||||||
|
colmod := byte(format) | 0x50
|
||||||
|
d.sendCommand(COLMOD, []byte{colmod})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotation returns the current rotation of the device.
|
||||||
|
func (d *DeviceOf[T]) Rotation() display.Rotation {
|
||||||
|
return d.rotation
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRotation changes the rotation of the device (clock-wise)
|
||||||
|
func (d *DeviceOf[T]) SetRotation(rotation Rotation) error {
|
||||||
|
d.rotation = rotation
|
||||||
|
d.startWrite()
|
||||||
|
err := d.setRotation(rotation)
|
||||||
|
d.endWrite()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) setRotation(rotation Rotation) error {
|
||||||
|
madctl := uint8(0)
|
||||||
|
switch rotation % 4 {
|
||||||
|
case display.NoRotation:
|
||||||
|
d.rowOffset = 0
|
||||||
|
d.columnOffset = 0
|
||||||
|
case display.Rotate90:
|
||||||
|
madctl = MADCTL_MX | MADCTL_MV
|
||||||
|
d.rowOffset = 0
|
||||||
|
d.columnOffset = 0
|
||||||
|
case display.Rotate180:
|
||||||
|
madctl = MADCTL_MX | MADCTL_MY
|
||||||
|
d.rowOffset = d.rowOffsetCfg
|
||||||
|
d.columnOffset = d.columnOffsetCfg
|
||||||
|
case display.Rotate270:
|
||||||
|
madctl = MADCTL_MY | MADCTL_MV
|
||||||
|
d.rowOffset = d.columnOffsetCfg
|
||||||
|
d.columnOffset = d.rowOffsetCfg
|
||||||
|
}
|
||||||
|
if d.isBGR {
|
||||||
|
madctl |= MADCTL_BGR
|
||||||
|
}
|
||||||
|
return d.sendCommand(MADCTL, []byte{madctl})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the current size of the display.
|
||||||
|
func (d *DeviceOf[T]) Size() image.Point {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
return image.Pt(int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
return image.Pt(int(d.height), int(d.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sizes returns the current size of the display.
|
||||||
|
func (d *DeviceOf[T]) Size16() (int16, int16) {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
return d.width, d.height
|
||||||
|
}
|
||||||
|
return d.height, d.width
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnableBacklight enables or disables the backlight
|
||||||
|
func (d *DeviceOf[T]) EnableBacklight(enable bool) {
|
||||||
|
if enable {
|
||||||
|
d.blPin.Out(gpio.High)
|
||||||
|
} else {
|
||||||
|
d.blPin.Out(gpio.Low)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the sleep mode for this LCD panel. When sleeping, the panel uses a lot
|
||||||
|
// less power. The LCD won't display an image anymore, but the memory contents
|
||||||
|
// will be kept.
|
||||||
|
func (d *DeviceOf[T]) Sleep(sleepEnabled bool) error {
|
||||||
|
if sleepEnabled {
|
||||||
|
d.startWrite()
|
||||||
|
d.sendCommand(SLPIN, nil)
|
||||||
|
d.endWrite()
|
||||||
|
time.Sleep(5 * time.Millisecond) // 5ms required by the datasheet
|
||||||
|
} else {
|
||||||
|
// Turn the LCD panel back on.
|
||||||
|
d.startWrite()
|
||||||
|
d.sendCommand(SLPOUT, nil)
|
||||||
|
d.endWrite()
|
||||||
|
// Note: the st7789 documentation says that it is needed to wait at
|
||||||
|
// least 120ms before going to sleep again. Sleeping here would not be
|
||||||
|
// practical (delays turning on the screen too much), so just hope the
|
||||||
|
// screen won't need to sleep again for at least 120ms.
|
||||||
|
// In practice, it's unlikely the user will set the display to sleep
|
||||||
|
// again within 120ms.
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvertColors inverts the colors of the screen
|
||||||
|
func (d *DeviceOf[T]) InvertColors(invert bool) {
|
||||||
|
d.startWrite()
|
||||||
|
if invert {
|
||||||
|
d.sendCommand(INVON, nil)
|
||||||
|
} else {
|
||||||
|
d.sendCommand(INVOFF, nil)
|
||||||
|
}
|
||||||
|
d.endWrite()
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsBGR changes the color mode (RGB/BGR)
|
||||||
|
func (d *DeviceOf[T]) IsBGR(bgr bool) {
|
||||||
|
d.isBGR = bgr
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetScrollArea sets an area to scroll with fixed top and bottom parts of the display.
|
||||||
|
func (d *DeviceOf[T]) SetScrollArea(topFixedArea, bottomFixedArea int16) {
|
||||||
|
if d.height < 320 {
|
||||||
|
// The screen doesn't use the full 320 pixel height.
|
||||||
|
// Enlarge the bottom fixed area to fill the 320 pixel height, so that
|
||||||
|
// bottomFixedArea starts from the visible bottom of the screen.
|
||||||
|
topFixedArea += d.rowOffset
|
||||||
|
bottomFixedArea += (320 - d.height) - d.rowOffset
|
||||||
|
}
|
||||||
|
if d.rotation == display.Rotate180 {
|
||||||
|
// The screen is rotated by 180°, so we have to switch the top and
|
||||||
|
// bottom fixed area.
|
||||||
|
topFixedArea, bottomFixedArea = bottomFixedArea, topFixedArea
|
||||||
|
}
|
||||||
|
verticalScrollArea := 320 - topFixedArea - bottomFixedArea
|
||||||
|
copy(d.buf[:6], []uint8{
|
||||||
|
uint8(topFixedArea >> 8), uint8(topFixedArea),
|
||||||
|
uint8(verticalScrollArea >> 8), uint8(verticalScrollArea),
|
||||||
|
uint8(bottomFixedArea >> 8), uint8(bottomFixedArea)})
|
||||||
|
d.startWrite()
|
||||||
|
d.sendCommand(VSCRDEF, d.buf[:6])
|
||||||
|
d.endWrite()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetScroll sets the vertical scroll address of the display.
|
||||||
|
func (d *DeviceOf[T]) SetScroll(line int16) {
|
||||||
|
if d.rotation == display.Rotate180 {
|
||||||
|
// The screen is rotated by 180°, so we have to invert the scroll line
|
||||||
|
// (taking care of the RowOffset).
|
||||||
|
line = (319 - d.rowOffset) - line
|
||||||
|
}
|
||||||
|
d.buf[0] = uint8(line >> 8)
|
||||||
|
d.buf[1] = uint8(line)
|
||||||
|
d.startWrite()
|
||||||
|
d.sendCommand(VSCRSADD, d.buf[:2])
|
||||||
|
d.endWrite()
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopScroll returns the display to its normal state.
|
||||||
|
func (d *DeviceOf[T]) StopScroll() {
|
||||||
|
d.startWrite()
|
||||||
|
d.sendCommand(NORON, nil)
|
||||||
|
d.endWrite()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) At(x, y int) color.Color {
|
||||||
|
return color.Black
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) Bounds() image.Rectangle {
|
||||||
|
if d.rotation == display.NoRotation || d.rotation == display.Rotate180 {
|
||||||
|
return image.Rect(0, 0, int(d.width), int(d.height))
|
||||||
|
}
|
||||||
|
return image.Rect(0, 0, int(d.height), int(d.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) ColorModel() color.Model {
|
||||||
|
return color.RGBAModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) Set(x, y int, c color.Color) {
|
||||||
|
c = pixel.FromColor[T](c)
|
||||||
|
d.FillRectangle(int16(x), int16(y), 1, 1, c.(T))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) Halt() error {
|
||||||
|
// Backlight off
|
||||||
|
return d.blPin.Out(gpio.Low)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (DeviceOf[T]) Refresh() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (DeviceOf[T]) String() string {
|
||||||
|
return "st7789"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) DrawImage(img image.Image) error {
|
||||||
|
d.setWindow(0, 0, d.width, d.height)
|
||||||
|
|
||||||
|
var np []uint8
|
||||||
|
for y := 0; y < int(d.height); y++ {
|
||||||
|
for x := 0; x < int(d.width); x++ {
|
||||||
|
r, g, b, _ := img.At(x, y).RGBA()
|
||||||
|
c := uint16((b & 0xF800) + ((g & 0xFC00) >> 5) + ((r & 0xF800) >> 11))
|
||||||
|
np = append(np, uint8(c), uint8(c>>8))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DC is active from setWindow call
|
||||||
|
stride := int(d.batchLength) << 1
|
||||||
|
for i := 0; i < len(np); i += stride {
|
||||||
|
if err := d.bus.Tx(np[i:i+stride], nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DeviceOf[T]) DrawImageAt(x, y int, img image.Image) error {
|
||||||
|
var (
|
||||||
|
rect = img.Bounds()
|
||||||
|
size = rect.Size()
|
||||||
|
orig = image.Pt(x, y)
|
||||||
|
view = image.Rectangle{
|
||||||
|
Min: orig,
|
||||||
|
Max: orig.Add(size),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
//view = view.Intersect()
|
||||||
|
|
||||||
|
if view.Max.X > int(d.width) {
|
||||||
|
view.Max.X = int(d.width)
|
||||||
|
}
|
||||||
|
if view.Max.X <= view.Min.X {
|
||||||
|
return nil // nothing to do here
|
||||||
|
}
|
||||||
|
if view.Max.Y > int(d.height) {
|
||||||
|
view.Max.Y = int(d.height)
|
||||||
|
}
|
||||||
|
|
||||||
|
d.setWindow(int16(x), int16(y), int16(view.Dx()), int16(view.Dy()))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bgr565 converts a color to uint16
|
||||||
|
func bgr565(c color.Color) uint16 {
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return uint16((b & 0xF800) +
|
||||||
|
((g & 0xFC00) >> 5) +
|
||||||
|
((r & 0xF800) >> 11))
|
||||||
|
}
|
||||||
|
|
||||||
|
// rgbaTo565 converts a color.RGBA to uint16 used in the display (bits r:5, g:6, b:5)
|
||||||
|
func rgbaTo565(c color.RGBA) uint16 {
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return uint16((r & 0xF800) +
|
||||||
|
((g & 0xFC00) >> 5) +
|
||||||
|
((b & 0xF800) >> 11))
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ display.Display = (*Device)(nil)
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package virtual
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for _, name := range []string{
|
||||||
|
"row",
|
||||||
|
//"append",
|
||||||
|
//"horizontal",
|
||||||
|
"col",
|
||||||
|
"column",
|
||||||
|
//"stack",
|
||||||
|
//"vertical",
|
||||||
|
} {
|
||||||
|
display.Register(name, newRowOrColumn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRowOrColumn(config *config.Display) (display.Display, error) {
|
||||||
|
if config.Address == "" {
|
||||||
|
return nil, fmt.Errorf("virtual display %q missing required addr", config.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
displays []display.Display
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
for i, name := range strings.Split(config.Address, ",") {
|
||||||
|
var d display.Display
|
||||||
|
if d, err = display.Lookup(name); err != nil {
|
||||||
|
return nil, fmt.Errorf("virtual display %q error loading %q: %w", config.Name, name, err)
|
||||||
|
}
|
||||||
|
displays = append(displays, d)
|
||||||
|
|
||||||
|
if i > 1 && !displays[i].Size().Eq(displays[i-1].Size()) {
|
||||||
|
return nil, fmt.Errorf("virtual display %q requires displays with the same dimensions")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(displays) == 1 {
|
||||||
|
return displays[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch config.Type {
|
||||||
|
case "row", "append", "horizontal":
|
||||||
|
// row of displays
|
||||||
|
return newList(displays, false), nil
|
||||||
|
case "col", "column", "stack", "vertical":
|
||||||
|
// column of displays
|
||||||
|
return newList(displays, true), nil
|
||||||
|
default:
|
||||||
|
panic("unreachable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// list is a virtual row or column of one or more displays.
|
||||||
|
type list struct {
|
||||||
|
displays []display.Display
|
||||||
|
size image.Point // size of one display
|
||||||
|
rect image.Rectangle // rect is the union of all displays
|
||||||
|
vertical bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newList(displays []display.Display, vertical bool) display.Display {
|
||||||
|
var (
|
||||||
|
rect image.Rectangle
|
||||||
|
size image.Point
|
||||||
|
)
|
||||||
|
for i, display := range displays {
|
||||||
|
if i == 0 {
|
||||||
|
size = display.Size()
|
||||||
|
rect = image.Rectangle{Max: size}
|
||||||
|
} else if vertical {
|
||||||
|
rect.Max.Y += size.Y
|
||||||
|
} else {
|
||||||
|
rect.Max.X += size.X
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &list{
|
||||||
|
displays: displays,
|
||||||
|
size: size,
|
||||||
|
rect: rect,
|
||||||
|
vertical: vertical,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *list) String() string {
|
||||||
|
if d.vertical {
|
||||||
|
return "column"
|
||||||
|
}
|
||||||
|
return "row"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *list) ColorModel() color.Model { return d.displays[0].ColorModel() }
|
||||||
|
func (d *list) Bounds() image.Rectangle { return d.rect }
|
||||||
|
func (d *list) Halt() error { return nil }
|
||||||
|
|
||||||
|
func (d *list) displayAt(x, y int) (int, int, display.Display) {
|
||||||
|
for _, display := range d.displays {
|
||||||
|
if image.Pt(x, y).In(display.Bounds()) {
|
||||||
|
return x, y, display
|
||||||
|
}
|
||||||
|
if d.vertical {
|
||||||
|
y -= d.size.Y
|
||||||
|
} else {
|
||||||
|
x -= d.size.X
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1, -1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *list) At(x, y int) color.Color {
|
||||||
|
var display display.Display
|
||||||
|
if x, y, display = d.displayAt(x, y); display != nil {
|
||||||
|
return display.At(x, y)
|
||||||
|
}
|
||||||
|
return pixel.Off
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *list) Set(x, y int, c color.Color) {
|
||||||
|
var display display.Display
|
||||||
|
if x, y, display = d.displayAt(x, y); display != nil {
|
||||||
|
display.Set(x, y, c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *list) Refresh() error {
|
||||||
|
for _, display := range d.displays {
|
||||||
|
if err := display.Refresh(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *list) Size() image.Point {
|
||||||
|
return d.rect.Size()
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package virtual
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
|
||||||
|
"git.maze.io/go/harmon/config"
|
||||||
|
"git.maze.io/go/harmon/display"
|
||||||
|
"git.maze.io/go/harmon/internal/pixel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
display.Register("split", NewSplit)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split is a view on another display.
|
||||||
|
type Split struct {
|
||||||
|
display display.Display
|
||||||
|
bbox image.Rectangle // b are the normalized bounds
|
||||||
|
rect image.Rectangle // r are the absolute bounds in d
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSplit(config *config.Display) (display.Display, error) {
|
||||||
|
if config.Address == "" {
|
||||||
|
return nil, fmt.Errorf("virtual display %q missing required addr", config.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
r, err := parseRect(config.Port)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("virtual display %q invalid port %q: %w", config.Name, config.Port, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
d, err := display.Lookup(config.Address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("virtual display %q error loading %q: %w", config.Name, config.Address, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Split{
|
||||||
|
display: d,
|
||||||
|
bbox: r.Sub(r.Min),
|
||||||
|
rect: r,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Split) String() string { return "split:" + d.display.String() }
|
||||||
|
|
||||||
|
func (d *Split) At(x, y int) color.Color {
|
||||||
|
p := image.Pt(x, y).Add(d.rect.Min)
|
||||||
|
if !p.In(d.rect) {
|
||||||
|
return pixel.Off
|
||||||
|
}
|
||||||
|
return d.display.At(p.X, p.Y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Split) Set(x, y int, c color.Color) {
|
||||||
|
p := image.Pt(x, y).Add(d.rect.Min)
|
||||||
|
if !p.In(d.rect) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.display.Set(p.X, p.Y, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Split) Bounds() image.Rectangle { return d.bbox }
|
||||||
|
func (d *Split) ColorModel() color.Model { return d.display.ColorModel() }
|
||||||
|
func (d *Split) Halt() error { return nil }
|
||||||
|
func (d *Split) Refresh() error { return d.display.Refresh() }
|
||||||
|
func (d *Split) Size() image.Point { return d.rect.Size() }
|
||||||
|
|
||||||
|
func parseRect(s string) (image.Rectangle, error) {
|
||||||
|
var r image.Rectangle
|
||||||
|
if _, err := fmt.Sscanf(s, "%d,%d,%d,%d", &r.Min.X, &r.Min.Y, &r.Max.X, &r.Max.Y); err != nil {
|
||||||
|
return r, err
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
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}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
module git.maze.io/go/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/sirupsen/logrus v1.9.3
|
||||||
|
github.com/spf13/cobra v1.8.1
|
||||||
|
golang.org/x/image v0.19.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/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
|
||||||
|
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
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/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=
|
||||||
|
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/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/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/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=
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
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,17 @@
|
|||||||
|
package hardware
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
// Halt stops the resource.
|
||||||
|
Halt() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsNotFound for resources that return a NotFound error.
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
return errors.Is(err, PinNotFound{})
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 19 KiB |
@@ -0,0 +1,156 @@
|
|||||||
|
audio {
|
||||||
|
type = "tcp"
|
||||||
|
host = "volumio.local:6601"
|
||||||
|
}
|
||||||
|
|
||||||
|
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" {
|
||||||
|
type = "ssd1306"
|
||||||
|
addr = "0x3d"
|
||||||
|
size = "128x64"
|
||||||
|
}
|
||||||
|
|
||||||
|
display "right" {
|
||||||
|
type = "ssd1306"
|
||||||
|
addr = "0x3c"
|
||||||
|
size = "128x64"
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Waveshare 240x320 ST7789V2
|
||||||
|
display "left" {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
visual "vumeter-right" {
|
||||||
|
type = "vumeter"
|
||||||
|
|
||||||
|
config = {
|
||||||
|
channel = 1
|
||||||
|
channels = 2
|
||||||
|
mirror = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
visual "peak" {
|
||||||
|
type = "peak"
|
||||||
|
}
|
||||||
|
|
||||||
|
visual "volume" {
|
||||||
|
type = "volume"
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<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>
|
||||||
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,115 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
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)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
package audio
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
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},
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package audio
|
||||||
|
|
||||||
|
var vumeterBackground = [2][]uint8{{
|
||||||
|
0x80, /* = width */
|
||||||
|
0x40, /* = height */
|
||||||
|
0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0xf0, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x50,
|
||||||
|
0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x50, 0xf0,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x78, 0x41, 0x41, 0x41, 0x40, 0x40, 0x40,
|
||||||
|
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
|
||||||
|
0x41, 0x40, 0x79, 0x41, 0x41, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40,
|
||||||
|
0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x79,
|
||||||
|
0x41, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40,
|
||||||
|
0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x79, 0x01, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x79,
|
||||||
|
0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x61, 0x79, 0x61, 0x60, 0x60,
|
||||||
|
0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x61, 0x79, 0x01,
|
||||||
|
0xc0, 0x4e, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0x42, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x02, 0x82, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x42, 0x42, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0xc2, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0xc2, 0x02, 0xc2, 0x42, 0xce, 0x00, 0xc0, 0x40, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x05, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00,
|
||||||
|
0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x10, 0x2f, 0x50, 0xa0, 0x50, 0x2f, 0x10, 0x0f, 0x00,
|
||||||
|
0x00, 0x3f, 0x40, 0xbf, 0xa0, 0xa0, 0xa0, 0xbf, 0x40, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x22, 0x22, 0x3e,
|
||||||
|
0x00, 0x7e, 0x52, 0x52, 0x42, 0x00, 0x7e, 0x12, 0x12, 0x7e, 0x00, 0x7e, 0x08, 0x08, 0x76, 0x00,
|
||||||
|
}, {
|
||||||
|
0x80, /* = width */
|
||||||
|
0x40, /* = height */
|
||||||
|
0x04, 0x04, 0x1f, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04,
|
||||||
|
0x50, 0x50, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50,
|
||||||
|
0x50, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x00, 0xf0, 0x10, 0xf0,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x01, 0x79, 0x61, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60,
|
||||||
|
0x60, 0x60, 0x61, 0x79, 0x61, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60,
|
||||||
|
0x79, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x01, 0x79, 0x41, 0x40, 0x40, 0x40, 0x40, 0x40,
|
||||||
|
0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41,
|
||||||
|
0x79, 0x41, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40,
|
||||||
|
0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x40, 0x79, 0x41, 0x41,
|
||||||
|
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
|
||||||
|
0x40, 0x40, 0x40, 0x41, 0x41, 0x41, 0x78, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0xc0, 0x40, 0xce, 0x02, 0xc2, 0x42, 0xc2, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0xc2, 0x42, 0x42, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0xc2, 0x02, 0x82, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0x02, 0x42, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02,
|
||||||
|
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x4e, 0xc0,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x05, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x04, 0x07,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00,
|
||||||
|
0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x10, 0x2f, 0x50, 0xa0, 0x50, 0x2f, 0x10, 0x0f, 0x00,
|
||||||
|
0x00, 0x3f, 0x40, 0xbf, 0xa0, 0xa0, 0xa0, 0xbf, 0x40, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x7e, 0x22, 0x22, 0x3e, 0x00, 0x7e, 0x52, 0x52, 0x42, 0x00, 0x7e, 0x12, 0x12, 0x7e, 0x00,
|
||||||
|
0x7e, 0x08, 0x08, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
}}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
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)
|
||||||
|
)
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package rotary
|
||||||
|
|
||||||
|
type Event uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Clockwise Event = iota
|
||||||
|
CounterClockwise
|
||||||
|
KeyPress
|
||||||
|
KeyRelease
|
||||||
|
)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package input
|
||||||
|
|
||||||
|
type Source interface {
|
||||||
|
// Name returns the name of the source.
|
||||||
|
Name() string
|
||||||
|
|
||||||
|
// Events returns a channel that will be used to send events to the source.
|
||||||
|
Events() (<-chan Event, error)
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Color555 is a 16-bit RGB555 color.
|
||||||
|
//
|
||||||
|
// The 5 most significant bits are red, the 5 middle bits are green, and the 5 last ones are blue:
|
||||||
|
//
|
||||||
|
// 0RRRRRGG GGGBBBBB
|
||||||
|
type Color555 uint16
|
||||||
|
|
||||||
|
func (c Color555) RGBA() (r, g, b, a uint32) {
|
||||||
|
r = ((uint32(c&0x7c00) >> 10) * 255) / 31
|
||||||
|
r |= r << 8
|
||||||
|
g = ((uint32(c&0x03e0) >> 5) * 255) / 31
|
||||||
|
g |= g << 8
|
||||||
|
b = ((uint32(c&0x001f) >> 0) * 255) / 31
|
||||||
|
b |= b << 8
|
||||||
|
a = 0xFFFF
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var Color555Model color.Model = color.ModelFunc(color555Model)
|
||||||
|
|
||||||
|
func color555Model(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(Color565); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA() // 16 bits per channel
|
||||||
|
r = (r & 0xf800) >> 1 // .RRRRR.. ........
|
||||||
|
g = (g & 0xf800) >> 6 // ......GG GGG.....
|
||||||
|
b = (b & 0xf800) >> 11 // ........ ...BBBBB
|
||||||
|
return Color555(r | g | b)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Image555 struct {
|
||||||
|
Pix []byte
|
||||||
|
Rect image.Rectangle
|
||||||
|
Stride int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewImage555(r image.Rectangle) *Image555 {
|
||||||
|
var (
|
||||||
|
w, h = r.Dx(), r.Dy()
|
||||||
|
size = w * h * 2
|
||||||
|
pix = make([]byte, size)
|
||||||
|
)
|
||||||
|
return &Image555{pix, r, w * 2}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Image555) ColorModel() color.Model { return Color555Model }
|
||||||
|
func (i *Image555) Bounds() image.Rectangle { return i.Rect }
|
||||||
|
|
||||||
|
func (i *Image555) At(x, y int) color.Color {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return Color555(0)
|
||||||
|
}
|
||||||
|
o := y*i.Stride + x*2
|
||||||
|
return Color555(i.Pix[o]) | Color555(i.Pix[o+1])<<8
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Image555) Set(x, y int, c color.Color) {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
o := y*i.Stride + x*2
|
||||||
|
cc := color555Model(c).(Color555)
|
||||||
|
i.Pix[o] = byte(cc)
|
||||||
|
i.Pix[o+1] = byte(cc >> 8)
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var testsColor555 = []struct {
|
||||||
|
name string
|
||||||
|
test Color555
|
||||||
|
r, g, b uint32
|
||||||
|
}{
|
||||||
|
{"black",
|
||||||
|
Color555(0b000000000000000), 0, 0, 0},
|
||||||
|
{"white",
|
||||||
|
Color555(0b111111111111111), 255, 255, 255},
|
||||||
|
{"red",
|
||||||
|
Color555(0b111110000000000), 255, 0, 0},
|
||||||
|
{"green",
|
||||||
|
Color555(0b000001111100000), 0, 255, 0},
|
||||||
|
{"blue",
|
||||||
|
Color555(0b000001001111011), 0, 156, 222},
|
||||||
|
{"yellow",
|
||||||
|
Color555(0b111111011000001), 255, 180, 8},
|
||||||
|
{"cyan",
|
||||||
|
Color555(0b000001111111111), 0, 255, 255},
|
||||||
|
{"magenta",
|
||||||
|
Color555(0b111110000011111), 255, 0, 255},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestColor555(t *testing.T) {
|
||||||
|
for _, test := range testsColor555 {
|
||||||
|
t.Run(test.name, func(it *testing.T) {
|
||||||
|
r, g, b, _ := test.test.RGBA()
|
||||||
|
r >>= 8 // undo the premultiplication
|
||||||
|
g >>= 8
|
||||||
|
b >>= 8
|
||||||
|
if r != test.r || g != test.g || b != test.b {
|
||||||
|
it.Errorf("expected %d %d %d, got %d %d %d", test.r, test.g, test.b, r, g, b)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModel555(t *testing.T) {
|
||||||
|
for _, test := range testsColor555 {
|
||||||
|
t.Run(test.name, func(it *testing.T) {
|
||||||
|
c := Color555Model.Convert(color.RGBA{uint8(test.r), uint8(test.g), uint8(test.b), 255})
|
||||||
|
if c != test.test {
|
||||||
|
it.Errorf("expected %#04x, got %#04x", test.test, c)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Color565 is a 16-bit RGB565 color.
|
||||||
|
//
|
||||||
|
// The 5 most significant bits are red, the 6 middle bits are green, and the 5 last ones are blue:
|
||||||
|
//
|
||||||
|
// RRRRRGGG GGGBBBBB
|
||||||
|
type Color565 uint16
|
||||||
|
|
||||||
|
//func RGB565(r, g, b uint8) Color565 {
|
||||||
|
// return Color565(uint16(r&0xF8)<<8 | uint16(g&0xFC)<<3 | uint16(b>>3))
|
||||||
|
//}
|
||||||
|
|
||||||
|
func (c Color565) RGBA() (r, g, b, a uint32) {
|
||||||
|
r = ((uint32(c&0xf800) >> 11) * 255) / 31
|
||||||
|
r |= r << 8
|
||||||
|
g = ((uint32(c&0x07e0) >> 5) * 255) / 63
|
||||||
|
g |= g << 8
|
||||||
|
b = ((uint32(c&0x001f) >> 0) * 255) / 31
|
||||||
|
b |= b << 8
|
||||||
|
a = 0xFFFF
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var Color565Model color.Model = color.ModelFunc(color565Model)
|
||||||
|
|
||||||
|
func color565Model(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(Color565); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA() // 16 bits per channel
|
||||||
|
r = (r & 0xf800) // RRRRR... ........
|
||||||
|
g = (g & 0xfc00) >> 5 // .....GGG GGG.....
|
||||||
|
b = (b & 0xf800) >> 11 // ........ ...BBBBB
|
||||||
|
return Color565(r | g | b)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Image565 struct {
|
||||||
|
Pix []byte
|
||||||
|
Rect image.Rectangle
|
||||||
|
Stride int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewImage565(r image.Rectangle) *Image565 {
|
||||||
|
var (
|
||||||
|
w, h = r.Dx(), r.Dy()
|
||||||
|
size = w * h * 2
|
||||||
|
pix = make([]byte, size)
|
||||||
|
)
|
||||||
|
return &Image565{pix, r, w * 2}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Image565) ColorModel() color.Model { return Color565Model }
|
||||||
|
func (i *Image565) Bounds() image.Rectangle { return i.Rect }
|
||||||
|
|
||||||
|
func (i *Image565) At(x, y int) color.Color {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return Color565(0)
|
||||||
|
}
|
||||||
|
o := y*i.Stride + x*2
|
||||||
|
return Color565(i.Pix[o]) | Color565(i.Pix[o+1])<<8
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Image565) Set(x, y int, c color.Color) {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
o := y*i.Stride + x*2
|
||||||
|
cc := color565Model(c).(Color565)
|
||||||
|
i.Pix[o] = byte(cc)
|
||||||
|
i.Pix[o+1] = byte(cc >> 8)
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var testsColor565 = []struct {
|
||||||
|
name string
|
||||||
|
test Color565
|
||||||
|
r, g, b uint32
|
||||||
|
}{
|
||||||
|
{"black",
|
||||||
|
Color565(0b0000000000000000), 0, 0, 0},
|
||||||
|
{"white",
|
||||||
|
Color565(0b1111111111111111), 255, 255, 255},
|
||||||
|
{"red",
|
||||||
|
Color565(0b1111100000000000), 255, 0, 0},
|
||||||
|
{"green",
|
||||||
|
Color565(0b0000011111100000), 0, 255, 0},
|
||||||
|
{"blue",
|
||||||
|
Color565(0b0000010011111100), 0, 157, 230},
|
||||||
|
{"yellow",
|
||||||
|
Color565(0b1111110111000001), 255, 186, 8},
|
||||||
|
{"cyan",
|
||||||
|
Color565(0b0000011111111111), 0, 255, 255},
|
||||||
|
{"magenta",
|
||||||
|
Color565(0b1111100000011111), 255, 0, 255},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestColor565(t *testing.T) {
|
||||||
|
for _, test := range testsColor565 {
|
||||||
|
t.Run(test.name, func(it *testing.T) {
|
||||||
|
r, g, b, _ := test.test.RGBA()
|
||||||
|
r >>= 8 // undo the premultiplication
|
||||||
|
g >>= 8
|
||||||
|
b >>= 8
|
||||||
|
if r != test.r || g != test.g || b != test.b {
|
||||||
|
it.Errorf("expected %d %d %d, got %d %d %d", test.r, test.g, test.b, r, g, b)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModel565(t *testing.T) {
|
||||||
|
for _, test := range testsColor565 {
|
||||||
|
t.Run(test.name, func(it *testing.T) {
|
||||||
|
c := Color565Model.Convert(color.RGBA{uint8(test.r), uint8(test.g), uint8(test.b), 255})
|
||||||
|
if c != test.test {
|
||||||
|
it.Errorf("expected %#04x, got %#04x", test.test, c)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ToGrayBits converts a color to a n-bit grayscale color.
|
||||||
|
func ToGrayBits(c color.Color, n uint8) uint16 {
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
|
||||||
|
if n < 1 {
|
||||||
|
return 0 // no color
|
||||||
|
} else if n > 16 {
|
||||||
|
n = 16 // most that will fit
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shift values to fit n bits.
|
||||||
|
s := 32 - n
|
||||||
|
|
||||||
|
// These coefficients (the fractions 0.299, 0.587 and 0.114) are the same
|
||||||
|
// as those given by the JFIF specification and used by func RGBToYCbCr in
|
||||||
|
// image/color/ycbcr.go.
|
||||||
|
//
|
||||||
|
// Note that 19595 + 38470 + 7471 equals 65536.
|
||||||
|
//
|
||||||
|
// The 28 is 16 + 8 + n. The 16 is the same as used in RGBToYCbCr. The 8 + n is
|
||||||
|
// because the return value is n-bit color, not 16 bit color.
|
||||||
|
return uint16((19595*r + 38470*g + 7471*b + 1<<15) >> s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsOn(c color.Color) bool {
|
||||||
|
return ToGrayBits(c, 1) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsOff(c color.Color) bool {
|
||||||
|
return ToGrayBits(c, 1) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monochrome is a 1-bit color.
|
||||||
|
type Monochrome uint8
|
||||||
|
|
||||||
|
// Monochrome constants.
|
||||||
|
const (
|
||||||
|
On Monochrome = iota
|
||||||
|
Off
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m Monochrome) RGBA() (r, g, b, a uint32) {
|
||||||
|
if m == 0 {
|
||||||
|
return 0, 0, 0, 0
|
||||||
|
}
|
||||||
|
return 0xffff, 0xffff, 0xffff, 0xffff
|
||||||
|
}
|
||||||
|
|
||||||
|
var MonochromeModel color.Model = color.ModelFunc(monochromeModel)
|
||||||
|
|
||||||
|
func monochromeModel(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(Monochrome); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
if IsOn(c) {
|
||||||
|
return Monochrome(1)
|
||||||
|
}
|
||||||
|
return Monochrome(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
type MonochromeImage struct {
|
||||||
|
Pix []byte
|
||||||
|
Rect image.Rectangle
|
||||||
|
Stride int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMonochromeImage(r image.Rectangle) *MonochromeImage {
|
||||||
|
var (
|
||||||
|
w, h = r.Dx(), r.Dy()
|
||||||
|
size = w * h / 8
|
||||||
|
pix = make([]byte, size)
|
||||||
|
)
|
||||||
|
return &MonochromeImage{pix, r, w / 8}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *MonochromeImage) ColorModel() color.Model { return MonochromeModel }
|
||||||
|
func (i *MonochromeImage) Bounds() image.Rectangle { return i.Rect }
|
||||||
|
|
||||||
|
func (i *MonochromeImage) At(x, y int) color.Color {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return Monochrome(0)
|
||||||
|
}
|
||||||
|
o := y*i.Stride + x/8
|
||||||
|
return Monochrome(i.Pix[o] >> (7 - uint(x%8)) & 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *MonochromeImage) Set(x, y int, c color.Color) {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
o := y*i.Stride + x/8
|
||||||
|
if IsOn(c) {
|
||||||
|
i.Pix[o] |= 1 << (7 - uint(x%8))
|
||||||
|
} else {
|
||||||
|
i.Pix[o] &^= 1 << (7 - uint(x%8))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Gray4 represents a 4-bit grayscale color.
|
||||||
|
type Gray4 struct {
|
||||||
|
Y uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Gray4) RGBA() (r, g, b, a uint32) {
|
||||||
|
y := uint32(c.Y & 0x0f)
|
||||||
|
y |= y << 4
|
||||||
|
y |= y << 8
|
||||||
|
return y, y, y, 0xffff
|
||||||
|
}
|
||||||
|
|
||||||
|
var Gray4Model color.Model = color.ModelFunc(gray4Model)
|
||||||
|
|
||||||
|
func gray4Model(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(Gray4); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
|
||||||
|
// These coefficients (the fractions 0.299, 0.587 and 0.114) are the same
|
||||||
|
// as those given by the JFIF specification and used by func RGBToYCbCr in
|
||||||
|
// ycbcr.go.
|
||||||
|
//
|
||||||
|
// Note that 19595 + 38470 + 7471 equals 65536.
|
||||||
|
//
|
||||||
|
// The 28 is 16 + 8 + 4. The 16 is the same as used in RGBToYCbCr. The 8 + 4 is
|
||||||
|
// because the return value is 4 bit color, not 16 bit color.
|
||||||
|
y := (19595*r + 38470*g + 7471*b + 1<<15) >> 28
|
||||||
|
|
||||||
|
return Gray4{uint8(y)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageGray4 contains 4-bit grayscale pixels.
|
||||||
|
type ImageGray4 struct {
|
||||||
|
Pix []byte
|
||||||
|
Rect image.Rectangle
|
||||||
|
Stride int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewImageGray4(r image.Rectangle) *ImageGray4 {
|
||||||
|
var (
|
||||||
|
w, h = r.Dx(), r.Dy()
|
||||||
|
size = w * h / 2
|
||||||
|
pix = make([]byte, size)
|
||||||
|
)
|
||||||
|
return &ImageGray4{pix, r, w / 2}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *ImageGray4) ColorModel() color.Model { return Gray4Model }
|
||||||
|
func (i *ImageGray4) Bounds() image.Rectangle { return i.Rect }
|
||||||
|
|
||||||
|
func (i *ImageGray4) At(x, y int) color.Color {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return Gray4{0}
|
||||||
|
}
|
||||||
|
o := (y*i.Stride + x) >> 1
|
||||||
|
if x&1 == 0 { // even x is stored in the high bits
|
||||||
|
return Gray4{i.Pix[o] >> 4}
|
||||||
|
}
|
||||||
|
return Gray4{i.Pix[o] & 0x0f}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *ImageGray4) Set(x, y int, c color.Color) {
|
||||||
|
if !(image.Point{x, y}.In(i.Rect)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
o := (y*i.Stride + x) >> 1
|
||||||
|
if x&1 == 0 { // even x is stored in the high bits
|
||||||
|
i.Pix[o] = i.Pix[o]&0x0f | c.(Gray4).Y<<4
|
||||||
|
} else {
|
||||||
|
i.Pix[o] = i.Pix[o]&0xf0 | c.(Gray4).Y
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package dsp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/cmplx"
|
||||||
|
|
||||||
|
"github.com/maddyblue/go-dsp/fft"
|
||||||
|
"periph.io/x/conn/v3/physic"
|
||||||
|
|
||||||
|
"git.maze.io/go/bragi/internal/audio"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Analyzer for audio signals.
|
||||||
|
type Analyzer struct {
|
||||||
|
signal audio.Complex128
|
||||||
|
}
|
||||||
|
|
||||||
|
type FrequencySpectrum struct {
|
||||||
|
// Store the frequency spectrum values
|
||||||
|
Spectrum []float64
|
||||||
|
|
||||||
|
// Store the frequencies used
|
||||||
|
Frequencies []float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// FrequencySpectrum calculates the frequency spectrum of the signal.
|
||||||
|
func (s *Analyzer) FrequencySpectrum(samples audio.Slice, rate physic.Frequency) (*FrequencySpectrum, error) {
|
||||||
|
// Copy the samples to our complex buffer.
|
||||||
|
length := samples.Len()
|
||||||
|
if len(s.signal) < length {
|
||||||
|
s.signal = make(audio.Complex128, length)
|
||||||
|
} else {
|
||||||
|
s.signal = s.signal[:length]
|
||||||
|
}
|
||||||
|
samples.CopyTo(s.signal)
|
||||||
|
|
||||||
|
// Apply the FFT on the signal to get the frequency components
|
||||||
|
ffft := fft.FFT(s.signal)
|
||||||
|
|
||||||
|
// Compute the two sided spectrum
|
||||||
|
var spectrum2 []float64
|
||||||
|
|
||||||
|
flength := float64(length)
|
||||||
|
for i := range ffft {
|
||||||
|
// Get the absolute value since the fft is a complex value with both real and imaginary parts
|
||||||
|
spectrum2 = append(spectrum2, cmplx.Abs(ffft[i])/flength)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look at the one sided spectrum
|
||||||
|
spectrum1 := spectrum2[0 : len(spectrum2)/2]
|
||||||
|
|
||||||
|
for i := range spectrum1 {
|
||||||
|
spectrum1[i] = spectrum1[i] * 2
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
frequencies []float64
|
||||||
|
spectrumLength = float64(len(spectrum2))
|
||||||
|
scale = rate.Period().Seconds() / spectrumLength
|
||||||
|
)
|
||||||
|
for i := range spectrum1 {
|
||||||
|
// Calculate which frequencies the spectrum contains
|
||||||
|
frequencies = append(frequencies, float64(i)*scale)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &FrequencySpectrum{
|
||||||
|
Spectrum: spectrum1,
|
||||||
|
Frequencies: frequencies,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Pixel with a particular color, matching the underlying hardware of a
|
||||||
|
// particular display. Each pixel is at least 1 byte in size.
|
||||||
|
// The color format is sRGB (or close to it) in all cases except for 1-bit.
|
||||||
|
type Color interface {
|
||||||
|
RGB888 | RGB565BE | RGB555 | RGB444BE | Monochrome
|
||||||
|
|
||||||
|
BaseColor
|
||||||
|
}
|
||||||
|
|
||||||
|
// BaseColor contains all the methods needed in a color format. This can be used
|
||||||
|
// in display drivers that want to define their own Color type with just the
|
||||||
|
// pixel formats the display supports.
|
||||||
|
type BaseColor interface {
|
||||||
|
color.Color
|
||||||
|
|
||||||
|
// The number of bits when stored.
|
||||||
|
// This means for example that RGB555 (which is still stored as a 16-bit
|
||||||
|
// integer) returns 16, while RGB444 returns 12.
|
||||||
|
BitsPerPixel() int
|
||||||
|
|
||||||
|
// Return the given color in color.RGBA format, which is always sRGB. The
|
||||||
|
// alpha channel is always 255.
|
||||||
|
RGBAColor() color.RGBA
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewColor returns the given color based on the RGB values passed in the
|
||||||
|
// parameters. The input value is assumed to be in sRGB color space.
|
||||||
|
func NewColor[T Color](r, g, b uint8) T {
|
||||||
|
// Ugly cast from color.RGBA to T. The type switch and interface casts are
|
||||||
|
// trivially optimized away after instantiation.
|
||||||
|
var value T
|
||||||
|
switch any(value).(type) {
|
||||||
|
case RGB888:
|
||||||
|
return any(NewRGB888(r, g, b)).(T)
|
||||||
|
case RGB565BE:
|
||||||
|
return any(NewRGB565BE(r, g, b)).(T)
|
||||||
|
case RGB555:
|
||||||
|
return any(NewRGB555(r, g, b)).(T)
|
||||||
|
case RGB444BE:
|
||||||
|
return any(NewRGB444BE(r, g, b)).(T)
|
||||||
|
case Monochrome:
|
||||||
|
return any(NewMonochrome(r, g, b)).(T)
|
||||||
|
default:
|
||||||
|
panic("unknown color format")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromColor retusn the given color.
|
||||||
|
func FromColor[T Color](c color.Color) T {
|
||||||
|
var value T
|
||||||
|
switch any(value).(type) {
|
||||||
|
case RGB888:
|
||||||
|
return rgb888Model(c).(T)
|
||||||
|
case RGB565BE:
|
||||||
|
return rgb565BEModel(c).(T)
|
||||||
|
case RGB555:
|
||||||
|
return rgb555Model(c).(T)
|
||||||
|
case RGB444BE:
|
||||||
|
return rgb444BEModel(c).(T)
|
||||||
|
case Monochrome:
|
||||||
|
return monochromeModel(c).(T)
|
||||||
|
default:
|
||||||
|
panic("unknown color format")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLinearColor returns the given color based on the linear RGB values passed
|
||||||
|
// in the parameters. Use this if the RGB values are actually linear colors
|
||||||
|
// (like those that are used in most RGB LEDs) and not when it is in the usual
|
||||||
|
// sRGB color space (which is not linear).
|
||||||
|
//
|
||||||
|
// The input is assumed to be in the linear sRGB color space.
|
||||||
|
func NewLinearColor[T Color](r, g, b uint8) T {
|
||||||
|
r = gammaEncodeTable[r]
|
||||||
|
g = gammaEncodeTable[g]
|
||||||
|
b = gammaEncodeTable[b]
|
||||||
|
return NewColor[T](r, g, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RGB888 format, more commonly used in other places (desktop PC displays, CSS,
|
||||||
|
// etc). Less commonly used on embedded displays due to the higher memory usage.
|
||||||
|
type RGB888 struct {
|
||||||
|
R, G, B uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRGB888(r, g, b uint8) RGB888 {
|
||||||
|
return RGB888{r, g, b}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB888) BitsPerPixel() int {
|
||||||
|
return 24
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB888) RGBA() (r, g, b, a uint32) {
|
||||||
|
r = uint32(c.R)
|
||||||
|
r |= r << 8
|
||||||
|
g = uint32(c.G)
|
||||||
|
g |= g << 8
|
||||||
|
b = uint32(c.B)
|
||||||
|
b |= b << 8
|
||||||
|
a = 0xffff
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB888) RGBAColor() color.RGBA {
|
||||||
|
return color.RGBA{
|
||||||
|
R: c.R,
|
||||||
|
G: c.G,
|
||||||
|
B: c.B,
|
||||||
|
A: 255,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RGB565 as used in many SPI displays. Stored as a big endian value.
|
||||||
|
//
|
||||||
|
// The color format in integer form is gggbbbbb_rrrrrggg on little endian
|
||||||
|
// systems, which is the standard RGB565 format but with the top and bottom
|
||||||
|
// bytes swapped.
|
||||||
|
//
|
||||||
|
// There are a few alternatives to this weird big-endian format, but they're not
|
||||||
|
// great:
|
||||||
|
// - Storing the value in two 8-bit stores (to make the code endian-agnostic)
|
||||||
|
// incurs too much of a performance penalty.
|
||||||
|
// - Swapping the upper and lower bits just before storing. This is still less
|
||||||
|
// efficient than it could be, since colors are usually constructed once and
|
||||||
|
// then reused in many store operations. Doing the swap once instead of many
|
||||||
|
// times for each store is a performance win.
|
||||||
|
type RGB565BE uint16
|
||||||
|
|
||||||
|
func NewRGB565BE(r, g, b uint8) RGB565BE {
|
||||||
|
val := uint16(r&0xF8)<<8 +
|
||||||
|
uint16(g&0xFC)<<3 +
|
||||||
|
uint16(b&0xF8)>>3
|
||||||
|
// Swap endianness (make big endian).
|
||||||
|
// This is done using a single instruction on ARM (rev16).
|
||||||
|
// TODO: this should only be done on little endian systems, but TinyGo
|
||||||
|
// doesn't currently (2023) support big endian systems so it's difficult to
|
||||||
|
// test. Also, big endian systems don't seem fasionable these days.
|
||||||
|
//val = bits.ReverseBytes16(val)
|
||||||
|
return RGB565BE(val)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB565BE) BitsPerPixel() int {
|
||||||
|
return 16
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB565BE) RGBA() (r, g, b, a uint32) {
|
||||||
|
r = uint32(uint8(c>>12) << 3)
|
||||||
|
r |= (r >> 5)
|
||||||
|
r |= (r << 8)
|
||||||
|
g = uint32(uint8(c>>5) << 2)
|
||||||
|
g |= (g >> 6)
|
||||||
|
g |= (g << 8)
|
||||||
|
b = uint32(uint8(c>>0) << 3)
|
||||||
|
b |= (b >> 5)
|
||||||
|
b |= (b << 8)
|
||||||
|
a = 0xffff
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB565BE) RGBAColor() color.RGBA {
|
||||||
|
// Note: on ARM, the compiler uses a rev instruction instead of a rev16
|
||||||
|
// instruction. I wonder whether this can be optimized further to use rev16
|
||||||
|
// instead?
|
||||||
|
c = c<<8 | c>>8
|
||||||
|
color := color.RGBA{
|
||||||
|
R: uint8(c>>11) << 3,
|
||||||
|
G: uint8(c>>5) << 2,
|
||||||
|
B: uint8(c) << 3,
|
||||||
|
A: 255,
|
||||||
|
}
|
||||||
|
// Correct color rounding, so that 0xff roundtrips back to 0xff.
|
||||||
|
color.R |= color.R >> 5
|
||||||
|
color.G |= color.G >> 6
|
||||||
|
color.B |= color.B >> 5
|
||||||
|
return color
|
||||||
|
}
|
||||||
|
|
||||||
|
// Color format used on the GameBoy Advance among others.
|
||||||
|
//
|
||||||
|
// Colors are stored as native endian values, with bits 0bbbbbgg_gggrrrrr (red
|
||||||
|
// is least significant, blue is most significant).
|
||||||
|
type RGB555 uint16
|
||||||
|
|
||||||
|
func NewRGB555(r, g, b uint8) RGB555 {
|
||||||
|
return RGB555(r)>>3 | (RGB555(g)>>3)<<5 | (RGB555(b)>>3)<<10
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB555) BitsPerPixel() int {
|
||||||
|
// 15 bits per pixel, but there are 16 bits when stored
|
||||||
|
return 16
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB555) RGBA() (r, g, b, a uint32) {
|
||||||
|
r = uint32(uint8(c>>10) << 3)
|
||||||
|
r |= (r >> 5)
|
||||||
|
r |= (r << 8)
|
||||||
|
g = uint32(uint8(c>>5) << 3)
|
||||||
|
g |= (g >> 5)
|
||||||
|
g |= (g << 8)
|
||||||
|
b = uint32(uint8(c>>0) << 3)
|
||||||
|
b |= (b >> 5)
|
||||||
|
b |= (b << 8)
|
||||||
|
a = 0xffff
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB555) RGBAColor() color.RGBA {
|
||||||
|
color := color.RGBA{
|
||||||
|
R: uint8(c>>10) << 3,
|
||||||
|
G: uint8(c>>5) << 3,
|
||||||
|
B: uint8(c) << 3,
|
||||||
|
A: 255,
|
||||||
|
}
|
||||||
|
// Correct color rounding, so that 0xff roundtrips back to 0xff.
|
||||||
|
color.R |= color.R >> 5
|
||||||
|
color.G |= color.G >> 5
|
||||||
|
color.B |= color.B >> 5
|
||||||
|
return color
|
||||||
|
}
|
||||||
|
|
||||||
|
// Color format that is supported by the ST7789 for example.
|
||||||
|
// It may be a bit faster to use than RGB565BE on very slow SPI buses.
|
||||||
|
//
|
||||||
|
// The color format is native endian as a uint16 (0000rrrr_ggggbbbb), not big
|
||||||
|
// endian which you might expect. I tried swapping the bytes, but it didn't have
|
||||||
|
// much of a performance impact and made the code harder to read. It is stored
|
||||||
|
// as a 12-bit big endian value in Image[RGB444BE] though.
|
||||||
|
type RGB444BE uint16
|
||||||
|
|
||||||
|
func NewRGB444BE(r, g, b uint8) RGB444BE {
|
||||||
|
return RGB444BE(r>>4)<<8 | RGB444BE(g>>4)<<4 | RGB444BE(b>>4)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB444BE) BitsPerPixel() int {
|
||||||
|
return 12
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB444BE) RGBA() (r, g, b, a uint32) {
|
||||||
|
r = uint32(c>>8) & 0x0f
|
||||||
|
r |= (r << 4) | (r << 8) | (r << 12)
|
||||||
|
g = uint32(c>>4) & 0x0f
|
||||||
|
g |= (g << 4) | (g << 8) | (g << 12)
|
||||||
|
b = uint32(c>>0) & 0x0f
|
||||||
|
b |= (b << 4) | (b << 8) | (b << 12)
|
||||||
|
a |= 0xffff
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c RGB444BE) RGBAColor() color.RGBA {
|
||||||
|
color := color.RGBA{
|
||||||
|
R: uint8(c>>8) << 4,
|
||||||
|
G: uint8(c>>4) << 4,
|
||||||
|
B: uint8(c>>0) << 4,
|
||||||
|
A: 255,
|
||||||
|
}
|
||||||
|
// Correct color rounding, so that 0xff roundtrips back to 0xff.
|
||||||
|
color.R |= color.R >> 4
|
||||||
|
color.G |= color.G >> 4
|
||||||
|
color.B |= color.B >> 4
|
||||||
|
return color
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monochrome is a 1-bit color.
|
||||||
|
type Monochrome uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Off Monochrome = iota
|
||||||
|
On
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewMonochrome(r, g, b uint8) Monochrome {
|
||||||
|
// Very simple black/white split.
|
||||||
|
// This isn't very accurate (especially for sRGB colors) but is close enough.
|
||||||
|
if int(r)+int(g)+int(b) > 128*3 { // light, convert to white
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
// dark, convert to black
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Monochrome) BitsPerPixel() int {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Monochrome) RGBA() (r, g, b, a uint32) {
|
||||||
|
if c > 0 {
|
||||||
|
return 0xffff, 0xffff, 0xffff, 0xffff
|
||||||
|
}
|
||||||
|
return 0, 0, 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Monochrome) RGBAColor() color.RGBA {
|
||||||
|
value := uint8(0)
|
||||||
|
if c > 0 {
|
||||||
|
value = 255
|
||||||
|
}
|
||||||
|
return color.RGBA{
|
||||||
|
R: value,
|
||||||
|
G: value,
|
||||||
|
B: value,
|
||||||
|
A: 255,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gamma brightness lookup table:
|
||||||
|
// https://victornpb.github.io/gamma-table-generator
|
||||||
|
// gamma = 0.45 steps = 256 range = 0-255
|
||||||
|
var gammaEncodeTable = [256]uint8{
|
||||||
|
0, 21, 28, 34, 39, 43, 46, 50, 53, 56, 59, 61, 64, 66, 68, 70,
|
||||||
|
72, 74, 76, 78, 80, 82, 84, 85, 87, 89, 90, 92, 93, 95, 96, 98,
|
||||||
|
99, 101, 102, 103, 105, 106, 107, 109, 110, 111, 112, 114, 115, 116, 117, 118,
|
||||||
|
119, 120, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
|
||||||
|
136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150,
|
||||||
|
151, 151, 152, 153, 154, 155, 156, 156, 157, 158, 159, 160, 160, 161, 162, 163,
|
||||||
|
164, 164, 165, 166, 167, 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175,
|
||||||
|
175, 176, 177, 178, 178, 179, 180, 180, 181, 182, 182, 183, 184, 184, 185, 186,
|
||||||
|
186, 187, 188, 188, 189, 190, 190, 191, 192, 192, 193, 194, 194, 195, 195, 196,
|
||||||
|
197, 197, 198, 199, 199, 200, 200, 201, 202, 202, 203, 203, 204, 205, 205, 206,
|
||||||
|
206, 207, 207, 208, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 214, 215,
|
||||||
|
215, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 223, 223, 224,
|
||||||
|
224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232,
|
||||||
|
232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, 240,
|
||||||
|
240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248,
|
||||||
|
248, 249, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255, 255,
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsOn checks if the pixel is on or off.
|
||||||
|
func IsOn(c color.Color) bool {
|
||||||
|
return monochromeModel(c) == On
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface checks
|
||||||
|
var (
|
||||||
|
_ color.Color = (*RGB888)(nil)
|
||||||
|
_ color.Color = (*RGB565BE)(nil)
|
||||||
|
_ color.Color = (*RGB555)(nil)
|
||||||
|
_ color.Color = (*RGB444BE)(nil)
|
||||||
|
_ color.Color = (*Monochrome)(nil)
|
||||||
|
)
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/draw"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Image buffer, used for working with the native image format of various
|
||||||
|
// displays. It works a lot like a slice: it can be rescaled while reusing the
|
||||||
|
// underlying buffer and should be passed around by value.
|
||||||
|
type Image[T Color] struct {
|
||||||
|
width int16
|
||||||
|
height int16
|
||||||
|
data unsafe.Pointer
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImage creates a new image of the given size.
|
||||||
|
func NewImage[T Color](width, height int) Image[T] {
|
||||||
|
if width < 0 || height < 0 || int(int16(width)) != width || int(int16(height)) != height {
|
||||||
|
// The width/height are stored as 16-bit integers and should never be
|
||||||
|
// negative.
|
||||||
|
panic("NewImage: width/height out of bounds")
|
||||||
|
}
|
||||||
|
var zeroColor T
|
||||||
|
var data unsafe.Pointer
|
||||||
|
switch {
|
||||||
|
case zeroColor.BitsPerPixel()%8 == 0:
|
||||||
|
// Typical formats like RGB888 and RGB565.
|
||||||
|
// Each color starts at a whole byte offset from the start.
|
||||||
|
buf := make([]T, width*height)
|
||||||
|
data = unsafe.Pointer(&buf[0])
|
||||||
|
default:
|
||||||
|
// Formats like RGB444 that have 12 bits per pixel.
|
||||||
|
// We access these as bytes, so allocate the buffer as a byte slice.
|
||||||
|
bufBits := width * height * zeroColor.BitsPerPixel()
|
||||||
|
bufBytes := (bufBits + 7) / 8
|
||||||
|
buf := make([]byte, bufBytes)
|
||||||
|
data = unsafe.Pointer(&buf[0])
|
||||||
|
}
|
||||||
|
return Image[T]{
|
||||||
|
width: int16(width),
|
||||||
|
height: int16(height),
|
||||||
|
data: data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImageFromBytes creates a new image of the given size using an existing data slice of bytes.
|
||||||
|
func NewImageFromBytes[T Color](width, height int, buf []byte) Image[T] {
|
||||||
|
if width < 0 || height < 0 || int(int16(width)) != width || int(int16(height)) != height {
|
||||||
|
// The width/height are stored as 16-bit integers and should never be
|
||||||
|
// negative.
|
||||||
|
panic("NewImageFromBytes: width/height out of bounds")
|
||||||
|
}
|
||||||
|
var zeroColor T
|
||||||
|
var data unsafe.Pointer
|
||||||
|
switch {
|
||||||
|
case zeroColor.BitsPerPixel()%8 == 0:
|
||||||
|
// Typical formats like RGB888 and RGB565.
|
||||||
|
// Each color starts at a whole byte offset from the start.
|
||||||
|
if len(buf) != width*height*int(unsafe.Sizeof(zeroColor)) {
|
||||||
|
panic("NewImageFromBytes: data slice size mismatch")
|
||||||
|
}
|
||||||
|
data = unsafe.Pointer(&buf[0])
|
||||||
|
default:
|
||||||
|
// Formats like RGB444 that have 12 bits per pixel.
|
||||||
|
// We access these as bytes, so allocate the buffer as a byte slice.
|
||||||
|
bufBits := width * height * zeroColor.BitsPerPixel()
|
||||||
|
bufBytes := (bufBits + 7) / 8
|
||||||
|
if len(buf) != bufBytes {
|
||||||
|
panic("NewImageFromBytes: data slice size mismatch")
|
||||||
|
}
|
||||||
|
data = unsafe.Pointer(&buf[0])
|
||||||
|
}
|
||||||
|
return Image[T]{
|
||||||
|
width: int16(width),
|
||||||
|
height: int16(height),
|
||||||
|
data: data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImageFromImage creates a new image from the provided image.
|
||||||
|
func NewImageFromImage[T Color](src image.Image) Image[T] {
|
||||||
|
var (
|
||||||
|
r = src.Bounds()
|
||||||
|
width = r.Dx()
|
||||||
|
height = r.Dy()
|
||||||
|
dst = NewImage[T](width, height)
|
||||||
|
)
|
||||||
|
draw.Draw(dst, r, src, image.Point{}, draw.Src)
|
||||||
|
return dst
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rescale returns a new Image buffer based on the img buffer.
|
||||||
|
// The contents is undefined after the Rescale operation, and any modification
|
||||||
|
// to the returned image will overwrite the underlying image buffer in undefined
|
||||||
|
// ways. It will panic if width*height is larger than img.Len().
|
||||||
|
func (img Image[T]) Rescale(width, height int) Image[T] {
|
||||||
|
if width*height > img.Len() {
|
||||||
|
panic("Image.Rescale size out of bounds")
|
||||||
|
}
|
||||||
|
return Image[T]{
|
||||||
|
width: int16(width),
|
||||||
|
height: int16(height),
|
||||||
|
data: img.data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LimitHeight returns a subimage with the bottom part cut off, as specified by
|
||||||
|
// height.
|
||||||
|
func (img Image[T]) LimitHeight(height int) Image[T] {
|
||||||
|
if height < 0 || height > int(img.height) {
|
||||||
|
panic("Image.LimitHeight: out of bounds")
|
||||||
|
}
|
||||||
|
return Image[T]{
|
||||||
|
width: img.width,
|
||||||
|
height: int16(height),
|
||||||
|
data: img.data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len returns the number of pixels in this image buffer.
|
||||||
|
func (img Image[T]) Len() int {
|
||||||
|
return int(img.width) * int(img.height)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RawBuffer returns a byte slice that can be written directly to the screen
|
||||||
|
// using DrawRGBBitmap8.
|
||||||
|
func (img Image[T]) RawBuffer() []uint8 {
|
||||||
|
var zeroColor T
|
||||||
|
var numBytes int
|
||||||
|
switch {
|
||||||
|
case zeroColor.BitsPerPixel()%8 == 0:
|
||||||
|
// Each color starts at a whole byte offset.
|
||||||
|
numBytes = int(unsafe.Sizeof(zeroColor)) * int(img.width) * int(img.height)
|
||||||
|
default:
|
||||||
|
// Formats like RGB444 that aren't a whole number of bytes.
|
||||||
|
numBits := zeroColor.BitsPerPixel() * int(img.width) * int(img.height)
|
||||||
|
numBytes = (numBits + 7) / 8 // round up (see NewImage)
|
||||||
|
}
|
||||||
|
return unsafe.Slice((*byte)(img.data), numBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the image size.
|
||||||
|
func (img Image[T]) Size() (int, int) {
|
||||||
|
return int(img.width), int(img.height)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (img Image[T]) setPixel(index int, c T) {
|
||||||
|
var zeroColor T
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case zeroColor.BitsPerPixel() == 1:
|
||||||
|
// Monochrome.
|
||||||
|
offset := index / 8
|
||||||
|
bits := index % 8
|
||||||
|
|
||||||
|
ptr := (*byte)(unsafe.Add(img.data, offset))
|
||||||
|
if c != zeroColor {
|
||||||
|
*((*byte)(ptr)) |= (1 << (7 - uint8(bits)))
|
||||||
|
} else {
|
||||||
|
*((*byte)(ptr)) &^= (1 << (7 - uint8(bits)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
case zeroColor.BitsPerPixel()%8 == 0:
|
||||||
|
// Each color starts at a whole byte offset.
|
||||||
|
// This is the easy case.
|
||||||
|
offset := index * int(unsafe.Sizeof(zeroColor))
|
||||||
|
ptr := unsafe.Add(img.data, offset)
|
||||||
|
*((*T)(ptr)) = c
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if c, ok := any(c).(RGB444BE); ok {
|
||||||
|
// Special case for RGB444.
|
||||||
|
bitIndex := index * zeroColor.BitsPerPixel()
|
||||||
|
if bitIndex%8 == 0 {
|
||||||
|
byteOffset := bitIndex / 8
|
||||||
|
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||||
|
ptr[0] = uint8(c >> 4)
|
||||||
|
ptr[1] = ptr[1]&0x0f | uint8(c)<<4 // change top bits
|
||||||
|
} else {
|
||||||
|
byteOffset := bitIndex / 8
|
||||||
|
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||||
|
ptr[0] = ptr[0]&0xf0 | uint8(c>>8) // change bottom bits
|
||||||
|
ptr[1] = uint8(c)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: the code for RGB444 should be generalized to support any bit size.
|
||||||
|
panic("todo: setPixel for odd bits per pixel")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set sets the pixel at x, y to the given color.
|
||||||
|
// Use FillSolidColor to efficiently fill the entire image buffer.
|
||||||
|
func (img Image[T]) SetPixel(x, y int, c T) {
|
||||||
|
if uint(x) >= uint(int(img.width)) || uint(y) >= uint(int(img.height)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
index := y*int(img.width) + x
|
||||||
|
img.setPixel(index, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns the color at the given index.
|
||||||
|
func (img Image[T]) GetPixel(x, y int) T {
|
||||||
|
var zeroColor T
|
||||||
|
if uint(x) >= uint(int(img.width)) || uint(y) >= uint(int(img.height)) {
|
||||||
|
return zeroColor
|
||||||
|
}
|
||||||
|
index := y*int(img.width) + x // index into img.data
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case zeroColor.BitsPerPixel() == 1:
|
||||||
|
// Monochrome.
|
||||||
|
var c Monochrome
|
||||||
|
offset := index / 8
|
||||||
|
bits := index % 8
|
||||||
|
ptr := (*byte)(unsafe.Add(img.data, offset))
|
||||||
|
c = Monochrome((*ptr >> (7 - uint8(bits))) & 0x1)
|
||||||
|
return any(c).(T)
|
||||||
|
case zeroColor.BitsPerPixel()%8 == 0:
|
||||||
|
// Colors like RGB565, RGB888, etc.
|
||||||
|
offset := index * int(unsafe.Sizeof(zeroColor))
|
||||||
|
ptr := unsafe.Add(img.data, offset)
|
||||||
|
return *((*T)(ptr))
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := any(zeroColor).(RGB444BE); ok {
|
||||||
|
// Special case for RGB444 that isn't stored in a neat byte multiple.
|
||||||
|
bitIndex := index * zeroColor.BitsPerPixel()
|
||||||
|
var c RGB444BE
|
||||||
|
if bitIndex%8 == 0 {
|
||||||
|
byteOffset := bitIndex / 8
|
||||||
|
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||||
|
c |= RGB444BE(ptr[0]) << 4
|
||||||
|
c |= RGB444BE(ptr[1] >> 4) // load top bits
|
||||||
|
} else {
|
||||||
|
byteOffset := bitIndex / 8
|
||||||
|
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||||
|
c |= RGB444BE(ptr[0]&0x0f) << 8 // load bottom bits
|
||||||
|
c |= RGB444BE(ptr[1])
|
||||||
|
}
|
||||||
|
return any(c).(T)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: generalize the above code.
|
||||||
|
panic("todo: Image.Get for odd bits per pixel")
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillSolidColor fills the entire image with the given color.
|
||||||
|
// This may be faster than setting individual pixels.
|
||||||
|
func (img Image[T]) FillSolidColor(color T) {
|
||||||
|
var zeroColor T
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case zeroColor.BitsPerPixel() == 1:
|
||||||
|
// Monochrome.
|
||||||
|
var colorByte uint8
|
||||||
|
if color != zeroColor {
|
||||||
|
colorByte = 0xff
|
||||||
|
}
|
||||||
|
numBytes := int(img.width) * int(img.height) / 8
|
||||||
|
for i := 0; i < numBytes; i++ {
|
||||||
|
// TODO: this can be optimized a lot.
|
||||||
|
// - The store can be done as a 32-bit integer, after checking for
|
||||||
|
// alignment.
|
||||||
|
// - Perhaps the loop can be unrolled to improve copy performance.
|
||||||
|
ptr := (*byte)(unsafe.Add(img.data, i))
|
||||||
|
*((*byte)(ptr)) = colorByte
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
case zeroColor.BitsPerPixel()%8 == 0:
|
||||||
|
// Fast pass for colors of 8, 16, 24, etc bytes in size.
|
||||||
|
ptr := img.data
|
||||||
|
for i := 0; i < img.Len(); i++ {
|
||||||
|
// TODO: this can be optimized a lot.
|
||||||
|
// - The store can be done as a 32-bit integer, after checking for
|
||||||
|
// alignment.
|
||||||
|
// - Perhaps the loop can be unrolled to improve copy performance.
|
||||||
|
*(*T)(ptr) = color
|
||||||
|
ptr = unsafe.Add(ptr, unsafe.Sizeof(zeroColor))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special case for RGB444.
|
||||||
|
if c, ok := any(color).(RGB444BE); ok {
|
||||||
|
// RGB444 can be stored in a more optimized way, by storing two colors
|
||||||
|
// at a time instead of setting each color individually. This avoids
|
||||||
|
// loading and masking the old color bits for the half-bytes.
|
||||||
|
var buf [3]uint8
|
||||||
|
buf[0] = uint8(c >> 4)
|
||||||
|
buf[1] = uint8(c)<<4 | uint8(c>>8)
|
||||||
|
buf[2] = uint8(c)
|
||||||
|
rawBuf := unsafe.Slice((*[3]byte)(img.data), img.Len()/2)
|
||||||
|
for i := 0; i < len(rawBuf); i++ {
|
||||||
|
rawBuf[i] = buf
|
||||||
|
}
|
||||||
|
if img.Len()%2 != 0 {
|
||||||
|
// The image contains an uneven number of pixels.
|
||||||
|
// This is uncommon, but it can happen and we have to handle it.
|
||||||
|
img.setPixel(img.Len()-1, color)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback for other color formats.
|
||||||
|
for i := 0; i < img.Len(); i++ {
|
||||||
|
img.setPixel(i, color)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// At implements the draw.Image interface.
|
||||||
|
func (img Image[T]) At(x, y int) color.Color {
|
||||||
|
return img.GetPixel(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set implements the draw.Image interface.
|
||||||
|
func (img Image[T]) Set(x, y int, c color.Color) {
|
||||||
|
var value T
|
||||||
|
switch any(value).(type) {
|
||||||
|
case RGB888:
|
||||||
|
img.SetPixel(x, y, rgb888Model(c).(T))
|
||||||
|
case RGB565BE:
|
||||||
|
img.SetPixel(x, y, rgb565BEModel(c).(T))
|
||||||
|
case RGB555:
|
||||||
|
img.SetPixel(x, y, rgb555Model(c).(T))
|
||||||
|
case RGB444BE:
|
||||||
|
img.SetPixel(x, y, rgb444BEModel(c).(T))
|
||||||
|
case Monochrome:
|
||||||
|
img.SetPixel(x, y, monochromeModel(c).(T))
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bounds returns the image bounding box.
|
||||||
|
func (img Image[T]) Bounds() image.Rectangle {
|
||||||
|
return image.Rect(0, 0, int(img.width), int(img.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ColorModel returns the image color model.
|
||||||
|
func (img Image[T]) ColorModel() color.Model {
|
||||||
|
// Ugly cast from color.RGBA to T. The type switch and interface casts are
|
||||||
|
// trivially optimized away after instantiation.
|
||||||
|
var value T
|
||||||
|
switch any(value).(type) {
|
||||||
|
case RGB888:
|
||||||
|
return RGB888Model
|
||||||
|
case RGB565BE:
|
||||||
|
return RGB565BEModel
|
||||||
|
case RGB555:
|
||||||
|
return RGB555Model
|
||||||
|
case RGB444BE:
|
||||||
|
return RGB444BEModel
|
||||||
|
case Monochrome:
|
||||||
|
return MonochromeModel
|
||||||
|
default:
|
||||||
|
panic("unknown color format")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear the image buffer.
|
||||||
|
func (img *Image[T]) Clear() {
|
||||||
|
var zeroColor T
|
||||||
|
img.FillSolidColor(zeroColor)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ draw.Image = (*Image[RGB888])(nil)
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package pixel
|
||||||
|
|
||||||
|
import "image/color"
|
||||||
|
|
||||||
|
var (
|
||||||
|
RGB888Model color.Model = color.ModelFunc(rgb888Model)
|
||||||
|
RGB565BEModel color.Model = color.ModelFunc(rgb565BEModel)
|
||||||
|
RGB555Model color.Model = color.ModelFunc(rgb555Model)
|
||||||
|
RGB444BEModel color.Model = color.ModelFunc(rgb444BEModel)
|
||||||
|
MonochromeModel color.Model = color.ModelFunc(monochromeModel)
|
||||||
|
)
|
||||||
|
|
||||||
|
func rgb888Model(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(RGB888); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return RGB888{
|
||||||
|
R: uint8(r >> 8),
|
||||||
|
G: uint8(g >> 8),
|
||||||
|
B: uint8(b >> 8),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func rgb565BEModel(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(RGB565BE); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return RGB565BE(uint16((r>>8)&0xF8)<<8 + uint16((g>>8)&0xFC)<<3 + uint16((b>>8)&0xF8)>>3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func rgb555Model(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(RGB555); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return RGB555(r>>11) | RGB555(g>>11)<<5 | RGB555(b>>11)<<10
|
||||||
|
}
|
||||||
|
|
||||||
|
func rgb444BEModel(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(RGB444BE); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return RGB444BE(r>>12)<<8 | RGB444BE(g>>12)<<4 | RGB444BE(b>>12)
|
||||||
|
}
|
||||||
|
|
||||||
|
func monochromeModel(c color.Color) color.Color {
|
||||||
|
if _, ok := c.(Monochrome); ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
r, g, b, _ := c.RGBA()
|
||||||
|
return NewMonochrome(uint8(r>>8), uint8(g>>8), uint8(b>>8))
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
// Copyright (C) 2007-2008 Jean-Marc Valin
|
||||||
|
// Copyright (C) 2008 Thorvald Natvig
|
||||||
|
// Copyright (C) 2013 Oov
|
||||||
|
//
|
||||||
|
// Arbitrary resampling code
|
||||||
|
//
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// 1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
// this list of conditions and the following disclaimer.
|
||||||
|
//
|
||||||
|
// 2. Redistributions in binary form must reproduce the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer in the
|
||||||
|
// documentation and/or other materials provided with the distribution.
|
||||||
|
//
|
||||||
|
// 3. The name of the author may not be used to endorse or promote products
|
||||||
|
// derived from this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||||
|
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||||
|
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
|
||||||
|
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
|
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||||
|
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||||
|
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||||
|
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||||
|
// POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
package resample
|
||||||
|
|
||||||
|
type kaiserTable struct {
|
||||||
|
table []float64
|
||||||
|
oversample int
|
||||||
|
}
|
||||||
|
|
||||||
|
type quality struct {
|
||||||
|
baseLength int
|
||||||
|
oversample int
|
||||||
|
downsampleBandwidth float64
|
||||||
|
upsampleBandwidth float64
|
||||||
|
table *kaiserTable
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
kaiser12 = kaiserTable{
|
||||||
|
table: []float64{
|
||||||
|
0.99859849, 1.00000000, 0.99859849, 0.99440475, 0.98745105, 0.97779076,
|
||||||
|
0.96549770, 0.95066529, 0.93340547, 0.91384741, 0.89213598, 0.86843014,
|
||||||
|
0.84290116, 0.81573067, 0.78710866, 0.75723148, 0.72629970, 0.69451601,
|
||||||
|
0.66208321, 0.62920216, 0.59606986, 0.56287762, 0.52980938, 0.49704014,
|
||||||
|
0.46473455, 0.43304576, 0.40211431, 0.37206735, 0.34301800, 0.31506490,
|
||||||
|
0.28829195, 0.26276832, 0.23854851, 0.21567274, 0.19416736, 0.17404546,
|
||||||
|
0.15530766, 0.13794294, 0.12192957, 0.10723616, 0.09382272, 0.08164178,
|
||||||
|
0.07063950, 0.06075685, 0.05193064, 0.04409466, 0.03718069, 0.03111947,
|
||||||
|
0.02584161, 0.02127838, 0.01736250, 0.01402878, 0.01121463, 0.00886058,
|
||||||
|
0.00691064, 0.00531256, 0.00401805, 0.00298291, 0.00216702, 0.00153438,
|
||||||
|
0.00105297, 0.00069463, 0.00043489, 0.00025272, 0.00013031, 0.0000527734,
|
||||||
|
0.00001000, 0.00000000},
|
||||||
|
oversample: 64,
|
||||||
|
}
|
||||||
|
|
||||||
|
kaiser10 = kaiserTable{
|
||||||
|
table: []float64{
|
||||||
|
0.99537781, 1.00000000, 0.99537781, 0.98162644, 0.95908712, 0.92831446,
|
||||||
|
0.89005583, 0.84522401, 0.79486424, 0.74011713, 0.68217934, 0.62226347,
|
||||||
|
0.56155915, 0.50119680, 0.44221549, 0.38553619, 0.33194107, 0.28205962,
|
||||||
|
0.23636152, 0.19515633, 0.15859932, 0.12670280, 0.09935205, 0.07632451,
|
||||||
|
0.05731132, 0.04193980, 0.02979584, 0.02044510, 0.01345224, 0.00839739,
|
||||||
|
0.00488951, 0.00257636, 0.00115101, 0.00035515, 0.00000000, 0.00000000},
|
||||||
|
oversample: 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
kaiser8 = kaiserTable{
|
||||||
|
table: []float64{
|
||||||
|
0.99635258, 1.00000000, 0.99635258, 0.98548012, 0.96759014, 0.94302200,
|
||||||
|
0.91223751, 0.87580811, 0.83439927, 0.78875245, 0.73966538, 0.68797126,
|
||||||
|
0.63451750, 0.58014482, 0.52566725, 0.47185369, 0.41941150, 0.36897272,
|
||||||
|
0.32108304, 0.27619388, 0.23465776, 0.19672670, 0.16255380, 0.13219758,
|
||||||
|
0.10562887, 0.08273982, 0.06335451, 0.04724088, 0.03412321, 0.02369490,
|
||||||
|
0.01563093, 0.00959968, 0.00527363, 0.00233883, 0.00050000, 0.00000000},
|
||||||
|
oversample: 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
kaiser6 = kaiserTable{
|
||||||
|
table: []float64{
|
||||||
|
0.99733006, 1.00000000, 0.99733006, 0.98935595, 0.97618418, 0.95799003,
|
||||||
|
0.93501423, 0.90755855, 0.87598009, 0.84068475, 0.80211977, 0.76076565,
|
||||||
|
0.71712752, 0.67172623, 0.62508937, 0.57774224, 0.53019925, 0.48295561,
|
||||||
|
0.43647969, 0.39120616, 0.34752997, 0.30580127, 0.26632152, 0.22934058,
|
||||||
|
0.19505503, 0.16360756, 0.13508755, 0.10953262, 0.08693120, 0.06722600,
|
||||||
|
0.05031820, 0.03607231, 0.02432151, 0.01487334, 0.00752000, 0.00000000},
|
||||||
|
oversample: 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
qualityMap = []quality{
|
||||||
|
// Q0
|
||||||
|
quality{
|
||||||
|
baseLength: 8,
|
||||||
|
oversample: 4,
|
||||||
|
downsampleBandwidth: 0.830,
|
||||||
|
upsampleBandwidth: 0.860,
|
||||||
|
table: &kaiser6,
|
||||||
|
},
|
||||||
|
// Q1
|
||||||
|
quality{
|
||||||
|
baseLength: 16,
|
||||||
|
oversample: 4,
|
||||||
|
downsampleBandwidth: 0.850,
|
||||||
|
upsampleBandwidth: 0.880,
|
||||||
|
table: &kaiser6,
|
||||||
|
},
|
||||||
|
// Q2
|
||||||
|
quality{
|
||||||
|
baseLength: 32,
|
||||||
|
oversample: 4,
|
||||||
|
downsampleBandwidth: 0.882,
|
||||||
|
upsampleBandwidth: 0.910,
|
||||||
|
table: &kaiser6,
|
||||||
|
},
|
||||||
|
// Q3
|
||||||
|
quality{
|
||||||
|
baseLength: 48,
|
||||||
|
oversample: 8,
|
||||||
|
downsampleBandwidth: 0.895,
|
||||||
|
upsampleBandwidth: 0.917,
|
||||||
|
table: &kaiser8,
|
||||||
|
},
|
||||||
|
// Q4
|
||||||
|
quality{
|
||||||
|
baseLength: 64,
|
||||||
|
oversample: 8,
|
||||||
|
downsampleBandwidth: 0.921,
|
||||||
|
upsampleBandwidth: 0.940,
|
||||||
|
table: &kaiser8,
|
||||||
|
},
|
||||||
|
// Q5
|
||||||
|
quality{
|
||||||
|
baseLength: 80,
|
||||||
|
oversample: 16,
|
||||||
|
downsampleBandwidth: 0.922,
|
||||||
|
upsampleBandwidth: 0.940,
|
||||||
|
table: &kaiser10,
|
||||||
|
},
|
||||||
|
// Q6
|
||||||
|
quality{
|
||||||
|
baseLength: 96,
|
||||||
|
oversample: 16,
|
||||||
|
downsampleBandwidth: 0.940,
|
||||||
|
upsampleBandwidth: 0.945,
|
||||||
|
table: &kaiser10,
|
||||||
|
},
|
||||||
|
// Q7
|
||||||
|
quality{
|
||||||
|
baseLength: 128,
|
||||||
|
oversample: 16,
|
||||||
|
downsampleBandwidth: 0.950,
|
||||||
|
upsampleBandwidth: 0.950,
|
||||||
|
table: &kaiser10,
|
||||||
|
},
|
||||||
|
// Q8
|
||||||
|
quality{
|
||||||
|
baseLength: 160,
|
||||||
|
oversample: 16,
|
||||||
|
downsampleBandwidth: 0.960,
|
||||||
|
upsampleBandwidth: 0.960,
|
||||||
|
table: &kaiser10,
|
||||||
|
},
|
||||||
|
// Q9
|
||||||
|
quality{
|
||||||
|
baseLength: 192,
|
||||||
|
oversample: 32,
|
||||||
|
downsampleBandwidth: 0.968,
|
||||||
|
upsampleBandwidth: 0.968,
|
||||||
|
table: &kaiser12,
|
||||||
|
},
|
||||||
|
// Q10
|
||||||
|
quality{
|
||||||
|
baseLength: 256,
|
||||||
|
oversample: 32,
|
||||||
|
downsampleBandwidth: 0.975,
|
||||||
|
upsampleBandwidth: 0.975,
|
||||||
|
table: &kaiser12,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,544 @@
|
|||||||
|
// Copyright (C) 2007-2008 Jean-Marc Valin
|
||||||
|
// Copyright (C) 2008 Thorvald Natvig
|
||||||
|
// Copyright (C) 2013 Oov
|
||||||
|
//
|
||||||
|
// Arbitrary resampling code
|
||||||
|
//
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// 1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
// this list of conditions and the following disclaimer.
|
||||||
|
//
|
||||||
|
// 2. Redistributions in binary form must reproduce the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer in the
|
||||||
|
// documentation and/or other materials provided with the distribution.
|
||||||
|
//
|
||||||
|
// 3. The name of the author may not be used to endorse or promote products
|
||||||
|
// derived from this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||||
|
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||||
|
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
|
||||||
|
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
|
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||||
|
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||||
|
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||||
|
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||||
|
// POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
// Package resampler implements audio resampler.
|
||||||
|
//
|
||||||
|
// This is a port of the Opus-tools( http://git.xiph.org/?p=opus-tools.git ) audio resampler to the pure Go.
|
||||||
|
package resample
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
const bufferSize = 160
|
||||||
|
|
||||||
|
type channelState struct {
|
||||||
|
lastSample int
|
||||||
|
sampFracNum int
|
||||||
|
magicSamples int
|
||||||
|
mem []float64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Resampler struct {
|
||||||
|
numRate int
|
||||||
|
denRate int
|
||||||
|
|
||||||
|
quality *quality
|
||||||
|
filtLen int
|
||||||
|
intAdvance int
|
||||||
|
fracAdvance int
|
||||||
|
cutoff float64
|
||||||
|
oversample int
|
||||||
|
|
||||||
|
initialised bool
|
||||||
|
started bool
|
||||||
|
skipZeros bool
|
||||||
|
|
||||||
|
channels []channelState
|
||||||
|
sincTable []float64
|
||||||
|
resampler func(channelIndex int, in []float64, out []float64) int
|
||||||
|
}
|
||||||
|
|
||||||
|
func Resample64(in []float64, inSampleRate int, out []float64, outSampleRate int, quality int) (read int, written int) {
|
||||||
|
return NewWithSkipZeros(1, inSampleRate, outSampleRate, quality).ProcessFloat64(0, in, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Resample32(in []float32, inSampleRate int, out []float32, outSampleRate int, quality int) (read int, written int) {
|
||||||
|
return NewWithSkipZeros(1, inSampleRate, outSampleRate, quality).ProcessFloat32(0, in, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(channels int, inSampleRate, outSampleRate int, quality int) *Resampler {
|
||||||
|
if channels < 1 {
|
||||||
|
panic("you must have at least one channel")
|
||||||
|
}
|
||||||
|
r := &Resampler{
|
||||||
|
cutoff: 1.0,
|
||||||
|
channels: make([]channelState, channels),
|
||||||
|
}
|
||||||
|
|
||||||
|
r.setQuality(quality)
|
||||||
|
r.setSampleRate(inSampleRate, outSampleRate)
|
||||||
|
r.updateFilter()
|
||||||
|
r.initialised = true
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWithSkipZeros(channels int, inSampleRate, outSampleRate int, quality int) *Resampler {
|
||||||
|
r := New(channels, inSampleRate, outSampleRate, quality)
|
||||||
|
r.skipZeros = true
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// cannot change quality on running in now implementation.
|
||||||
|
func (r *Resampler) setQuality(q int) {
|
||||||
|
if q < 0 || q > 10 {
|
||||||
|
panic("invalid quality value")
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.quality == &qualityMap[q] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.quality = &qualityMap[q]
|
||||||
|
if r.initialised {
|
||||||
|
r.updateFilter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func imin(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
} else {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// cannot change sample on running in now implementation.
|
||||||
|
func (r *Resampler) setSampleRate(in int, out int) {
|
||||||
|
ratioNum := in
|
||||||
|
ratioDen := out
|
||||||
|
|
||||||
|
// FIXME: This is terribly inefficient, but who cares (at least for now)?
|
||||||
|
for fact := 2; fact <= imin(ratioNum, ratioDen); fact++ {
|
||||||
|
for (ratioNum%fact == 0) && (ratioDen%fact == 0) {
|
||||||
|
ratioNum /= fact
|
||||||
|
ratioDen /= fact
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.numRate == ratioNum && r.denRate == ratioDen {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.denRate > 0 {
|
||||||
|
for i := range r.channels {
|
||||||
|
ch := &r.channels[i]
|
||||||
|
ch.sampFracNum = ch.sampFracNum * ratioDen / r.denRate
|
||||||
|
// Safety net
|
||||||
|
if ch.sampFracNum >= ratioDen {
|
||||||
|
ch.sampFracNum = ratioDen - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r.numRate = ratioNum
|
||||||
|
r.denRate = ratioDen
|
||||||
|
|
||||||
|
if r.initialised {
|
||||||
|
r.updateFilter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) ProcessFloat64(channelIndex int, in []float64, out []float64) (read int, written int) {
|
||||||
|
if r.skipZeros {
|
||||||
|
for i := range r.channels {
|
||||||
|
r.channels[i].lastSample = r.InputLatency()
|
||||||
|
}
|
||||||
|
r.skipZeros = false
|
||||||
|
}
|
||||||
|
|
||||||
|
ch := &r.channels[channelIndex]
|
||||||
|
x := ch.mem
|
||||||
|
filtOffs := r.filtLen - 1
|
||||||
|
iLen, oLen, xLen := len(in), len(out), len(x)-filtOffs
|
||||||
|
read, written = iLen, oLen
|
||||||
|
|
||||||
|
if ch.magicSamples != 0 {
|
||||||
|
oLen -= r.magic(channelIndex, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ch.magicSamples == 0 {
|
||||||
|
for iLen != 0 && oLen != 0 {
|
||||||
|
ichunk, ochunk := imin(xLen, iLen), 0
|
||||||
|
if in != nil {
|
||||||
|
copy(x[filtOffs:], in[:ichunk])
|
||||||
|
} else {
|
||||||
|
for j := filtOffs; j < ichunk+filtOffs; j++ {
|
||||||
|
x[j] = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ichunk, ochunk = r.processNative(channelIndex, ichunk, out)
|
||||||
|
iLen -= ichunk
|
||||||
|
oLen -= ochunk
|
||||||
|
out = out[ochunk:]
|
||||||
|
if in != nil {
|
||||||
|
in = in[ichunk:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read -= iLen
|
||||||
|
written -= oLen
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) ProcessFloat32(channelIndex int, in []float32, out []float32) (read int, written int) {
|
||||||
|
const stackSize = 1024
|
||||||
|
var stack [stackSize]float64
|
||||||
|
|
||||||
|
if r.skipZeros {
|
||||||
|
for i := range r.channels {
|
||||||
|
r.channels[i].lastSample = r.InputLatency()
|
||||||
|
}
|
||||||
|
r.skipZeros = false
|
||||||
|
}
|
||||||
|
|
||||||
|
ch := &r.channels[channelIndex]
|
||||||
|
x := ch.mem
|
||||||
|
filtOffs := r.filtLen - 1
|
||||||
|
iLen, oLen := len(in), len(out)
|
||||||
|
xLen, yLen := len(x)-filtOffs, stackSize
|
||||||
|
read, written = iLen, oLen
|
||||||
|
|
||||||
|
if ch.magicSamples != 0 {
|
||||||
|
m := r.magic(channelIndex, stack[:imin(yLen, oLen)])
|
||||||
|
oLen -= m
|
||||||
|
for i, s := range stack[:m] {
|
||||||
|
out[i] = float32(s)
|
||||||
|
}
|
||||||
|
out = out[m:]
|
||||||
|
}
|
||||||
|
|
||||||
|
if ch.magicSamples == 0 {
|
||||||
|
for iLen != 0 && oLen != 0 {
|
||||||
|
ichunk, ochunk := imin(xLen, iLen), imin(yLen, oLen)
|
||||||
|
if in != nil {
|
||||||
|
for i, s := range in[:ichunk] {
|
||||||
|
x[filtOffs+i] = float64(s)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for j := filtOffs; j < ichunk+filtOffs; j++ {
|
||||||
|
x[j] = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ichunk, ochunk = r.processNative(channelIndex, ichunk, stack[:ochunk])
|
||||||
|
iLen -= ichunk
|
||||||
|
oLen -= ochunk
|
||||||
|
for i, s := range stack[:ochunk] {
|
||||||
|
out[i] = float32(s)
|
||||||
|
}
|
||||||
|
out = out[ochunk:]
|
||||||
|
if in != nil {
|
||||||
|
in = in[ichunk:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read -= iLen
|
||||||
|
written -= oLen
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) processNative(channelIndex int, inLen int, out []float64) (inLenRet int, outLenRet int) {
|
||||||
|
ch := &r.channels[channelIndex]
|
||||||
|
r.started = true
|
||||||
|
|
||||||
|
outLenRet = r.resampler(channelIndex, ch.mem[:inLen], out)
|
||||||
|
if ch.lastSample < inLen {
|
||||||
|
inLenRet = ch.lastSample
|
||||||
|
} else {
|
||||||
|
inLenRet = inLen
|
||||||
|
}
|
||||||
|
ch.lastSample -= inLenRet
|
||||||
|
copy(ch.mem, ch.mem[inLenRet:inLenRet+r.filtLen-1])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) magic(channelIndex int, out []float64) (outWritten int) {
|
||||||
|
ch := &r.channels[channelIndex]
|
||||||
|
n := r.filtLen - 1
|
||||||
|
|
||||||
|
inLen, outLen := r.processNative(channelIndex, ch.magicSamples, out)
|
||||||
|
|
||||||
|
ch.magicSamples -= inLen
|
||||||
|
|
||||||
|
// If we couldn't process all "magic" input samples, save the rest for next time
|
||||||
|
if ch.magicSamples != 0 {
|
||||||
|
copy(ch.mem[n:n+ch.magicSamples], ch.mem[n+inLen:])
|
||||||
|
}
|
||||||
|
return outLen
|
||||||
|
}
|
||||||
|
|
||||||
|
func computeFunc(x float64, windowFunc *kaiserTable) float64 {
|
||||||
|
y := x * float64(windowFunc.oversample)
|
||||||
|
ind := int(math.Floor(y))
|
||||||
|
frac := y - float64(ind)
|
||||||
|
fracx2 := frac * frac
|
||||||
|
fracx3 := fracx2 * frac
|
||||||
|
fracx2mul0_5 := 0.5 * fracx2
|
||||||
|
fracx3mul0_16 := 0.1666666667 * fracx3
|
||||||
|
// Compute interpolation coefficients. I'm not sure whether this corresponds to cubic interpolation but I know it's MMSE-optimal on a sinc
|
||||||
|
i3 := -0.1666666667*frac + fracx3mul0_16
|
||||||
|
i2 := frac + fracx2mul0_5 - 0.5*fracx3
|
||||||
|
// interp[2] = 1.f - 0.5f*frac - frac*frac + 0.5f*frac*frac*frac;
|
||||||
|
i0 := -0.3333333333*frac + fracx2mul0_5 - fracx3mul0_16
|
||||||
|
// Just to make sure we don't have rounding problems
|
||||||
|
i1 := 1.0 - i3 - i2 - i0
|
||||||
|
return i0*windowFunc.table[ind] + i1*windowFunc.table[ind+1] + i2*windowFunc.table[ind+2] + i3*windowFunc.table[ind+3]
|
||||||
|
}
|
||||||
|
|
||||||
|
// The slow way of computing a sinc for the table. Should improve that some day
|
||||||
|
func sinc(cutoff float64, x float64, n float64, windowFunc *kaiserTable) float64 {
|
||||||
|
xabs := math.Abs(x)
|
||||||
|
if xabs < 1e-6 {
|
||||||
|
return cutoff
|
||||||
|
} else if xabs > 0.5*n {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
// FIXME: Can it really be any slower than this?
|
||||||
|
xx := x * cutoff * math.Pi
|
||||||
|
return cutoff * math.Sin(xx) / xx * computeFunc(2.0*xabs/n, windowFunc)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) resamplerBasicDirect(channelIndex int, in []float64, out []float64) int {
|
||||||
|
ch := &r.channels[channelIndex]
|
||||||
|
n := r.filtLen
|
||||||
|
outSample := 0
|
||||||
|
lastSample := ch.lastSample
|
||||||
|
sampFracNum := ch.sampFracNum
|
||||||
|
sincTable := r.sincTable
|
||||||
|
intAdvance := r.intAdvance
|
||||||
|
fracAdvance := r.fracAdvance
|
||||||
|
denRate := r.denRate
|
||||||
|
|
||||||
|
for lastSample < len(in) && outSample < len(out) {
|
||||||
|
sinct := sincTable[sampFracNum*n : sampFracNum*n+n]
|
||||||
|
var sum float64
|
||||||
|
for j, s := range in[lastSample : lastSample+n] {
|
||||||
|
sum += sinct[j] * s
|
||||||
|
}
|
||||||
|
|
||||||
|
out[outSample] = sum
|
||||||
|
outSample++
|
||||||
|
lastSample += intAdvance
|
||||||
|
sampFracNum += fracAdvance
|
||||||
|
if sampFracNum >= denRate {
|
||||||
|
sampFracNum -= denRate
|
||||||
|
lastSample++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ch.lastSample = lastSample
|
||||||
|
ch.sampFracNum = sampFracNum
|
||||||
|
return outSample
|
||||||
|
}
|
||||||
|
|
||||||
|
func cubicCoef(frac float64) (float64, float64, float64, float64) {
|
||||||
|
fracx2 := frac * frac
|
||||||
|
fracx3 := fracx2 * frac
|
||||||
|
fracx2mul0_5 := 0.5 * fracx2
|
||||||
|
fracx3mul0_16 := 0.1666666667 * fracx3
|
||||||
|
// Compute interpolation coefficients. I'm not sure whether this corresponds to cubic interpolation but I know it's MMSE-optimal on a sinc
|
||||||
|
i0 := -0.1666666667*frac + fracx3mul0_16
|
||||||
|
i1 := frac + fracx2mul0_5 - 0.5*fracx3
|
||||||
|
// interp[2] = 1.f - 0.5f*frac - frac*frac + 0.5f*frac*frac*frac;
|
||||||
|
i3 := -0.3333333333*frac + fracx2mul0_5 - fracx3mul0_16
|
||||||
|
// Just to make sure we don't have rounding problems
|
||||||
|
i2 := 1.0 - i0 - i1 - i3
|
||||||
|
return i0, i1, i2, i3
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) resamplerBasicInterpolate(channelIndex int, in []float64, out []float64) int {
|
||||||
|
ch := &r.channels[channelIndex]
|
||||||
|
n := r.filtLen
|
||||||
|
outSample := 0
|
||||||
|
lastSample := ch.lastSample
|
||||||
|
sampFracNum := ch.sampFracNum
|
||||||
|
intAdvance := r.intAdvance
|
||||||
|
fracAdvance := r.fracAdvance
|
||||||
|
denRate := r.denRate
|
||||||
|
|
||||||
|
for lastSample < len(in) && outSample < len(out) {
|
||||||
|
offset := sampFracNum * r.oversample / r.denRate
|
||||||
|
frac := float64((sampFracNum*r.oversample)%r.denRate) / float64(r.denRate)
|
||||||
|
var accum0, accum1, accum2, accum3 float64
|
||||||
|
for j, s := range in[lastSample : lastSample+n] {
|
||||||
|
t := 4 + (j+1)*r.oversample - offset
|
||||||
|
accum0 += s * r.sincTable[t-2]
|
||||||
|
accum1 += s * r.sincTable[t-1]
|
||||||
|
accum2 += s * r.sincTable[t]
|
||||||
|
accum3 += s * r.sincTable[t+1]
|
||||||
|
}
|
||||||
|
i0, i1, i2, i3 := cubicCoef(frac)
|
||||||
|
out[outSample] = i0*accum0 + i1*accum1 + i2*accum2 + i3*accum3
|
||||||
|
outSample++
|
||||||
|
lastSample += intAdvance
|
||||||
|
sampFracNum += fracAdvance
|
||||||
|
if sampFracNum >= denRate {
|
||||||
|
sampFracNum -= denRate
|
||||||
|
lastSample++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ch.lastSample = lastSample
|
||||||
|
ch.sampFracNum = sampFracNum
|
||||||
|
return outSample
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) updateFilter() {
|
||||||
|
oldLength := r.filtLen
|
||||||
|
r.oversample = r.quality.oversample
|
||||||
|
r.filtLen = r.quality.baseLength
|
||||||
|
|
||||||
|
if r.numRate > r.denRate {
|
||||||
|
// down-sampling
|
||||||
|
r.cutoff = r.quality.downsampleBandwidth * float64(r.denRate) / float64(r.numRate)
|
||||||
|
// FIXME: divide the numerator and denominator by a certain amount if they're too large
|
||||||
|
r.filtLen = r.filtLen * r.numRate / r.denRate
|
||||||
|
// Round up to make sure we have a multiple of 8
|
||||||
|
r.filtLen = ((r.filtLen - 1) & (^int(0x7))) + 8
|
||||||
|
if r.denRate<<1 < r.numRate {
|
||||||
|
r.oversample >>= 1
|
||||||
|
}
|
||||||
|
if r.denRate<<2 < r.numRate {
|
||||||
|
r.oversample >>= 1
|
||||||
|
}
|
||||||
|
if r.denRate<<3 < r.numRate {
|
||||||
|
r.oversample >>= 1
|
||||||
|
}
|
||||||
|
if r.denRate<<4 < r.numRate {
|
||||||
|
r.oversample >>= 1
|
||||||
|
}
|
||||||
|
if r.oversample < 1 {
|
||||||
|
r.oversample = 1
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// up-sampling
|
||||||
|
r.cutoff = r.quality.upsampleBandwidth
|
||||||
|
}
|
||||||
|
|
||||||
|
// Choose the resampling type that requires the least amount of memory
|
||||||
|
if r.denRate <= 16*(r.oversample+8) {
|
||||||
|
if r.sincTable == nil || len(r.sincTable) < r.filtLen*r.denRate {
|
||||||
|
r.sincTable = make([]float64, r.filtLen*r.denRate)
|
||||||
|
}
|
||||||
|
for i := 0; i < r.denRate; i++ {
|
||||||
|
for j := 0; j < r.filtLen; j++ {
|
||||||
|
r.sincTable[i*r.filtLen+j] = sinc(
|
||||||
|
r.cutoff,
|
||||||
|
float64(j-(r.filtLen>>1)+1)-float64(i)/float64(r.denRate),
|
||||||
|
float64(r.filtLen),
|
||||||
|
r.quality.table,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.resampler = r.resamplerBasicDirect
|
||||||
|
} else {
|
||||||
|
if r.sincTable == nil || len(r.sincTable) < r.filtLen*r.oversample+8 {
|
||||||
|
r.sincTable = make([]float64, r.filtLen*r.oversample+8)
|
||||||
|
}
|
||||||
|
for i := -4; i < r.oversample*r.filtLen+4; i++ {
|
||||||
|
r.sincTable[i+4] = sinc(
|
||||||
|
r.cutoff,
|
||||||
|
float64(i)/float64(r.oversample)-float64(r.filtLen>>1),
|
||||||
|
float64(r.filtLen),
|
||||||
|
r.quality.table,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
r.resampler = r.resamplerBasicInterpolate
|
||||||
|
}
|
||||||
|
|
||||||
|
r.intAdvance = r.numRate / r.denRate
|
||||||
|
r.fracAdvance = r.numRate % r.denRate
|
||||||
|
|
||||||
|
// Here's the place where we update the filter memory to take into account
|
||||||
|
// the change in filter length. It's probably the messiest part of the code
|
||||||
|
// due to handling of lots of corner cases.
|
||||||
|
switch {
|
||||||
|
case r.channels[0].mem == nil || !r.started:
|
||||||
|
size := r.filtLen - 1 + bufferSize
|
||||||
|
for i := range r.channels {
|
||||||
|
r.channels[i].mem = make([]float64, size)
|
||||||
|
}
|
||||||
|
case r.filtLen > oldLength:
|
||||||
|
panic("not implemented")
|
||||||
|
// Increase the filter length
|
||||||
|
// oldAllocSize := len(r.mem) / len(r.channels)
|
||||||
|
// if r.filtLen-1+r.bufferSize > oldAllocSize {
|
||||||
|
// m := make([]float64, (r.filtLen-1+r.bufferSize)*len(r.channels))
|
||||||
|
// copy(m, r.mem)
|
||||||
|
// r.mem = m
|
||||||
|
// }
|
||||||
|
for i := len(r.channels) - 1; i >= 0; i-- {
|
||||||
|
// spx_int32_t j;
|
||||||
|
// spx_uint32_t olen = old_length;
|
||||||
|
// /*if (st->magic_samples[i])*/
|
||||||
|
// {
|
||||||
|
// /* Try and remove the magic samples as if nothing had happened */
|
||||||
|
//
|
||||||
|
// /* FIXME: This is wrong but for now we need it to avoid going over the array bounds */
|
||||||
|
// olen = old_length + 2*st->magic_samples[i];
|
||||||
|
// for (j=old_length-2+st->magic_samples[i];j>=0;j--)
|
||||||
|
// st->mem[i*st->mem_alloc_size+j+st->magic_samples[i]] = st->mem[i*old_alloc_size+j];
|
||||||
|
// for (j=0;j<st->magic_samples[i];j++)
|
||||||
|
// st->mem[i*st->mem_alloc_size+j] = 0;
|
||||||
|
// st->magic_samples[i] = 0;
|
||||||
|
// }
|
||||||
|
// if (st->filt_len > olen)
|
||||||
|
// {
|
||||||
|
// /* If the new filter length is still bigger than the "augmented" length */
|
||||||
|
// /* Copy data going backward */
|
||||||
|
// for (j=0;j<olen-1;j++)
|
||||||
|
// st->mem[i*st->mem_alloc_size+(st->filt_len-2-j)] = st->mem[i*st->mem_alloc_size+(olen-2-j)];
|
||||||
|
// /* Then put zeros for lack of anything better */
|
||||||
|
// for (;j<st->filt_len-1;j++)
|
||||||
|
// st->mem[i*st->mem_alloc_size+(st->filt_len-2-j)] = 0;
|
||||||
|
// /* Adjust last_sample */
|
||||||
|
// st->last_sample[i] += (st->filt_len - olen)/2;
|
||||||
|
// } else {
|
||||||
|
// /* Put back some of the magic! */
|
||||||
|
// st->magic_samples[i] = (olen - st->filt_len)/2;
|
||||||
|
// for (j=0;j<st->filt_len-1+st->magic_samples[i];j++)
|
||||||
|
// st->mem[i*st->mem_alloc_size+j] = st->mem[i*st->mem_alloc_size+j+st->magic_samples[i]];
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
case r.filtLen < oldLength:
|
||||||
|
panic("not implemented")
|
||||||
|
// spx_uint32_t i;
|
||||||
|
// /* Reduce filter length, this a bit tricky. We need to store some of the memory as "magic"
|
||||||
|
// samples so they can be used directly as input the next time(s) */
|
||||||
|
// for (i=0;i<st->nb_channels;i++)
|
||||||
|
// {
|
||||||
|
// spx_uint32_t j;
|
||||||
|
// spx_uint32_t old_magic = st->magic_samples[i];
|
||||||
|
// st->magic_samples[i] = (old_length - st->filt_len)/2;
|
||||||
|
// /* We must copy some of the memory that's no longer used */
|
||||||
|
// /* Copy data going backward */
|
||||||
|
// for (j=0;j<st->filt_len-1+st->magic_samples[i]+old_magic;j++)
|
||||||
|
// st->mem[i*st->mem_alloc_size+j] = st->mem[i*st->mem_alloc_size+j+st->magic_samples[i]];
|
||||||
|
// st->magic_samples[i] += old_magic;
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) InputLatency() int {
|
||||||
|
return r.filtLen >> 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resampler) OutputLatency() int {
|
||||||
|
return ((r.filtLen>>1)*r.denRate + (r.numRate >> 1)) / r.numRate
|
||||||
|
}
|
||||||