server.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/container/gmap"
  6. "github.com/gogf/gf/frame/g"
  7. "github.com/gogf/gf/net/gtcp"
  8. "github.com/gogf/gf/os/glog"
  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. glog.Printf("服务端启动[%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. glog.Debugf("新的设备接入:%s", conn.RemoteAddr())
  47. client := NewClient(s, conn)
  48. client.closeHandler = func(id string, c *Client) {
  49. glog.Debugf("客户端断开:%s", id)
  50. if id != "" {
  51. _ = s.gateWay.SubDeviceLogout(g.Cfg().GetString("sparrow.DeviceCode"), id)
  52. s.clients.Remove(id)
  53. }
  54. }
  55. client.regHandler = func(id string, c *Client) {
  56. _ = s.gateWay.SubDeviceLogin(g.Cfg().GetString("Sparrow.DeviceCode"), 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. }