|
|
|
@ -16,9 +16,10 @@ import (
|
|
|
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type MQTTFormatFunc func(mqtt.Message) []byte
|
|
|
|
|
type MQTTHandler struct {
|
|
|
|
|
sync.Mutex
|
|
|
|
|
Template string
|
|
|
|
|
Format MQTTFormatFunc
|
|
|
|
|
Channels []chan mqtt.Message
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -87,9 +88,9 @@ func NewMQTTHandlerClient(broker string, username string, password string, id st
|
|
|
|
|
}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (client *MQTTHandlerClient) NewHandler(subscription string, template string) (*MQTTHandler, error) {
|
|
|
|
|
func (client *MQTTHandlerClient) NewHandler(subscription string, format MQTTFormatFunc) (*MQTTHandler, error) {
|
|
|
|
|
handler := &MQTTHandler{
|
|
|
|
|
Template: template,
|
|
|
|
|
Format: format,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sub_token := client.Subscribe(subscription, 0x00, handler.ProcessMessage)
|
|
|
|
@ -103,10 +104,6 @@ func (client *MQTTHandlerClient) NewHandler(subscription string, template string
|
|
|
|
|
return handler, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (handler *MQTTHandler) Format(message mqtt.Message) []byte {
|
|
|
|
|
return []byte(fmt.Sprintf(handler.Template, message.Payload()))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channel := make(chan mqtt.Message, 1)
|
|
|
|
|
remove_channel := handler.AddChannel(channel)
|
|
|
|
@ -141,8 +138,9 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
os.Stderr.WriteString("websocket context done")
|
|
|
|
|
running = false
|
|
|
|
|
case message := <- channel:
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket write: %s\n", message.Payload()))
|
|
|
|
|
err := conn.Write(ctx, websocket.MessageText, message.Payload())
|
|
|
|
|
text := handler.Format(message)
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket write: %s\n", text))
|
|
|
|
|
err := conn.Write(ctx, websocket.MessageText, text)
|
|
|
|
|
if err != nil {
|
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("websocket write error: %s\n", err))
|
|
|
|
|
running = false
|
|
|
|
@ -151,13 +149,19 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func PayloadFormatFunc(template string) MQTTFormatFunc {
|
|
|
|
|
return func(message mqtt.Message) []byte {
|
|
|
|
|
return []byte(fmt.Sprintf(template, message.Payload()))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
handler_client, err := NewMQTTHandlerClient("tcp://localhost:1883", "", "", "htmx")
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
handler_1, err := handler_client.NewHandler("test", "%s")
|
|
|
|
|
handler_1, err := handler_client.NewHandler("test", PayloadFormatFunc(`<p id="test">%s</p>`))
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|