119 lines
2.5 KiB
Go
119 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/IOTechSystems/onvif/event"
|
|
"github.com/IOTechSystems/onvif/gosoap"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
var connections = make(map[string]*Connection)
|
|
|
|
func main() {
|
|
|
|
r := gin.Default()
|
|
|
|
r.GET("/ping", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "pong",
|
|
})
|
|
})
|
|
|
|
r.POST("/onvif", createConnection)
|
|
r.GET("/onvif", getConnections)
|
|
r.GET("/onvif/:xaddr", getConnectionByXaddr)
|
|
r.DELETE("/onvif/:xaddr", deleteConnection)
|
|
|
|
r.POST("/events/subscribe/:xaddr", eventsSubscribe)
|
|
r.POST("/events/callback", eventsCallback)
|
|
|
|
go func() {
|
|
if err := r.Run(":8080"); err != nil {
|
|
fmt.Println("Failed to start server:", err)
|
|
}
|
|
}()
|
|
|
|
//log.Print("Waiting for server to start...")
|
|
//time.Sleep(3 * time.Second)
|
|
//go printTime()
|
|
|
|
// block main()
|
|
select {}
|
|
}
|
|
|
|
func createConnection(c *gin.Context) {
|
|
conn, err := NewConnection("172.16.19.239", "admin", "admin123")
|
|
if err != nil {
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{
|
|
"message": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
connections[conn.Device.GetDeviceParams().Xaddr] = conn
|
|
|
|
info, err := conn.GetDeviceInformation()
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"connectionParams": conn.Params,
|
|
"deviceInfo": info,
|
|
})
|
|
}
|
|
|
|
func getConnections(c *gin.Context) {
|
|
c.JSON(http.StatusOK, connections)
|
|
}
|
|
|
|
func getConnectionByXaddr(c *gin.Context) {
|
|
xaddr := c.Param("xaddr")
|
|
c.JSON(http.StatusOK, connections[xaddr])
|
|
}
|
|
|
|
func deleteConnection(c *gin.Context) {
|
|
xaddr := c.Param("xaddr")
|
|
delete(connections, xaddr)
|
|
}
|
|
|
|
func eventsSubscribe(c *gin.Context) {
|
|
xaddr := c.Param("xaddr")
|
|
result, err := connections[xaddr].SubscribeEvents("http://172.16.19.230:8080/events/callback")
|
|
if err != nil {
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{
|
|
"message": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, result)
|
|
}
|
|
|
|
func eventsCallback(c *gin.Context) {
|
|
var notify event.Notify
|
|
envelope := gosoap.NewSOAPEnvelope(¬ify)
|
|
if err := c.ShouldBindXML(&envelope); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
for _, msg := range envelope.Body.Content.(*event.Notify).NotificationMessage {
|
|
log.Println(msg.Topic.TopicKinds, msg.Message.Message)
|
|
}
|
|
|
|
c.String(http.StatusOK, "OK")
|
|
}
|
|
|
|
func printTime() {
|
|
ticker := time.NewTicker(1 * time.Second) // 每秒触发一次
|
|
defer ticker.Stop() // 确保在函数结束时停止 ticker
|
|
|
|
for {
|
|
select {
|
|
case t := <-ticker.C:
|
|
fmt.Println("当前时间:", t.Format("2006-01-02 15:04:05"))
|
|
}
|
|
}
|
|
}
|