server.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package server
  2. import (
  3. "context"
  4. "dlt645-server/protocol"
  5. "fmt"
  6. "github.com/gogf/gf/net/gtcp"
  7. "github.com/gogf/gf/os/glog"
  8. gatewayV2 "sparrow-sdk/v2"
  9. "sync"
  10. )
  11. type Server struct {
  12. closeChan chan struct{}
  13. server *gtcp.Server
  14. ctx context.Context
  15. addr string
  16. port int
  17. grMu sync.Mutex
  18. grWG sync.WaitGroup
  19. message protocol.Message
  20. gateWay *gatewayV2.Gateway
  21. packetCtx *protocol.PacketContext
  22. data *protocol.Data
  23. }
  24. func NewServer(ctx context.Context, addr string, port int, gw *gatewayV2.Gateway, packetCtx *protocol.PacketContext, data *protocol.Data) *Server {
  25. return &Server{
  26. closeChan: make(chan struct{}),
  27. ctx: ctx,
  28. addr: addr,
  29. port: port,
  30. gateWay: gw,
  31. packetCtx: packetCtx,
  32. data: data,
  33. }
  34. }
  35. func (s *Server) Start() error {
  36. glog.Printf("服务端启动[%s:%d]", s.addr, s.port)
  37. server := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
  38. s.server = server
  39. return s.server.Run()
  40. }
  41. func (s *Server) Stop() {
  42. s.server.Close()
  43. }
  44. func (s *Server) onClientConnect(conn *gtcp.Conn) {
  45. glog.Debugf("新的设备接入:%s", conn.RemoteAddr())
  46. c := NewClient(s, conn)
  47. c.closeHandler = func(id string, c *Client) {
  48. glog.Debugf("客户端断开:%s", id)
  49. }
  50. _ = c.SendGetAddress(s.packetCtx, s.data)
  51. go c.SendLoop(s.packetCtx, s.data)
  52. go c.GetActivePower(s.packetCtx)
  53. go c.GetVBlock(s.packetCtx)
  54. go c.GetIBlock(s.packetCtx)
  55. }
  56. func (s *Server) ReportStatus(subId string, data interface{}) error {
  57. return s.gateWay.ReportStatus(subId, "status", data)
  58. }