deviceMgr.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package tcp
  2. import (
  3. "encoding/hex"
  4. "go.uber.org/zap"
  5. "net"
  6. "server/dao/devices"
  7. Dev "server/dao/devices"
  8. "server/model/common/request"
  9. "server/utils/logger"
  10. "strings"
  11. "time"
  12. )
  13. type Device struct {
  14. info devices.Screens
  15. conn net.Conn
  16. lastTime time.Time
  17. }
  18. func (s *Device) Start(conn net.Conn) {
  19. s.conn = conn
  20. go s.Process()
  21. go s.Handle()
  22. }
  23. func (s *Device) Process() {
  24. // 函数执行完之后关闭连接
  25. defer s.conn.Close()
  26. for {
  27. buf := make([]byte, 256)
  28. // 将tcp连接读取到的数据读取到byte数组中, 返回读取到的byte的数目
  29. n, err := s.conn.Read(buf)
  30. if err != nil {
  31. // 从客户端读取数据的过程中发生错误
  32. logger.Logger.Errorf("read from client failed, err:%v", err)
  33. break
  34. }
  35. data := hex.EncodeToString(buf[:n])
  36. if len(data) > 51 {
  37. logger.Logger.Debugf("led sn = %v", data[34:50])
  38. }
  39. if !strings.Contains(strings.ToLower(data), "fe5c4b89") {
  40. continue
  41. }
  42. switch data[16:18] {
  43. case "61":
  44. logger.Logger.Debug("登录")
  45. reply, _ := hex.DecodeString(
  46. "fe5c4b892a0000006200000000170000003123323032333035313530313038333431352330363023ffff")
  47. s.conn.Write(reply)
  48. case "91":
  49. logger.Logger.Debug("心跳")
  50. if data[34:50] != s.info.ScreensCode {
  51. continue
  52. }
  53. s.UpdateInfo(data[82:84], data[86:88], data[90:92])
  54. }
  55. }
  56. }
  57. func (s *Device) Handle() {
  58. t2 := time.NewTicker(3 * time.Minute) //在线监测
  59. for {
  60. select {
  61. case <-t2.C:
  62. state := request.DeviceStatus{
  63. Status: 1,
  64. PlayStatus: s.info.PlayStatus,
  65. DisplayStatus: s.info.DisplayStatus,
  66. SourceStatus: s.info.SourceStatus,
  67. }
  68. if time.Now().Add(-2 * time.Minute).After(s.lastTime) {
  69. //离线
  70. state.Status = 0
  71. } else {
  72. logger.Logger.Debugf("%s在线", s.info.ScreensCode)
  73. }
  74. //修改数据库状态
  75. err := Dev.UpdateScreensStatus(s.info.ScreensCode, state)
  76. if err != nil {
  77. logger.Logger.Error("UpdateScreensStatus err", zap.Error(err))
  78. continue
  79. }
  80. break
  81. default:
  82. continue
  83. }
  84. }
  85. }
  86. func (s *Device) UpdateInfo(playStatus, displayStatus, sourceStatus string) {
  87. play, display, source := 0, 0, 0
  88. if playStatus != "31" {
  89. play = 1
  90. }
  91. if displayStatus != "30" {
  92. display = 1
  93. }
  94. if sourceStatus != "30" {
  95. source = 1
  96. }
  97. s.info.Status = 1
  98. s.info.PlayStatus = play
  99. s.info.DisplayStatus = display
  100. s.info.SourceStatus = source
  101. s.lastTime = time.Now()
  102. }