th7/api/api.go

89 lines
2.1 KiB
Go
Raw Normal View History

2023-12-12 21:07:04 +00:00
package api
2023-12-05 17:22:12 +00:00
import (
"fmt"
2023-12-12 21:07:04 +00:00
"log"
2023-12-05 17:22:12 +00:00
"github.com/gin-gonic/gin"
"th7/data/config"
"th7/ports"
)
type GinAdapter struct {
router *gin.Engine
corePort ports.CorePort
cfg config.Config
port int
}
func (g *GinAdapter) IndexHandler(c *gin.Context) {
2023-12-06 19:39:51 +00:00
c.File("./static/index.html")
2023-12-05 17:22:12 +00:00
}
func NewGinAdapter(corePort ports.CorePort, cfg config.Config) *GinAdapter {
var adapter GinAdapter
adapter.corePort = corePort
2023-12-12 21:07:04 +00:00
adapter.port = cfg.API.Port
2023-12-05 17:22:12 +00:00
adapter.cfg = cfg
//gin.SetMode(gin.ReleaseMode)
adapter.router = gin.New()
2023-12-12 21:07:04 +00:00
// websockets
manager := NewManager()
go manager.start()
2023-12-05 17:22:12 +00:00
// API
2023-12-06 19:39:51 +00:00
adapter.router.GET("/v1/data/channel/:id", adapter.GetChannelByIDHandler)
adapter.router.GET("/v1/data/channels", adapter.GetChannelsHandler)
adapter.router.GET("/v1/data/ratio", adapter.GetRatioHandler)
adapter.router.GET("/v1/data", adapter.GetDataHandler)
2023-12-05 17:22:12 +00:00
2023-12-06 19:39:51 +00:00
adapter.router.GET("/v1/config/channel/:id", adapter.GetConfigChannelByIdHandler)
adapter.router.GET("/v1/config/channels", adapter.GetConfigChannelsHandler)
adapter.router.GET("/v1/config/device", adapter.GetConfigDeviceHandler)
adapter.router.GET("/v1/config/db", adapter.GetConfigDBHandler)
2023-12-05 17:22:12 +00:00
2023-12-12 21:07:04 +00:00
adapter.router.GET("/ws", func(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
}
client := &Client{
socket: conn,
send: make(chan []byte),
manager: manager,
all: false,
channels: false,
config: false,
}
manager.register <- client
go client.read()
go client.write()
})
2023-12-06 19:39:51 +00:00
adapter.router.POST("/v1/config/device", adapter.SetConfigDeviceHandler)
adapter.router.POST("/v1/config/channel/:id", adapter.SetConfigChannelByIdHandler)
adapter.router.POST("/v1/config/db", adapter.SetConfigDBHandler)
2023-12-05 17:22:12 +00:00
2023-12-12 21:07:04 +00:00
// start service that dumps new data to websocket chan
go startService(manager, corePort)
2023-12-06 19:39:51 +00:00
// TH7 demo code. html file and javascript
2023-12-05 17:22:12 +00:00
adapter.router.GET("/", adapter.IndexHandler)
2023-12-06 19:39:51 +00:00
adapter.router.Static("/assets", "./static")
2023-12-05 17:22:12 +00:00
return &adapter
}
func (g *GinAdapter) Run() {
portStr := fmt.Sprintf(":%d", g.port)
g.router.Run(portStr)
}