164 lines
3.1 KiB
Go
164 lines
3.1 KiB
Go
// cmd/server/main.go
|
||
package main
|
||
|
||
import (
|
||
"context"
|
||
"embed"
|
||
"encoding/json"
|
||
"flag"
|
||
"io/fs"
|
||
"log"
|
||
"net/http"
|
||
"os"
|
||
"time"
|
||
|
||
"gpio-monitor/internal/adapter"
|
||
)
|
||
|
||
// ===== EMBED WEB =====
|
||
//go:embed web/*
|
||
var webFiles embed.FS
|
||
|
||
type API struct {
|
||
buf *adapter.RingBuffer
|
||
startTime time.Time
|
||
}
|
||
|
||
func writeJSON(w http.ResponseWriter, v any) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(v)
|
||
}
|
||
|
||
func (a *API) HandleHealth(w http.ResponseWriter, r *http.Request) {
|
||
latest, ok := a.buf.GetLatest()
|
||
idle := time.Since(a.buf.LastWriteTime())
|
||
|
||
status := "На связи"
|
||
if idle > 15*time.Second {
|
||
status = "Нет связи"
|
||
}
|
||
|
||
writeJSON(w, map[string]any{
|
||
"status": status,
|
||
"uptime_sec": time.Since(a.startTime).Seconds(),
|
||
"last_data_ms": idle.Milliseconds(),
|
||
"pipe_alive": a.buf.IsAlive(3 * time.Second),
|
||
"has_data": ok,
|
||
"latest": latest,
|
||
"stats": a.buf.Stats(),
|
||
})
|
||
}
|
||
|
||
func (a *API) HandleLatest(w http.ResponseWriter, r *http.Request) {
|
||
latest, ok := a.buf.GetLatest()
|
||
if !ok {
|
||
writeJSON(w, map[string]string{"error": "no data"})
|
||
return
|
||
}
|
||
|
||
writeJSON(w, map[string]any{
|
||
"latest": latest,
|
||
"history": a.buf.GetLast(10),
|
||
})
|
||
}
|
||
|
||
func (a *API) HandleHistory(w http.ResponseWriter, r *http.Request) {
|
||
raw := a.buf.GetLast(100)
|
||
|
||
out := make([]int, len(raw))
|
||
for i, v := range raw {
|
||
out[i] = int(v)
|
||
}
|
||
|
||
writeJSON(w, map[string]any{
|
||
"bytes": out,
|
||
})
|
||
}
|
||
|
||
// ===== PIPE READER =====
|
||
|
||
func startPipeReader(ctx context.Context, buf *adapter.RingBuffer, path string) {
|
||
go func() {
|
||
buffer := make([]byte, 64)
|
||
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
default:
|
||
}
|
||
|
||
f, err := os.OpenFile(path, os.O_RDONLY, 0)
|
||
if err != nil {
|
||
time.Sleep(time.Second)
|
||
continue
|
||
}
|
||
|
||
log.Println("pipe connected")
|
||
|
||
for {
|
||
n, err := f.Read(buffer)
|
||
if err != nil {
|
||
f.Close()
|
||
break
|
||
}
|
||
|
||
for i := 0; i < n; i++ {
|
||
buf.Write(buffer[i])
|
||
}
|
||
}
|
||
|
||
log.Println("pipe disconnected, retry...")
|
||
}
|
||
}()
|
||
}
|
||
|
||
func cors(next http.HandlerFunc) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||
next(w, r)
|
||
}
|
||
}
|
||
|
||
func main() {
|
||
pipePath := flag.String("pipe", "/tmp/gpio_pipe", "pipe path")
|
||
flag.Parse()
|
||
|
||
buf := adapter.NewRingBuffer(1024 * 10)
|
||
ctx, cancel := context.WithCancel(context.Background())
|
||
defer cancel()
|
||
|
||
startPipeReader(ctx, buf, *pipePath)
|
||
|
||
api := &API{
|
||
buf: buf,
|
||
startTime: time.Now(),
|
||
}
|
||
|
||
// ===== API =====
|
||
http.Handle("/api/", http.StripPrefix("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
||
switch r.URL.Path {
|
||
case "/latest":
|
||
cors(api.HandleLatest)(w, r)
|
||
case "/history":
|
||
cors(api.HandleHistory)(w, r)
|
||
case "/health":
|
||
cors(api.HandleHealth)(w, r)
|
||
default:
|
||
http.Error(w, "not found", 404)
|
||
}
|
||
})))
|
||
|
||
// ===== WEB (EMBEDDED) =====
|
||
webFS, err := fs.Sub(webFiles, "web")
|
||
if err != nil {
|
||
log.Fatal(err)
|
||
}
|
||
|
||
http.Handle("/", http.FileServer(http.FS(webFS)))
|
||
|
||
log.Println("server :8080")
|
||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||
}
|