client.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package server
  2. import (
  3. "bth-rs30-gateway/protocol"
  4. "bytes"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "github.com/gogf/gf/encoding/gbinary"
  9. "github.com/gogf/gf/net/gtcp"
  10. "github.com/gogf/gf/os/glog"
  11. "github.com/gogf/gf/util/gconv"
  12. "io"
  13. "math"
  14. "net"
  15. "strconv"
  16. "strings"
  17. "syscall"
  18. "time"
  19. )
  20. type Client struct {
  21. Id string
  22. srv *Server
  23. conn *gtcp.Conn
  24. sendChan chan []byte
  25. closeChan chan struct{}
  26. closeHandler func(id string, c *Client)
  27. regHandler func(id string, c *Client)
  28. isReg bool
  29. }
  30. func NewClient(s *Server, conn *gtcp.Conn) *Client {
  31. return &Client{
  32. srv: s,
  33. conn: conn,
  34. sendChan: make(chan []byte),
  35. closeChan: make(chan struct{}),
  36. }
  37. }
  38. func (c *Client) SetId(id string) {
  39. c.Id = id
  40. }
  41. func (c *Client) SendLoop() {
  42. for {
  43. select {
  44. case buf := <-c.sendChan:
  45. err := c.send(buf)
  46. if err != nil {
  47. glog.Errorf("指令发送失败:%s", err.Error())
  48. continue
  49. }
  50. timer := time.NewTimer(5 * time.Second)
  51. for {
  52. select {
  53. case <-c.closeChan:
  54. return
  55. case <-timer.C:
  56. glog.Error("接收指令超时")
  57. break
  58. default:
  59. receiveBuf, err := c.conn.Recv(-1)
  60. if err != nil {
  61. c.readError(err)
  62. break
  63. }
  64. if !c.isReg {
  65. id := gbinary.DecodeToString(receiveBuf)
  66. glog.Debugf("收到注册包!id:%s", id)
  67. c.SetId(id)
  68. c.isReg = true
  69. if c.regHandler != nil {
  70. c.regHandler(c.Id, c)
  71. }
  72. continue
  73. }
  74. glog.Debugf("收到数据:%2X", receiveBuf)
  75. if err := c.decodeAndReport(receiveBuf); err != nil {
  76. glog.Debugf("处理数据失败:%s", err.Error())
  77. break
  78. }
  79. }
  80. break
  81. }
  82. }
  83. }
  84. }
  85. // 收到数据:01 03 04 00 FD 00 8A EA 64
  86. func (c *Client) decodeAndReport(buf []byte) error {
  87. length := len(buf)
  88. var crc crc
  89. crc.reset().pushBytes(buf[0 : length-2])
  90. checksum := uint16(buf[length-1])<<8 | uint16(buf[length-2])
  91. if checksum != crc.value() {
  92. return errors.New(fmt.Sprintf("modbus: response crc '%v' does not match expected '%v'", checksum, crc.value()))
  93. }
  94. if buf[1] == 0x03 {
  95. if buf[2] == 0x04 {
  96. data := &protocol.Data{}
  97. data.Temperature = gconv.Float32(caleTemperature(buf[3:5])) / 10
  98. data.Humidly = gconv.Float32(gbinary.BeDecodeToUint16(buf[5:7])) / 10
  99. if err := c.srv.ReportStatus(c.Id, data, "status"); err != nil {
  100. return err
  101. }
  102. }
  103. if buf[2] == 0x08 {
  104. data := &protocol.OffsetData{
  105. TemOffset: 2,
  106. HumOffset: 2,
  107. }
  108. if gconv.Int(gbinary.BeDecodeToUint16(buf[3:5])) == 1 {
  109. data.TemOffset = 1
  110. value := gconv.Float32(gbinary.BeDecodeToUint16(buf[5:7])&0x7FFF) / 100
  111. if gconv.Int(gbinary.BeDecodeToUint16(buf[5:7])&0x8000) == 0 {
  112. value = -value
  113. }
  114. data.TemOffsetValue = value
  115. }
  116. if gconv.Int(gbinary.BeDecodeToUint16(buf[7:9])) == 1 {
  117. data.HumOffset = 1
  118. data.HumOffsetValue = gconv.Float32(gbinary.BeDecodeToUint16(buf[9:11])) / 100
  119. }
  120. if err := c.srv.ReportStatus(c.Id, data, "rs30_offset"); err != nil {
  121. return err
  122. }
  123. }
  124. }
  125. return nil
  126. }
  127. func (c *Client) readError(err error) {
  128. defer c.closeConnection()
  129. if err == io.EOF || isErrConnReset(err) {
  130. return
  131. }
  132. glog.Errorf("读取数据发生错误:%s", err.Error())
  133. }
  134. func (c *Client) closeConnection() {
  135. _ = c.conn.Close()
  136. c.conn = nil
  137. close(c.closeChan)
  138. c.isReg = false
  139. if c.closeHandler != nil {
  140. c.closeHandler(c.Id, c)
  141. }
  142. }
  143. // 计算温度值, 处理零下的情况
  144. func caleTemperature(data []byte) int {
  145. var ym uint16
  146. var isBlowZero bool
  147. var result int
  148. bm := binary.BigEndian.Uint16(data)
  149. var bitNum = len(data) * 8
  150. f := "%." + strconv.Itoa(bitNum) + "b"
  151. bmStr := fmt.Sprintf(f, bm)
  152. if string(bmStr[0]) == "1" { // blow zero
  153. ym = ^bm + 1
  154. isBlowZero = true
  155. } else {
  156. ym = bm
  157. }
  158. result = int(ym)
  159. if isBlowZero {
  160. result = int(ym) * -1
  161. }
  162. return result
  163. }
  164. // isErrConnReset read: connection reset by peer
  165. func isErrConnReset(err error) bool {
  166. if ne, ok := err.(*net.OpError); ok {
  167. return strings.Contains(ne.Err.Error(), syscall.ECONNRESET.Error())
  168. }
  169. return false
  170. }
  171. // SetOffset 设置温湿度偏移值
  172. func (c *Client) SetOffset(act int, value float32, slaveId int) error {
  173. var sendBuf []byte
  174. buffer := bytes.NewBuffer(sendBuf)
  175. buffer.Write(gbinary.BeEncodeInt(slaveId))
  176. var funcByte byte
  177. var address []byte
  178. if act == 1 || act == 3 {
  179. funcByte = 0x10
  180. } else if act == 2 || act == 4 {
  181. funcByte = 0x06
  182. }
  183. if act == 1 || act == 2 {
  184. address = []byte{0x00, 0x50}
  185. } else if act == 3 || act == 4 {
  186. address = []byte{0x00, 0x52}
  187. }
  188. buffer.WriteByte(funcByte)
  189. buffer.Write(address)
  190. if act == 1 {
  191. number := []byte{0x00, 0x02}
  192. buffer.Write(number)
  193. buffer.Write([]byte{0x00, 0x01})
  194. buffer.Write(dataBlock(value))
  195. } else if act == 3 {
  196. number := []byte{0x00, 0x02}
  197. buffer.Write(number)
  198. buffer.Write([]byte{0x00, 0x01})
  199. buffer.Write(gbinary.BeEncodeUint16(uint16(value * 100)))
  200. } else if act == 2 || act == 4 {
  201. buffer.Write([]byte{0x00, 0x00})
  202. }
  203. var mCrc crc
  204. checkSum := mCrc.reset().pushBytes(buffer.Bytes()).value()
  205. buffer.Write([]byte{byte(checkSum), byte(checkSum >> 8)})
  206. //fmt.Printf("%2X", buffer.Bytes())
  207. c.sendChan <- buffer.Bytes()
  208. return nil
  209. }
  210. func dataBlock(value float32) []byte {
  211. buffer := &bytes.Buffer{}
  212. var a uint16
  213. if value >= 0 {
  214. a = uint16(value*100) | 0x8000
  215. } else {
  216. a = uint16(math.Abs(float64(value))*100) | 0x0000
  217. }
  218. buffer.Write(gbinary.BeEncodeUint16(a))
  219. return buffer.Bytes()
  220. }
  221. func (c *Client) GetOffset() {
  222. c.sendChan <- []byte{0x01, 0x03, 0x00, 0x50, 0x00, 0x04, 0x44, 0x18}
  223. }
  224. func (c *Client) GetSendByte() {
  225. for {
  226. c.sendChan <- []byte{0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B}
  227. time.Sleep(10 * time.Second)
  228. }
  229. }
  230. func (c *Client) send(buf []byte) error {
  231. if c.conn == nil {
  232. return nil
  233. }
  234. glog.Debugf("----->%2X", buf)
  235. err := c.conn.Send(buf)
  236. if err != nil {
  237. glog.Error(c.srv.ctx, err)
  238. c.closeConnection()
  239. return err
  240. }
  241. return nil
  242. }