server.go 2.1 KB

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