diff options
Diffstat (limited to 'liust-50/cmd')
-rw-r--r-- | liust-50/cmd/liustatus/status.go | 208 | ||||
-rw-r--r-- | liust-50/cmd/liustatus/weather.go | 132 | ||||
-rw-r--r-- | liust-50/cmd/liustsim/simulator.go | 325 |
3 files changed, 665 insertions, 0 deletions
diff --git a/liust-50/cmd/liustatus/status.go b/liust-50/cmd/liustatus/status.go new file mode 100644 index 0000000..2c41e71 --- /dev/null +++ b/liust-50/cmd/liustatus/status.go @@ -0,0 +1,208 @@ +package main + +import ( + "fmt" + "os" + "strings" + "time" + + "janouch.name/desktop-tools/liust-50/charset" +) + +// TODO(p): Make more elaberate animations with these. +var kaomoji = []struct { + kao, message string +}{ + {"(o_o)", ""}, + {"(゚ロ゚)", ""}, + {"(゚∩゚)", ""}, + {"(^_^)", ""}, + {" (^_^)", ""}, + {"(^_^) ", ""}, + {"(x_x)", "ズキズキ"}, + {"(T_T)", "ズーン"}, + {"=^.^=", "ニャー"}, + {"(>_<)", "ゲップ"}, + {"(O_O)", "ジー"}, + {"(-_-)", ""}, + {"(-_-)", "グーグー"}, + {"(o_-)", ""}, + {"(-_o)", ""}, +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +const ( + displayWidth = 20 + displayHeight = 2 + targetCharset = 0x63 +) + +type DisplayState struct { + Display [displayHeight][displayWidth]uint8 +} + +type Display struct { + Current, Last DisplayState +} + +func NewDisplay() *Display { + t := &Display{} + for y := 0; y < displayHeight; y++ { + for x := 0; x < displayWidth; x++ { + t.Current.Display[y][x] = ' ' + t.Last.Display[y][x] = ' ' + } + } + return t +} + +func (t *Display) SetLine(row int, content string) { + if row < 0 || row >= displayHeight { + return + } + + runes := []rune(content) + for x := 0; x < displayWidth; x++ { + if x < len(runes) { + b, ok := charset.ResolveRune(runes[x], targetCharset) + if ok { + t.Current.Display[row][x] = b + } else { + t.Current.Display[row][x] = '?' + } + } else { + t.Current.Display[row][x] = ' ' + } + } +} + +func (t *Display) HasChanges() bool { + for y := 0; y < displayHeight; y++ { + for x := 0; x < displayWidth; x++ { + if t.Current.Display[y][x] != t.Last.Display[y][x] { + return true + } + } + } + return false +} + +func (t *Display) Update() { + for y := 0; y < displayHeight; y++ { + x := 0 + for x < displayWidth { + if t.Current.Display[y][x] == t.Last.Display[y][x] { + x++ + continue + } + + startX := x + var changes strings.Builder + for x < displayWidth && + t.Current.Display[y][x] != t.Last.Display[y][x] { + changes.WriteByte(t.Current.Display[y][x]) + t.Last.Display[y][x] = t.Current.Display[y][x] + x++ + } + + fmt.Printf("\x1b[%d;%dH%s", y+1, startX+1, changes.String()) + } + } + + os.Stdout.Sync() +} + +func centerText(text string, width int) string { + textLen := len([]rune(text)) + if textLen >= width { + return text[:width] + } + leftPad := (width - textLen + 1) / 2 + rightPad := width - textLen - leftPad + return strings.Repeat(" ", leftPad) + text + strings.Repeat(" ", rightPad) +} + +func kaomojiProducer(lines chan<- string) { + ticker := time.NewTicker(30_000 * time.Millisecond) + defer ticker.Stop() + + idx := 0 + for { + km := kaomoji[idx] + + line := centerText(km.kao, displayWidth) + if km.message != "" { + line = line[:14] + km.message + line += strings.Repeat(" ", displayWidth-len([]rune(line))) + } + + lines <- line + + idx = (idx + 1) % len(kaomoji) + <-ticker.C + } +} + +func statusProducer(lines chan<- string) { + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + + temperature, fetcher := "", NewWeatherFetcher() + temperatureChan := make(chan string) + go fetcher.Run(5*time.Minute, temperatureChan) + + for { + select { + case newTemperature := <-temperatureChan: + temperature = newTemperature + default: + } + + now := time.Now() + status := fmt.Sprintf("%s %3s %s", + now.Format("Mon 2 Jan"), temperature, now.Format("15:04")) + + // Ensure exactly 20 characters. + runes := []rune(status) + if len(runes) > displayWidth { + status = string(runes[:displayWidth]) + } else if len(runes) < displayWidth { + status = status + strings.Repeat(" ", displayWidth-len(runes)) + } + + lines <- status + <-ticker.C + } +} + +func main() { + terminal := NewDisplay() + + kaomojiChan := make(chan string, 1) + statusChan := make(chan string, 1) + + go kaomojiProducer(kaomojiChan) + go statusProducer(statusChan) + + // TODO(p): And we might want to disable cursor visibility as well. + fmt.Printf("\x1bR%c", targetCharset) + fmt.Print("\x1b[2J") // Clear display + + go func() { + kaomojiChan <- centerText(kaomoji[0].kao, displayWidth) + statusChan <- strings.Repeat(" ", displayWidth) + }() + + for { + select { + case line := <-kaomojiChan: + terminal.SetLine(0, line) + case line := <-statusChan: + terminal.SetLine(1, line) + } + if terminal.HasChanges() { + terminal.Update() + } + } +} diff --git a/liust-50/cmd/liustatus/weather.go b/liust-50/cmd/liustatus/weather.go new file mode 100644 index 0000000..c744f2f --- /dev/null +++ b/liust-50/cmd/liustatus/weather.go @@ -0,0 +1,132 @@ +package main + +import ( + "encoding/xml" + "fmt" + "io" + "log" + "net/http" + "strconv" + "time" +) + +const ( + baseURL = "https://api.met.no/weatherapi" + userAgent = "liustatus/1.0" + + // Prague coordinates. + lat = 50.08804 + lon = 14.42076 + altitude = 202 +) + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +type Weatherdata struct { + XMLName xml.Name `xml:"weatherdata"` + Product Product `xml:"product"` +} + +type Product struct { + Times []Time `xml:"time"` +} + +type Time struct { + From string `xml:"from,attr"` + To string `xml:"to,attr"` + Location Location `xml:"location"` +} + +type Location struct { + Temperature *Temperature `xml:"temperature"` +} + +type Temperature struct { + Unit string `xml:"unit,attr"` + Value string `xml:"value,attr"` +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// WeatherFetcher handles weather data retrieval. +type WeatherFetcher struct { + client *http.Client +} + +// NewWeatherFetcher creates a new weather fetcher instance. +func NewWeatherFetcher() *WeatherFetcher { + return &WeatherFetcher{ + client: &http.Client{Timeout: 30 * time.Second}, + } +} + +// fetchWeather retrieves the current temperature from the API. +func (w *WeatherFetcher) fetchWeather() (string, error) { + url := fmt.Sprintf( + "%s/locationforecast/2.0/classic?lat=%.5f&lon=%.5f&altitude=%d", + baseURL, lat, lon, altitude) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return "", err + } + + req.Header.Set("User-Agent", userAgent) + + resp, err := w.client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("API returned status %d", resp.StatusCode) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + + var weatherData Weatherdata + if err := xml.Unmarshal(body, &weatherData); err != nil { + return "", err + } + + now := time.Now().UTC() + for _, t := range weatherData.Product.Times { + toTime, err := time.Parse("2006-01-02T15:04:05Z", t.To) + if err != nil || toTime.Before(now) { + continue + } + if t.Location.Temperature != nil { + temp, err := strconv.ParseFloat(t.Location.Temperature.Value, 64) + if err != nil { + continue + } + return fmt.Sprintf("%d゚", int(temp)), nil + } + } + + return "", fmt.Errorf("no usable temperature data found") +} + +// update fetches new weather data and returns it. +func (w *WeatherFetcher) update() string { + temp, err := w.fetchWeather() + if err != nil { + log.Printf("Error fetching weather: %v", err) + } + return temp +} + +// Run runs as a goroutine to periodically fetch weather data. +func (w *WeatherFetcher) Run(interval time.Duration, output chan<- string) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + + output <- w.update() + for range ticker.C { + output <- w.update() + } +} diff --git a/liust-50/cmd/liustsim/simulator.go b/liust-50/cmd/liustsim/simulator.go new file mode 100644 index 0000000..43e06d9 --- /dev/null +++ b/liust-50/cmd/liustsim/simulator.go @@ -0,0 +1,325 @@ +package main + +import ( + "bufio" + "image" + "image/color" + "os" + "strconv" + "strings" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/app" + "fyne.io/fyne/v2/canvas" + + "janouch.name/desktop-tools/liust-50/charset" +) + +const ( + displayWidth = 20 + displayHeight = 2 + charWidth = 5 + 1 + charHeight = 7 + 1 + magnification = 5 +) + +// TODO(p): See how this works exactly, and implement it. +const ( + cursorModeOff = iota + cursorModeBlink + cursorModeLightUp +) + +type Display struct { + image *canvas.Image + chars [displayHeight][displayWidth]uint8 + charset uint8 + cursorX int + cursorY int + cursorMode int +} + +func NewDisplay() *Display { + return &Display{charset: 2} +} + +func (d *Display) Clear() { + for y := 0; y < displayHeight; y++ { + for x := 0; x < displayWidth; x++ { + d.chars[y][x] = 0x20 // space + } + } +} + +func (d *Display) ClearToEnd() { + for x := d.cursorX; x < displayWidth; x++ { + d.chars[d.cursorY][x] = 0x20 // space + } +} + +func (d *Display) drawCharacter( + img *image.RGBA, charImg image.Image, cx, cy int) { + if charImg == nil { + return + } + + bounds := charImg.Bounds() + width, height := bounds.Dx(), bounds.Dy() + for dy := 0; dy < height; dy++ { + for dx := 0; dx < width; dx++ { + c := charImg.At(bounds.Min.X+dx, bounds.Min.Y+dy) + if r, _, _, _ := c.RGBA(); r >= 0x8000 { + c = color.RGBA{0x00, 0xFF, 0xA0, 0xFF} + } else { + c = color.RGBA{0x20, 0x20, 0x20, 0xFF} + } + img.Set(1+cx*charWidth+dx, 1+cy*charHeight+dy, c) + } + } +} + +func (d *Display) Render() image.Image { + width := 1 + displayWidth*charWidth + height := 1 + displayHeight*charHeight + + img := image.NewRGBA(image.Rect(0, 0, width, height)) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + img.Set(x, y, color.Black) + } + } + + for cy := 0; cy < displayHeight; cy++ { + for cx := 0; cx < displayWidth; cx++ { + charImg := charset.ResolveCharToImage(d.chars[cy][cx], d.charset) + d.drawCharacter(img, charImg, cx, cy) + } + } + + return img +} + +func (d *Display) PutChar(ch uint8) { + if d.cursorX >= displayWidth || d.cursorY >= displayHeight { + return + } + + d.chars[d.cursorY][d.cursorX] = ch + d.cursorX++ + if d.cursorX >= displayWidth { + d.cursorX = displayWidth - 1 + } +} + +func (d *Display) LineFeed() { + d.cursorY++ + if d.cursorY >= displayHeight { + d.cursorY = displayHeight - 1 + + // XXX: This relies on displayHeight being exactly 2. + d.chars[0] = d.chars[1] + for x := 0; x < displayWidth; x++ { + d.chars[1][x] = 0x20 + } + } +} + +func (d *Display) CarriageReturn() { + d.cursorX = 0 +} + +func (d *Display) Backspace() { + if d.cursorX > 0 { + d.cursorX-- + } +} + +func (d *Display) SetCursor(x, y int) { + if x >= 0 && x < displayWidth { + d.cursorX = x + } + if y >= 0 && y < displayHeight { + d.cursorY = y + } +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func parseANSI(input string) (command string, params []int) { + if !strings.HasPrefix(input, "\x1b[") { + return "", nil + } + + input = input[2:] + if len(input) == 0 { + return "", nil + } + + cmdIdx := len(input) - 1 + command = string(input[cmdIdx]) + + paramStr := input[:cmdIdx] + if paramStr == "" { + return command, []int{} + } + + parts := strings.Split(paramStr, ";") + for _, p := range parts { + p = strings.TrimSpace(p) + if val, err := strconv.Atoi(p); err == nil { + params = append(params, val) + } + } + return command, params +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +type escapeParser struct { + seq strings.Builder + inEsc bool + inCSI bool + display *Display +} + +func newEscapeParser(d *Display) *escapeParser { + return &escapeParser{display: d} +} + +func (ep *escapeParser) reset() { + ep.inEsc = false + ep.inCSI = false + ep.seq.Reset() +} + +func (ep *escapeParser) handleCSICommand() bool { + cmd, params := parseANSI(ep.seq.String()) + + switch cmd { + case "J": // Clear display + // XXX: No params case is unverified. + if len(params) == 0 || params[0] == 2 { + ep.display.Clear() + } + case "K": // Delete to end of line + // XXX: No params case is unverified (but it should work). + if len(params) == 0 || params[0] == 0 { + ep.display.ClearToEnd() + } + case "H": // Cursor position + y, x := 0, 0 + if len(params) >= 1 { + y = params[0] - 1 // 1-indexed to 0-indexed + } + if len(params) >= 2 { + x = params[1] - 1 + } + ep.display.SetCursor(x, y) + } + return true +} + +func (ep *escapeParser) handleEscapeSequence(b byte) bool { + ep.seq.WriteByte(b) + + if ep.seq.Len() == 2 && b == '[' { + ep.inCSI = true + return false + } + + if ep.seq.Len() == 3 && ep.seq.String()[1] == 'R' { + ep.display.charset = b + ep.reset() + return true + } + + if ep.inCSI && (b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z') { + refresh := ep.handleCSICommand() + ep.reset() + return refresh + } + + if ep.seq.Len() == 6 && ep.seq.String()[1:5] == "\\?LC" { + ep.display.cursorMode = int(ep.seq.String()[5]) + return true + } + + return false +} + +func (ep *escapeParser) handleControlChar(b byte) bool { + switch b { + case 0x0A: // LF + ep.display.LineFeed() + return true + case 0x0D: // CR + ep.display.CarriageReturn() + return true + case 0x08: // BS + ep.display.Backspace() + return true + default: + if b >= 0x20 { + ep.display.PutChar(b) + return true + } + } + return false +} + +func (ep *escapeParser) handleByte(b byte) (needsRefresh bool) { + if b == 0x1b { // ESC + ep.reset() + ep.inEsc = true + ep.seq.WriteByte(b) + return false + } + + if ep.inEsc { + return ep.handleEscapeSequence(b) + } + + return ep.handleControlChar(b) +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func main() { + myApp := app.New() + window := myApp.NewWindow("Toshiba Tec LIUST-50 Simulator") + + display := NewDisplay() + display.Clear() + + img := canvas.NewImageFromImage(display.Render()) + img.FillMode = canvas.ImageFillOriginal + img.ScaleMode = canvas.ImageScalePixels + + window.SetContent(img) + + window.Resize(fyne.NewSize(600, 100)) + + go func() { + reader := bufio.NewReader(os.Stdin) + parser := newEscapeParser(display) + + for { + b, err := reader.ReadByte() + if err != nil { + fyne.DoAndWait(func() { + window.SetTitle(err.Error()) + }) + return + } + + if parser.handleByte(b) { + fyne.DoAndWait(func() { + img.Image = display.Render() + img.Refresh() + }) + } + } + }() + + window.ShowAndRun() +} |