|
|
|
@ -3,7 +3,7 @@ package htmxmqtt
|
|
|
|
|
import (
|
|
|
|
|
"time"
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
|
|
|
|
"log/slog"
|
|
|
|
|
"fmt"
|
|
|
|
|
"context"
|
|
|
|
|
"sync"
|
|
|
|
@ -31,7 +31,7 @@ func (handler *MQTTHandler) processMessage(client mqtt.Client, message mqtt.Mess
|
|
|
|
|
case channel <- message:
|
|
|
|
|
remaining = append(remaining, channel)
|
|
|
|
|
default:
|
|
|
|
|
os.Stderr.WriteString("Channel overflow\n")
|
|
|
|
|
slog.Warn("Channel overflow")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -107,7 +107,10 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
|
|
|
|
|
conn, err := websocket.Accept(w, r, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket accept error: %s\n", err))
|
|
|
|
|
slog.Error("websocket accept error", "error", err)
|
|
|
|
|
return
|
|
|
|
|
} else {
|
|
|
|
|
slog.Info("new websocket connection", "addr", r.RemoteAddr)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
defer conn.CloseNow()
|
|
|
|
@ -117,11 +120,11 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
for true {
|
|
|
|
|
msg_type, data, err := conn.Read(ctx)
|
|
|
|
|
if err != nil {
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket error: %s\n", err))
|
|
|
|
|
slog.Error("websocket error", "error", err)
|
|
|
|
|
cancel_func()
|
|
|
|
|
break
|
|
|
|
|
} else {
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket data(%s): %s\n", msg_type, string(data)))
|
|
|
|
|
slog.Debug("websocket data", "type", msg_type, "data", string(data))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}(conn, cancel_func)
|
|
|
|
@ -131,18 +134,20 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
for running == true {
|
|
|
|
|
select {
|
|
|
|
|
case <- done:
|
|
|
|
|
os.Stderr.WriteString("websocket context done")
|
|
|
|
|
slog.Debug("websocket context done")
|
|
|
|
|
running = false
|
|
|
|
|
case message := <- channel:
|
|
|
|
|
text := handler.format(message)
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket write: %s\n", text))
|
|
|
|
|
slog.Debug("websocket write", "data", text)
|
|
|
|
|
err := conn.Write(ctx, websocket.MessageText, text)
|
|
|
|
|
if err != nil {
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket write error: %s\n", err))
|
|
|
|
|
slog.Error("websocket write error", "error", err)
|
|
|
|
|
running = false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
slog.Info("closing websocket", "addr", r.RemoteAddr)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func PayloadFormatFunc(template string) MQTTFormatFunc {
|
|
|
|
|