matemat/uncanny/display.go
2021-05-05 22:34:25 +02:00

53 lines
1.3 KiB
Go

package uncanny
import (
"errors"
"fmt"
"golang.org/x/text/encoding/charmap"
)
// 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")
}
// print in 3 chunks, as one frame is limited to 8 bytes
// the display has only 16 characters per line, so we truncate there
if len(a) > 0 {
return c.bus.Publish(DisplayCommand{addr, a[:7]}.Encode())
}
if len(a) > 7 {
return c.bus.Publish(DisplayCommand{addr, a[7:14]}.Encode())
}
if len(a) > 14 {
return c.bus.Publish(DisplayCommand{addr, a[14:16]}.Encode())
}
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)
}