Adds websocket for opened
All checks were successful
Gitea Build Action / build-go (push) Successful in 26s
Gitea Build Action / build-nuxt (push) Successful in 10m2s

This commit is contained in:
Daniel Svitan 2025-06-07 09:15:00 +02:00
parent 000c12845c
commit 4aad657c9d
2 changed files with 36 additions and 3 deletions

View File

@ -24,7 +24,7 @@ var token string
// the condition is: distance >= threshold (is door open)
var opened bool
var openedChange = make(chan bool)
var openedChange = make(chan any)
// is door locked
var locked bool = false

View File

@ -1,11 +1,15 @@
package main
import (
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
"net/http"
"time"
)
var upgrader = websocket.Upgrader{}
func helloWorld(c echo.Context) error {
return c.JSON(http.StatusOK, "Hello world!")
}
@ -19,7 +23,36 @@ func getOpened(c echo.Context) error {
}
func getOpenedWs(c echo.Context) error {
return nil
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
}
defer func() { _ = ws.Close() }()
// empty the channel
emptied := false
for !emptied {
select {
case <-openedChange:
default:
emptied = true
}
}
for {
<-openedChange
mut.Lock()
err = ws.WriteJSON(opened)
mut.Unlock()
if err != nil {
log.Error(err)
break
}
}
return err
}
func setOpened(c echo.Context) error {
@ -46,7 +79,7 @@ func setOpened(c echo.Context) error {
go sendAlert(action)
}
openedChange <- true
openedChange <- 0
mut.Unlock()
return c.NoContent(http.StatusOK)
}