server.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package server
  2. import (
  3. "context"
  4. "dlt645-server/protocol"
  5. "fmt"
  6. "github.com/gogf/gf/container/gmap"
  7. "github.com/gogf/gf/frame/g"
  8. "github.com/gogf/gf/net/gtcp"
  9. "github.com/gogf/gf/os/glog"
  10. gatewayV2 "sparrow-sdk/v2"
  11. "sync"
  12. "time"
  13. )
  14. type Server struct {
  15. closeChan chan struct{}
  16. server *gtcp.Server
  17. ctx context.Context
  18. addr string
  19. port int
  20. grMu sync.Mutex
  21. grWG sync.WaitGroup
  22. message protocol.Message
  23. gateWay *gatewayV2.Gateway
  24. clients *gmap.Map
  25. }
  26. func NewServer(ctx context.Context, addr string, port int, gw *gatewayV2.Gateway) *Server {
  27. return &Server{
  28. closeChan: make(chan struct{}),
  29. ctx: ctx,
  30. addr: addr,
  31. port: port,
  32. gateWay: gw,
  33. clients: gmap.New(false),
  34. }
  35. }
  36. func (s *Server) Start() error {
  37. glog.Printf("服务端启动[%s:%d]", s.addr, s.port)
  38. server := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
  39. s.server = server
  40. return s.server.Run()
  41. }
  42. func (s *Server) Stop() {
  43. s.clients.Iterator(func(k interface{}, v interface{}) bool {
  44. client := v.(*Client)
  45. client.closeConnection()
  46. return true
  47. })
  48. _ = s.server.Close()
  49. }
  50. func (s *Server) onClientConnect(conn *gtcp.Conn) {
  51. glog.Debugf("新的设备接入:%s", conn.RemoteAddr())
  52. c := NewClient(s, conn)
  53. c.closeHandler = func(id string, c *Client) {
  54. glog.Debugf("客户端断开:%s", id)
  55. if id != "" {
  56. _ = s.gateWay.SubDeviceLogout(g.Cfg().GetString("Sparrow.DeviceCode"), id)
  57. s.clients.Remove(id)
  58. }
  59. }
  60. c.regHandler = func(id string, c *Client) {
  61. _ = s.gateWay.SubDeviceLogin(g.Cfg().GetString("Sparrow.DeviceCode"), id)
  62. s.clients.Set(id, c)
  63. }
  64. time.Sleep(10 * time.Second)
  65. err := c.SendGetAddress()
  66. if err != nil {
  67. return
  68. }
  69. go c.SendLoop()
  70. go c.GetActivePower()
  71. go c.GetVBlock()
  72. go c.GetIBlock()
  73. }
  74. func (s *Server) ReportStatus(subId string, data interface{}, code string) error {
  75. return s.gateWay.ReportStatus(subId, code, data)
  76. }