matemat/uncanny/display.go

66 lines
1.4 KiB
Go
Raw Normal View History

2021-05-05 22:34:25 +02:00
package uncanny
import (
"errors"
"fmt"
"golang.org/x/text/encoding/charmap"
)
2021-05-05 23:35:49 +02:00
// min returns the smaller of two integers {
func min(x, y int) int {
if x < y {
return x
}
return y
}
// max returns the larger of two integers {
func max(x, y int) int {
if x > y {
return x
}
return y
}
2021-05-05 22:34:25 +02:00
// encodeString encodes a Unicode string into a given charmap.
// Unsupported characters are replaced by the default replacement symbol.
// Mysteriously, this functionality is missing from x/text/encoding.
// TODO Implement the custom NEC display encoding.
func encodeString(s string) ([]byte) {
ret := make([]byte, len(s))
for i, c := range(s) {
ret[i], _ = charmap.ISO8859_1.EncodeRune(c)
}
return ret
}
func (c *Can) DisplayWrite(line int, a []byte) error {
var addr int
switch line {
case 0:
addr = 0x80
case 1:
addr = 0xc0
default:
return errors.New("Invalid line")
}
2021-05-05 23:13:02 +02:00
// print in separate chunks, as one frame payload is limited to 7 bytes
2021-05-05 22:34:25 +02:00
// the display has only 16 characters per line, so we truncate there
2021-05-05 23:35:49 +02:00
for i := 0; i < min(len(a), 16); i += 7 {
2021-05-05 23:39:27 +02:00
err := c.bus.Publish(DisplayCommand{addr + i, a[i:min(i+7,len(a))]}.Encode())
2021-05-05 23:21:02 +02:00
if err != nil {
return err
}
2021-05-05 22:34:25 +02:00
}
return nil
}
func (c *Can) DisplayPrint(line int, a string) error {
return c.DisplayWrite(line, encodeString(a))
}
func (c *Can) DisplayPrintf(line int, a string, args ...interface{}) error {
s := fmt.Sprintf(a, args...)
return c.DisplayPrint(line, s)
}