generated from rmcguire/go-server-with-otel
add ui, new config opts
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
package econetui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
pb "gitea.libretechconsulting.com/rmcguire/econet-exporter/api/econet/v1alpha1"
|
||||
"gitea.libretechconsulting.com/rmcguire/econet-exporter/pkg/econet/econetgrpc"
|
||||
)
|
||||
|
||||
// cardView is the template model for one device card.
|
||||
type cardView struct {
|
||||
Device *pb.Device
|
||||
Icon string // static asset path for the device type
|
||||
Modes []modeOption // settable modes for the dropdown
|
||||
Pending string // pretty label of an in-flight mode change, if any
|
||||
Error string // last mode-change error, if any
|
||||
}
|
||||
|
||||
type modeOption struct {
|
||||
Value string // proto enum name, e.g. MODE_HEAT_PUMP
|
||||
Label string // display label, e.g. Heat Pump
|
||||
Selected bool
|
||||
}
|
||||
|
||||
type pageView struct {
|
||||
Devices []cardView
|
||||
}
|
||||
|
||||
func (s *EconetUIServer) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
// A full page load is a "fresh get": show reported state, ignore pending.
|
||||
s.render(w, "layout", pageView{Devices: s.deviceViews(r.Context(), false)})
|
||||
}
|
||||
|
||||
func (s *EconetUIServer) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
// The polling refresh honors pending so an in-flight change stays visible
|
||||
// until it lands or its TTL lapses.
|
||||
s.render(w, "devices", pageView{Devices: s.deviceViews(r.Context(), true)})
|
||||
}
|
||||
|
||||
func (s *EconetUIServer) handleSetMode(w http.ResponseWriter, r *http.Request) {
|
||||
serial := r.PathValue("serial")
|
||||
modeName := r.FormValue("mode")
|
||||
|
||||
modeVal, ok := pb.Mode_value[modeName]
|
||||
if !ok || pb.Mode(modeVal) == pb.Mode_MODE_UNSPECIFIED {
|
||||
s.renderCard(w, r.Context(), serial, "invalid mode "+modeName)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := s.econetGRPC.SetMode(r.Context(), &pb.SetModeRequest{
|
||||
SerialNumber: serial,
|
||||
Mode: pb.Mode(modeVal),
|
||||
})
|
||||
if err != nil {
|
||||
s.log.Warn().Err(err).Str("serial", serial).Msg("ui: set mode failed")
|
||||
s.renderCard(w, r.Context(), serial, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.pending.set(serial, econetgrpc.ModeSlug(pb.Mode(modeVal)))
|
||||
s.renderCard(w, r.Context(), serial, "")
|
||||
}
|
||||
|
||||
// handleDebug returns the raw EcoNet payload for a device, pretty-printed, for
|
||||
// the bug-icon modal.
|
||||
func (s *EconetUIServer) handleDebug(w http.ResponseWriter, r *http.Request) {
|
||||
serial := r.PathValue("serial")
|
||||
raw, ok := s.econetGRPC.DeviceRawJSON(serial)
|
||||
if !ok {
|
||||
s.render(w, "debug", "No raw payload captured for "+serial+" yet.")
|
||||
return
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := json.Indent(&buf, raw, "", " "); err != nil {
|
||||
buf.Write(raw)
|
||||
}
|
||||
s.render(w, "debug", buf.String())
|
||||
}
|
||||
|
||||
// deviceViews builds card views for all devices. When usePending is true, an
|
||||
// in-flight mode change is shown as a pending badge (and cleared once the
|
||||
// reported mode catches up).
|
||||
func (s *EconetUIServer) deviceViews(ctx context.Context, usePending bool) []cardView {
|
||||
resp, err := s.econetGRPC.ListDevices(ctx, &pb.ListDevicesRequest{})
|
||||
if err != nil {
|
||||
s.log.Error().Err(err).Msg("ui: list devices failed")
|
||||
return nil
|
||||
}
|
||||
views := make([]cardView, 0, len(resp.GetDevices()))
|
||||
for _, d := range resp.GetDevices() {
|
||||
views = append(views, s.toCardView(d, usePending))
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
// renderCard re-renders a single device's card, used for the HTMX swap after a
|
||||
// mode change. A successful change is optimistic (pending badge shown).
|
||||
func (s *EconetUIServer) renderCard(w http.ResponseWriter, ctx context.Context, serial, errMsg string) {
|
||||
resp, err := s.econetGRPC.GetDevice(ctx, &pb.GetDeviceRequest{SerialNumber: serial})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
cv := s.toCardView(resp.GetDevice(), true)
|
||||
cv.Error = errMsg
|
||||
s.render(w, "card", cv)
|
||||
}
|
||||
|
||||
func (s *EconetUIServer) toCardView(d *pb.Device, usePending bool) cardView {
|
||||
cv := cardView{Device: d, Icon: iconFor(d.GetGenericType())}
|
||||
|
||||
for _, m := range d.GetSupportedModes() {
|
||||
slug := econetgrpc.ModeSlug(m)
|
||||
cv.Modes = append(cv.Modes, modeOption{
|
||||
Value: m.String(),
|
||||
Label: prettyMode(slug),
|
||||
Selected: slug == d.GetMode(),
|
||||
})
|
||||
}
|
||||
|
||||
if usePending {
|
||||
if desired, ok := s.pending.get(d.GetSerialNumber()); ok {
|
||||
if desired == d.GetMode() {
|
||||
s.pending.clear(d.GetSerialNumber()) // reported caught up
|
||||
} else {
|
||||
cv.Pending = prettyMode(desired)
|
||||
}
|
||||
}
|
||||
}
|
||||
return cv
|
||||
}
|
||||
|
||||
func (s *EconetUIServer) render(w http.ResponseWriter, name string, data any) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
|
||||
s.log.Error().Err(err).Str("template", name).Msg("ui: render failed")
|
||||
}
|
||||
}
|
||||
|
||||
// iconFor maps a device's generic type to an embedded SVG asset. It matches
|
||||
// loosely (case/spacing/underscore-insensitive substrings) because the reported
|
||||
// @TYPE varies in form across firmware (e.g. "heatpumpWaterHeater", "HeatPump",
|
||||
// "Hybrid Electric"); unrecognized types fall back to a generic icon.
|
||||
func iconFor(genericType string) string {
|
||||
t := strings.NewReplacer(" ", "", "_", "", "-", "").Replace(strings.ToLower(genericType))
|
||||
switch {
|
||||
case strings.Contains(t, "heatpump"), strings.Contains(t, "hybrid"):
|
||||
return "/static/icons/heatpump.svg"
|
||||
case strings.Contains(t, "tankless"):
|
||||
return "/static/icons/tankless.svg"
|
||||
case strings.Contains(t, "gas"):
|
||||
return "/static/icons/gas.svg"
|
||||
case strings.Contains(t, "electric"):
|
||||
return "/static/icons/electric.svg"
|
||||
default:
|
||||
return "/static/icons/unknown.svg"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package econetui
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// pendingStore holds best-effort "desired mode" hints for the brief, async
|
||||
// window between a SetMode publish and the Rheem cloud reporting the new mode.
|
||||
// Entries expire after a TTL so a mode change that never takes hold quietly
|
||||
// falls back to the reported state (a "fresh get") rather than showing a stuck
|
||||
// pending badge forever.
|
||||
type pendingStore struct {
|
||||
mu sync.Mutex
|
||||
ttl time.Duration
|
||||
m map[string]pendingEntry
|
||||
}
|
||||
|
||||
type pendingEntry struct {
|
||||
desired string // desired mode slug
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
func newPendingStore(ttl time.Duration) *pendingStore {
|
||||
return &pendingStore{ttl: ttl, m: make(map[string]pendingEntry)}
|
||||
}
|
||||
|
||||
func (p *pendingStore) set(serial, desired string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.m[serial] = pendingEntry{desired: desired, expiresAt: time.Now().Add(p.ttl)}
|
||||
}
|
||||
|
||||
// get returns the desired mode slug for a serial, or ("", false) if there is no
|
||||
// pending change or it has expired (expired entries are dropped).
|
||||
func (p *pendingStore) get(serial string) (string, bool) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
e, ok := p.m[serial]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
if time.Now().After(e.expiresAt) {
|
||||
delete(p.m, serial)
|
||||
return "", false
|
||||
}
|
||||
return e.desired, true
|
||||
}
|
||||
|
||||
func (p *pendingStore) clear(serial string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
delete(p.m, serial)
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
Package econetui serves a small admin UI at / for viewing EcoNet devices and
|
||||
changing their operating mode. It renders server-side HTML (html/template with
|
||||
embedded assets) and uses HTMX for interactivity; device reads and mode writes
|
||||
go through the in-process gRPC server, exactly like the MCP packages. Auth is
|
||||
left to the edge (oauth2-proxy) — this package serves the human surface at /
|
||||
and the mode-write at /ui/, leaving /health, /metrics, and /api untouched.
|
||||
*/
|
||||
package econetui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/econet-exporter/pkg/config"
|
||||
"gitea.libretechconsulting.com/rmcguire/econet-exporter/pkg/econet/econetgrpc"
|
||||
)
|
||||
|
||||
//go:embed templates/*.html
|
||||
var templatesFS embed.FS
|
||||
|
||||
//go:embed static
|
||||
var staticFS embed.FS
|
||||
|
||||
// pendingTTL bounds how long an optimistic mode change is shown before the UI
|
||||
// falls back to the reported state.
|
||||
const pendingTTL = 90 * time.Second
|
||||
|
||||
type EconetUIServer struct {
|
||||
ctx context.Context
|
||||
cfg *config.ServiceConfig
|
||||
log *zerolog.Logger
|
||||
econetGRPC *econetgrpc.EconetGRPCServer
|
||||
tmpl *template.Template
|
||||
pending *pendingStore
|
||||
}
|
||||
|
||||
func NewEconetUIServer(ctx context.Context, cfg *config.ServiceConfig,
|
||||
grpc *econetgrpc.EconetGRPCServer,
|
||||
) *EconetUIServer {
|
||||
tmpl := template.Must(template.New("").Funcs(template.FuncMap{
|
||||
"prettyMode": prettyMode,
|
||||
"fillClass": fillClass,
|
||||
"fillWidth": fillWidth,
|
||||
}).ParseFS(templatesFS, "templates/*.html"))
|
||||
|
||||
return &EconetUIServer{
|
||||
ctx: ctx,
|
||||
cfg: cfg,
|
||||
log: zerolog.Ctx(ctx),
|
||||
econetGRPC: grpc,
|
||||
tmpl: tmpl,
|
||||
pending: newPendingStore(pendingTTL),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EconetUIServer) GetHandlers() []opts.HTTPHandler {
|
||||
staticSub, _ := fs.Sub(staticFS, "static")
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /{$}", s.handleIndex)
|
||||
mux.HandleFunc("GET /ui/devices", s.handleDevices)
|
||||
mux.HandleFunc("GET /ui/devices/{serial}/debug", s.handleDebug)
|
||||
mux.HandleFunc("POST /ui/devices/{serial}/mode", s.handleSetMode)
|
||||
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))
|
||||
|
||||
s.log.Debug().Msg("Econet admin UI ready at /")
|
||||
|
||||
return []opts.HTTPHandler{{Prefix: "/", Handler: mux}}
|
||||
}
|
||||
|
||||
// prettyMode turns a mode slug ("heat-pump") into a display label ("Heat Pump").
|
||||
func prettyMode(slug string) string {
|
||||
switch slug {
|
||||
case "":
|
||||
return "Unknown"
|
||||
case "electric-gas":
|
||||
return "Electric/Gas"
|
||||
}
|
||||
words := strings.Split(slug, "-")
|
||||
for i, w := range words {
|
||||
if w != "" {
|
||||
words[i] = strings.ToUpper(w[:1]) + w[1:]
|
||||
}
|
||||
}
|
||||
return strings.Join(words, " ")
|
||||
}
|
||||
|
||||
// fillClass buckets a hot-water fill percentage into a color class. It takes
|
||||
// int32 to match the proto Device field (html/template is strict about types).
|
||||
func fillClass(pct int32) string {
|
||||
switch {
|
||||
case pct >= 66:
|
||||
return "fill-high"
|
||||
case pct >= 33:
|
||||
return "fill-mid"
|
||||
default:
|
||||
return "fill-low"
|
||||
}
|
||||
}
|
||||
|
||||
// fillWidth returns a safe CSS width for the fill bar.
|
||||
func fillWidth(pct int32) template.CSS {
|
||||
if pct < 0 {
|
||||
pct = 0
|
||||
}
|
||||
return template.CSS(fmt.Sprintf("width:%d%%", pct))
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/* Layout + components for the EcoNet admin UI. Colors come from Pico's CSS
|
||||
custom properties so light and dark themes both work without overrides. */
|
||||
|
||||
body {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: 2.5rem 2rem;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
.app-header hgroup { margin-bottom: 0; }
|
||||
|
||||
.theme-toggle {
|
||||
flex: 0 0 auto;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
padding: 0;
|
||||
border-radius: 50%;
|
||||
font-size: 1.25rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* Comfortable, capped card width that wraps and centers, so a single device
|
||||
sits in a tidy card surrounded by whitespace rather than stretching wide or
|
||||
getting crammed. min(100%, 420px) keeps it fluid on narrow screens. */
|
||||
.device-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 460px));
|
||||
justify-content: center;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.device-card {
|
||||
margin: 0;
|
||||
padding: 2rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
.device-icon {
|
||||
flex: 0 0 auto;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
color: var(--pico-primary);
|
||||
}
|
||||
.card-title { flex: 1 1 auto; min-width: 0; line-height: 1.3; }
|
||||
.card-title strong { display: block; font-size: 1.2rem; }
|
||||
.card-title small { color: var(--pico-muted-color); word-break: break-all; }
|
||||
|
||||
.bug-btn {
|
||||
flex: 0 0 auto;
|
||||
padding: 0.25rem 0.4rem;
|
||||
background: none;
|
||||
border: none;
|
||||
border-radius: var(--pico-border-radius);
|
||||
font-size: 1.1rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
opacity: 0.55;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
.bug-btn:hover { opacity: 1; }
|
||||
|
||||
.dot {
|
||||
flex: 0 0 auto;
|
||||
width: 0.8rem;
|
||||
height: 0.8rem;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
}
|
||||
.dot-ok { background: var(--pico-color-green-500, #22c55e); }
|
||||
.dot-off { background: var(--pico-color-red-500, #ef4444); }
|
||||
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem 1.5rem;
|
||||
}
|
||||
.stats > div { display: flex; flex-direction: column; gap: 0.2rem; }
|
||||
.stats span { color: var(--pico-muted-color); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.04em; }
|
||||
.stats b { font-size: 1.1rem; }
|
||||
|
||||
.fill { display: flex; flex-direction: column; gap: 0.45rem; }
|
||||
.fill-head { display: flex; justify-content: space-between; align-items: baseline; }
|
||||
.fill-head span { color: var(--pico-muted-color); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.04em; }
|
||||
.fill-meter {
|
||||
height: 0.6rem;
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
background: color-mix(in srgb, var(--pico-muted-color) 22%, transparent);
|
||||
}
|
||||
.fill-bar { height: 100%; border-radius: 999px; transition: width 0.4s ease; }
|
||||
.fill-high { background: var(--pico-color-green-500, #22c55e); }
|
||||
.fill-mid { background: var(--pico-color-amber-500, #f59e0b); }
|
||||
.fill-low { background: var(--pico-color-red-500, #ef4444); }
|
||||
|
||||
.card-foot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
.mode-label { margin: 0; font-size: 0.85rem; color: var(--pico-muted-color); }
|
||||
.mode-label select { margin-top: 0.35rem; margin-bottom: 0; }
|
||||
.mode-fixed { color: var(--pico-muted-color); }
|
||||
|
||||
.badge {
|
||||
align-self: flex-start;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border-radius: var(--pico-border-radius);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.badge-pending {
|
||||
background: var(--pico-primary-background);
|
||||
color: var(--pico-primary-inverse);
|
||||
}
|
||||
.badge-error {
|
||||
background: var(--pico-color-red-500, #ef4444);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.empty-state { grid-column: 1 / -1; text-align: center; padding: 3rem 1rem; }
|
||||
|
||||
.debug-modal pre {
|
||||
max-height: 65vh;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
}
|
||||
.debug-modal code { white-space: pre; }
|
||||
|
||||
/* Mobile: tighten spacing; the grid already collapses to a single full-width
|
||||
column via minmax(min(100%, 420px), …). */
|
||||
@media (max-width: 480px) {
|
||||
body { padding: 1.25rem 1rem; }
|
||||
.app-header { margin-bottom: 1.5rem; }
|
||||
.app-header h1 { font-size: 1.6rem; }
|
||||
.device-grid { gap: 1.25rem; }
|
||||
.device-card { padding: 1.5rem; gap: 1.25rem; }
|
||||
.device-icon { width: 48px; height: 48px; }
|
||||
}
|
||||
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="14" y="8" width="20" height="32" rx="4"/>
|
||||
<line x1="18" y1="40" x2="18" y2="43"/>
|
||||
<line x1="30" y1="40" x2="30" y2="43"/>
|
||||
<path d="M25 15l-5 7h4l-1 7 6-8h-4z" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 397 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="14" y="6" width="20" height="28" rx="4"/>
|
||||
<line x1="18" y1="34" x2="18" y2="37"/>
|
||||
<line x1="30" y1="34" x2="30" y2="37"/>
|
||||
<path d="M24 38c-3 0-5 2-5 4.5S21 46 24 46s5-1.5 5-3.5c0-3-3-3.5-2-6.5-2 1-3 2.5-3 4.5z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 415 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="14" y="12" width="20" height="30" rx="4"/>
|
||||
<line x1="18" y1="42" x2="18" y2="45"/>
|
||||
<line x1="30" y1="42" x2="30" y2="45"/>
|
||||
<circle cx="24" cy="9" r="6"/>
|
||||
<path d="M24 5.5v7M20.5 9h7M21.5 6.5l5 5M26.5 6.5l-5 5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 416 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="12" y="10" width="24" height="22" rx="3"/>
|
||||
<line x1="18" y1="32" x2="18" y2="40"/>
|
||||
<line x1="30" y1="32" x2="30" y2="40"/>
|
||||
<line x1="17" y1="17" x2="31" y2="17"/>
|
||||
<circle cx="24" cy="25" r="3"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 399 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="14" y="8" width="20" height="32" rx="4"/>
|
||||
<line x1="18" y1="40" x2="18" y2="43"/>
|
||||
<line x1="30" y1="40" x2="30" y2="43"/>
|
||||
<path d="M21 20a3 3 0 1 1 4 2.8c-1 .5-1 1.2-1 2.2"/>
|
||||
<line x1="24" y1="30" x2="24" y2="30.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 421 B |
File diff suppressed because one or more lines are too long
@@ -0,0 +1,57 @@
|
||||
{{define "card"}}
|
||||
<article id="card-{{.Device.SerialNumber}}" class="device-card">
|
||||
<div class="card-head">
|
||||
<img class="device-icon" src="{{.Icon}}" alt="" width="56" height="56">
|
||||
<div class="card-title">
|
||||
<strong>{{.Device.FriendlyName}}</strong>
|
||||
<small>{{.Device.SerialNumber}}</small>
|
||||
</div>
|
||||
<button class="bug-btn" title="Show raw device JSON" aria-label="Show raw device JSON"
|
||||
hx-get="/ui/devices/{{.Device.SerialNumber}}/debug"
|
||||
hx-target="#debug-modal-body"
|
||||
hx-swap="innerHTML"
|
||||
onclick="document.getElementById('debug-modal').showModal()">🐛</button>
|
||||
<span class="dot {{if .Device.Connected}}dot-ok{{else}}dot-off{{end}}"
|
||||
title="{{if .Device.Connected}}Connected{{else}}Disconnected{{end}}"></span>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div><span>Status</span>
|
||||
<b>{{if .Device.Running}}🔥 {{prettyMode .Device.RunningState}}{{else}}Idle{{end}}</b></div>
|
||||
<div><span>Setpoint</span><b>{{.Device.Setpoint}}°F</b></div>
|
||||
<div><span>Alerts</span>
|
||||
<b>{{if gt .Device.AlertCount 0}}⚠ {{.Device.AlertCount}}{{else}}0{{end}}</b></div>
|
||||
</div>
|
||||
|
||||
{{if ge .Device.HotWaterAvailability 0}}
|
||||
<div class="fill">
|
||||
<div class="fill-head"><span>Hot water</span><b>{{.Device.HotWaterAvailability}}%</b></div>
|
||||
<div class="fill-meter">
|
||||
<div class="fill-bar {{fillClass .Device.HotWaterAvailability}}" style="{{fillWidth .Device.HotWaterAvailability}}"></div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div class="card-foot">
|
||||
{{if .Modes}}
|
||||
<label class="mode-label">
|
||||
Mode
|
||||
<select name="mode"
|
||||
hx-post="/ui/devices/{{.Device.SerialNumber}}/mode"
|
||||
hx-target="#card-{{.Device.SerialNumber}}"
|
||||
hx-swap="outerHTML"
|
||||
hx-trigger="change"
|
||||
{{if .Pending}}disabled aria-busy="true"{{end}}>
|
||||
{{range .Modes}}
|
||||
<option value="{{.Value}}" {{if .Selected}}selected{{end}}>{{.Label}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
</label>
|
||||
{{if .Pending}}<span class="badge badge-pending" aria-busy="true">Updating → {{.Pending}}…</span>{{end}}
|
||||
{{else}}
|
||||
<small class="mode-fixed">Mode: {{prettyMode .Device.Mode}} (not settable)</small>
|
||||
{{end}}
|
||||
{{if .Error}}<span class="badge badge-error" role="alert">{{.Error}}</span>{{end}}
|
||||
</div>
|
||||
</article>
|
||||
{{end}}
|
||||
@@ -0,0 +1 @@
|
||||
{{define "debug"}}{{.}}{{end}}
|
||||
@@ -0,0 +1,10 @@
|
||||
{{define "devices"}}
|
||||
{{if .Devices}}
|
||||
{{range .Devices}}{{template "card" .}}{{end}}
|
||||
{{else}}
|
||||
<article class="empty-state">
|
||||
<p>No EcoNet devices loaded yet.</p>
|
||||
<small>Device state populates after the first successful cloud poll.</small>
|
||||
</article>
|
||||
{{end}}
|
||||
{{end}}
|
||||
@@ -0,0 +1,57 @@
|
||||
{{define "layout"}}<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>EcoNet Admin</title>
|
||||
<link rel="stylesheet" href="/static/pico.classless.min.css">
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
<script src="/static/htmx.min.js" defer></script>
|
||||
<script>
|
||||
// Set the theme before first paint to avoid a flash.
|
||||
(function () {
|
||||
var saved = localStorage.getItem("theme");
|
||||
var theme = saved || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<hgroup>
|
||||
<h1>EcoNet Admin</h1>
|
||||
<p>Rheem water heater status & control</p>
|
||||
</hgroup>
|
||||
<button id="theme-toggle" class="secondary theme-toggle" aria-label="Toggle dark mode" onclick="toggleTheme()"></button>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<div id="devices" class="device-grid" hx-get="/ui/devices" hx-trigger="every 30s" hx-swap="innerHTML">
|
||||
{{template "devices" .}}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<dialog id="debug-modal" class="debug-modal">
|
||||
<article>
|
||||
<header>
|
||||
<button aria-label="Close" rel="prev" onclick="document.getElementById('debug-modal').close()"></button>
|
||||
<strong>Raw device JSON</strong>
|
||||
</header>
|
||||
<pre><code id="debug-modal-body">Loading…</code></pre>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<script>
|
||||
function themeIcon(t) { return t === "dark" ? "☀️" : "🌙"; } // sun / moon
|
||||
function toggleTheme() {
|
||||
var cur = document.documentElement.getAttribute("data-theme");
|
||||
var next = cur === "dark" ? "light" : "dark";
|
||||
document.documentElement.setAttribute("data-theme", next);
|
||||
localStorage.setItem("theme", next);
|
||||
document.getElementById("theme-toggle").textContent = themeIcon(next);
|
||||
}
|
||||
document.getElementById("theme-toggle").textContent =
|
||||
themeIcon(document.documentElement.getAttribute("data-theme"));
|
||||
</script>
|
||||
</body>
|
||||
</html>{{end}}
|
||||
@@ -0,0 +1,148 @@
|
||||
package econetui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
pb "gitea.libretechconsulting.com/rmcguire/econet-exporter/api/econet/v1alpha1"
|
||||
"gitea.libretechconsulting.com/rmcguire/econet-exporter/pkg/config"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) *EconetUIServer {
|
||||
t.Helper()
|
||||
// grpc is nil: the render/view helpers under test never touch it.
|
||||
return NewEconetUIServer(context.Background(), &config.ServiceConfig{}, nil)
|
||||
}
|
||||
|
||||
func sampleDevice() *pb.Device {
|
||||
return &pb.Device{
|
||||
SerialNumber: "SN123",
|
||||
FriendlyName: "Garage Water Heater",
|
||||
GenericType: "heatpumpWaterHeater",
|
||||
Connected: true,
|
||||
Mode: "energy-saving",
|
||||
Running: true,
|
||||
RunningState: "compressor-running",
|
||||
Setpoint: 120,
|
||||
HotWaterAvailability: 66,
|
||||
AlertCount: 1,
|
||||
SupportedModes: []pb.Mode{
|
||||
pb.Mode_MODE_HEAT_PUMP,
|
||||
pb.Mode_MODE_ENERGY_SAVING,
|
||||
pb.Mode_MODE_HIGH_DEMAND,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardRendersWithPending(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
d := sampleDevice()
|
||||
|
||||
// Simulate an in-flight change to a mode different from the reported one.
|
||||
s.pending.set(d.SerialNumber, "heat-pump")
|
||||
|
||||
cv := s.toCardView(d, true)
|
||||
if cv.Pending != "Heat Pump" {
|
||||
t.Fatalf("pending = %q, want %q", cv.Pending, "Heat Pump")
|
||||
}
|
||||
if cv.Icon != "/static/icons/heatpump.svg" {
|
||||
t.Fatalf("icon = %q", cv.Icon)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
s.render(rec, "card", cv)
|
||||
body := rec.Body.String()
|
||||
|
||||
for _, want := range []string{
|
||||
`id="card-SN123"`,
|
||||
"Garage Water Heater",
|
||||
`hx-post="/ui/devices/SN123/mode"`,
|
||||
"badge-pending",
|
||||
"Updating", // "Updating → Heat Pump…"
|
||||
"Energy Saving",
|
||||
"Heat Pump",
|
||||
"High Demand",
|
||||
"120°F",
|
||||
"66%",
|
||||
"fill-meter", // fill-level graph
|
||||
"fill-high", // 66% → high bucket (>=66)
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("card body missing %q\n---\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardConvergenceClearsPending(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
d := sampleDevice()
|
||||
d.Mode = "heat-pump" // reported now matches the desired
|
||||
|
||||
s.pending.set(d.SerialNumber, "heat-pump")
|
||||
cv := s.toCardView(d, true)
|
||||
|
||||
if cv.Pending != "" {
|
||||
t.Fatalf("pending should clear once reported catches up, got %q", cv.Pending)
|
||||
}
|
||||
if _, ok := s.pending.get(d.SerialNumber); ok {
|
||||
t.Fatalf("pending entry should have been removed after convergence")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevicesEmptyState(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
rec := httptest.NewRecorder()
|
||||
s.render(rec, "devices", pageView{})
|
||||
if !strings.Contains(rec.Body.String(), "No EcoNet devices loaded yet") {
|
||||
t.Errorf("empty state not rendered:\n%s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIconForLoose(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"heatpumpWaterHeater": "/static/icons/heatpump.svg",
|
||||
"heatpumpWaterHeaterGen5": "/static/icons/heatpump.svg",
|
||||
"HeatPump": "/static/icons/heatpump.svg",
|
||||
"Hybrid Electric": "/static/icons/heatpump.svg",
|
||||
"heat_pump_water_heater": "/static/icons/heatpump.svg",
|
||||
"gasWaterHeater": "/static/icons/gas.svg",
|
||||
"tanklessWaterHeater": "/static/icons/tankless.svg",
|
||||
"electricWaterHeater": "/static/icons/electric.svg",
|
||||
"somethingElse": "/static/icons/unknown.svg",
|
||||
"": "/static/icons/unknown.svg",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := iconFor(in); got != want {
|
||||
t.Errorf("iconFor(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebugTemplateEscapes(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
rec := httptest.NewRecorder()
|
||||
s.render(rec, "debug", `{"@NAME":"<b>x</b>"}`)
|
||||
body := rec.Body.String()
|
||||
if strings.Contains(body, "<b>") {
|
||||
t.Errorf("debug output not escaped: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "<b>") {
|
||||
t.Errorf("expected escaped JSON, got: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrettyMode(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"heat-pump": "Heat Pump",
|
||||
"energy-saving": "Energy Saving",
|
||||
"off": "Off",
|
||||
"": "Unknown",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := prettyMode(in); got != want {
|
||||
t.Errorf("prettyMode(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user