✨ Adds websocket for opened
This commit is contained in:
parent
000c12845c
commit
4aad657c9d
@ -24,7 +24,7 @@ var token string
|
|||||||
|
|
||||||
// the condition is: distance >= threshold (is door open)
|
// the condition is: distance >= threshold (is door open)
|
||||||
var opened bool
|
var opened bool
|
||||||
var openedChange = make(chan bool)
|
var openedChange = make(chan any)
|
||||||
|
|
||||||
// is door locked
|
// is door locked
|
||||||
var locked bool = false
|
var locked bool = false
|
||||||
|
@ -1,11 +1,15 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
|
"github.com/labstack/gommon/log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var upgrader = websocket.Upgrader{}
|
||||||
|
|
||||||
func helloWorld(c echo.Context) error {
|
func helloWorld(c echo.Context) error {
|
||||||
return c.JSON(http.StatusOK, "Hello world!")
|
return c.JSON(http.StatusOK, "Hello world!")
|
||||||
}
|
}
|
||||||
@ -19,7 +23,36 @@ func getOpened(c echo.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getOpenedWs(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 {
|
func setOpened(c echo.Context) error {
|
||||||
@ -46,7 +79,7 @@ func setOpened(c echo.Context) error {
|
|||||||
go sendAlert(action)
|
go sendAlert(action)
|
||||||
}
|
}
|
||||||
|
|
||||||
openedChange <- true
|
openedChange <- 0
|
||||||
mut.Unlock()
|
mut.Unlock()
|
||||||
return c.NoContent(http.StatusOK)
|
return c.NoContent(http.StatusOK)
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user