100 lines
1.9 KiB
Go

package onvif
import (
"github.com/gin-gonic/gin"
"net/http"
"onvif-agent/response"
"onvif-agent/service/onvif"
)
var conns = make(map[string]*onvif.Connection)
type CreateConnectionRequest struct {
Xaddr string `json:"xaddr"`
Username string `json:"username"`
Password string `json:"password"`
}
func CreateConnection(c *gin.Context) {
var req CreateConnectionRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.NewResponse().Error(err).Send(c)
return
}
conn, err := onvif.New(req.Xaddr, req.Username, req.Password)
if err != nil {
response.NewResponse().Error(err).Send(c)
return
}
info, err := conn.GetDeviceInfo()
if err != nil {
response.NewResponse().Error(err).Send(c)
return
}
// store connection
conns[conn.Device.GetDeviceParams().Xaddr] = conn
response.NewResponse().WithData(info).Send(c)
}
func GetConnections(c *gin.Context) {
devices := make(map[string]any)
for xaddr, conn := range conns {
info, err := conn.GetDeviceInfo()
if err != nil {
response.NewResponse().Error(err).Send(c)
return
}
devices[xaddr] = info
}
response.NewResponse().WithData(devices).Send(c)
}
func ZBXConnectionDiscovery(c *gin.Context) {
type ZBXDiscovery struct {
Xaddr string `json:"{#XADDR}"`
}
arr := make([]ZBXDiscovery, 0)
for xaddr := range conns {
arr = append(arr, ZBXDiscovery{
Xaddr: xaddr,
})
}
c.JSON(http.StatusOK, gin.H{
"data": arr,
})
}
func GetConnectionByXaddr(c *gin.Context) {
xaddr := c.Param("xaddr")
conn := conns[xaddr]
if conn == nil {
response.NewResponse().Fail("Connection not found").WithCode(http.StatusNotFound).Send(c)
return
}
info, err := conn.GetDeviceInfo()
if err != nil {
response.NewResponse().Error(err).Send(c)
return
}
response.NewResponse().WithData(info).Send(c)
}
func DeleteConnection(c *gin.Context) {
xaddr := c.Param("xaddr")
delete(conns, xaddr)
response.NewResponse().Success().Send(c)
}