server.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. }
  22. func NewServer(ctx context.Context, addr string, port int, gw *gatewayV2.Gateway) *Server {
  23. return &Server{
  24. closeChan: make(chan struct{}),
  25. ctx: ctx,
  26. addr: addr,
  27. port: port,
  28. gateWay: gw,
  29. }
  30. }
  31. func (s *Server) Start() error {
  32. glog.Printf("服务端启动[%s:%d]", s.addr, s.port)
  33. server := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
  34. s.server = server
  35. return s.server.Run()
  36. }
  37. func (s *Server) Stop() {
  38. s.server.Close()
  39. }
  40. func (s *Server) onClientConnect(conn *gtcp.Conn) {
  41. glog.Debugf("新的设备接入:%s", conn.RemoteAddr())
  42. c := NewClient(s, conn)
  43. c.closeHandler = func(id string, c *Client) {
  44. glog.Debugf("客户端断开:%s", id)
  45. }
  46. ctx := new(protocol.PacketContext)
  47. data := new(protocol.Data)
  48. go c.ReadLoop(ctx, data)
  49. addressChan := make(chan struct{}, 1)
  50. avChan := make(chan struct{}, 1)
  51. aiChan := make(chan struct{}, 1)
  52. bvChan := make(chan struct{}, 1)
  53. biChan := make(chan struct{}, 1)
  54. cvChan := make(chan struct{}, 1)
  55. ciChan := make(chan struct{}, 1)
  56. powerChan := make(chan struct{}, 1)
  57. addressChan <- struct{}{}
  58. go c.SendGetAddress(ctx, addressChan, avChan)
  59. go c.GetActivePower(ctx, powerChan)
  60. go c.GetAV(ctx, avChan, aiChan)
  61. go c.GetAI(ctx, aiChan, bvChan)
  62. go c.GetBV(ctx, bvChan, biChan)
  63. go c.GetBI(ctx, biChan, cvChan)
  64. go c.GetCV(ctx, cvChan, ciChan)
  65. go c.GetCI(ctx, ciChan, powerChan)
  66. }
  67. func (s *Server) ReportStatus(subId string, data interface{}) error {
  68. return s.gateWay.ReportStatus(subId, "status", data)
  69. }