-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
98 lines (86 loc) · 2.31 KB
/
Copy pathmain.go
File metadata and controls
98 lines (86 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"github.com/gin-gonic/gin"
"github.com/olahol/melody"
"log"
"net/http"
"slices"
)
func main() {
gin.SetMode(gin.ReleaseMode)
m := melody.New()
r := gin.Default()
r.Static("/echo-live", "static/echo-live/echo-live")
//fmt.Println(echoliveStaticFS.ReadDir("static/echo-live/echo-live"))
r.LoadHTMLGlob("static/echo-live/*.html")
var devicesList []Device
r.GET("/live", func(c *gin.Context) {
c.HTML(http.StatusOK, "live.html", gin.H{})
})
r.GET("/history", func(c *gin.Context) {
c.HTML(http.StatusOK, "history.html", gin.H{})
})
r.GET("/settings", func(c *gin.Context) {
c.HTML(http.StatusOK, "settings.html", gin.H{})
})
r.GET("/editor", func(c *gin.Context) {
c.HTML(http.StatusOK, "editor.html", gin.H{})
})
r.GET("/ws", func(c *gin.Context) {
err := m.HandleRequest(c.Writer, c.Request)
if err != nil {
log.Println("HandleRequest error:", err)
return
}
})
m.HandleConnect(func(s *melody.Session) {
log.Println("存在设备接入:", s.RemoteAddr())
//newDeviceRegData := NewEchoAPI()
//json, _ := newDeviceRegData.Marshal()
//err := s.Write(json)
//if err != nil {
// log.Println("发送注册信息失败:", err)
// return
//}
})
m.HandleDisconnect(func(s *melody.Session) {
log.Println("设备断开连接", s.RemoteAddr())
for index, device := range devicesList {
if device.Addr == s.RemoteAddr() {
log.Println("设备删除:", device.Addr, device.UUID)
slices.Delete(devicesList, index, index+1)
break
}
}
})
m.HandleMessage(func(s *melody.Session, msg []byte) {
log.Println("收到新WS消息:", string(msg))
echoAPIData := NewEchoAPI()
err := echoAPIData.Unmarshal(msg)
if err != nil {
log.Println("解析消息失败:", err)
return
}
switch echoAPIData.Action {
case "hello":
log.Println("收到设备注册信息:", s.RemoteAddr(), echoAPIData.From.UUID)
devicesList = append(devicesList, Device{
Name: echoAPIData.From.Name,
UUID: echoAPIData.From.UUID,
Type: echoAPIData.From.Type,
Timestamp: echoAPIData.From.Timestamp,
Addr: s.RemoteAddr(),
})
}
err = m.Broadcast(msg)
if err != nil {
log.Println("广播消息失败:", err)
return
}
})
err := r.Run(":3000")
if err != nil {
log.Fatal("ListenAndServe: ", err)
return
}
}