server.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. c.sendChan <- c.SendGetAddress(ctx)
  48. data := new(protocol.Data)
  49. go c.SendLoop(ctx, data)
  50. go c.GetActivePower(ctx)
  51. go c.GetAV(ctx)
  52. go c.GetAI(ctx)
  53. }
  54. func (s *Server) ReportStatus(subId string, data interface{}) error {
  55. return s.gateWay.ReportStatus(subId, "status", data)
  56. }