client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. var value float32
  98. value := gconv.Float32(gbinary.BeDecodeToUint16(buf[3:5])&0x7FFF) / 10
  99. if value < 1 {
  100. value = 0
  101. }
  102. if gbinary.BeDecodeToUint16(buf[3:5])&0x8000 == 0x8000 {
  103. value = -value
  104. }
  105. data.Temperature = value
  106. data.Humidly = gconv.Float32(gbinary.BeDecodeToUint16(buf[5:7])) / 10
  107. if err := c.srv.ReportStatus(c.Id, data, "status"); err != nil {
  108. return err
  109. }
  110. }
  111. if buf[2] == 0x08 {
  112. data := &protocol.OffsetData{
  113. TemOffset: 2,
  114. HumOffset: 2,
  115. }
  116. if gconv.Int(gbinary.BeDecodeToUint16(buf[3:5])) == 1 {
  117. data.TemOffset = 1
  118. value := gconv.Float32(gbinary.BeDecodeToUint16(buf[5:7])&0x7FFF) / 100
  119. if gconv.Int(gbinary.BeDecodeToUint16(buf[5:7])&0x8000) == 0 {
  120. value = -value
  121. }
  122. data.TemOffsetValue = value
  123. }
  124. if gconv.Int(gbinary.BeDecodeToUint16(buf[7:9])) == 1 {
  125. data.HumOffset = 1
  126. data.HumOffsetValue = gconv.Float32(gbinary.BeDecodeToUint16(buf[9:11])) / 100
  127. }
  128. if err := c.srv.ReportStatus(c.Id, data, "rs30_offset"); err != nil {
  129. return err
  130. }
  131. }
  132. }
  133. return nil
  134. }
  135. func (c *Client) readError(err error) {
  136. defer c.closeConnection()
  137. if err == io.EOF || isErrConnReset(err) {
  138. return
  139. }
  140. glog.Errorf("读取数据发生错误:%s", err.Error())
  141. }
  142. func (c *Client) closeConnection() {
  143. _ = c.conn.Close()
  144. c.conn = nil
  145. close(c.closeChan)
  146. c.isReg = false
  147. if c.closeHandler != nil {
  148. c.closeHandler(c.Id, c)
  149. }
  150. }
  151. // 计算温度值, 处理零下的情况
  152. func caleTemperature(data []byte) int {
  153. var ym uint16
  154. var isBlowZero bool
  155. var result int
  156. bm := binary.BigEndian.Uint16(data)
  157. var bitNum = len(data) * 8
  158. f := "%." + strconv.Itoa(bitNum) + "b"
  159. bmStr := fmt.Sprintf(f, bm)
  160. if string(bmStr[0]) == "1" { // blow zero
  161. ym = ^bm + 1
  162. isBlowZero = true
  163. } else {
  164. ym = bm
  165. }
  166. result = int(ym)
  167. if isBlowZero {
  168. result = int(ym) * -1
  169. }
  170. return result
  171. }
  172. // isErrConnReset read: connection reset by peer
  173. func isErrConnReset(err error) bool {
  174. if ne, ok := err.(*net.OpError); ok {
  175. return strings.Contains(ne.Err.Error(), syscall.ECONNRESET.Error())
  176. }
  177. return false
  178. }
  179. // SetOffset 设置温湿度偏移值
  180. func (c *Client) SetOffset(act int, value float32, slaveId int) error {
  181. var sendBuf []byte
  182. buffer := bytes.NewBuffer(sendBuf)
  183. buffer.Write(gbinary.BeEncodeInt(slaveId))
  184. var funcByte byte
  185. var address []byte
  186. if act == 1 || act == 3 {
  187. funcByte = 0x10
  188. } else if act == 2 || act == 4 {
  189. funcByte = 0x06
  190. }
  191. if act == 1 || act == 2 {
  192. address = []byte{0x00, 0x50}
  193. } else if act == 3 || act == 4 {
  194. address = []byte{0x00, 0x52}
  195. }
  196. buffer.WriteByte(funcByte)
  197. buffer.Write(address)
  198. if act == 1 {
  199. number := []byte{0x00, 0x02}
  200. buffer.Write(number)
  201. buffer.Write([]byte{0x00, 0x01})
  202. buffer.Write(dataBlock(value))
  203. } else if act == 3 {
  204. number := []byte{0x00, 0x02}
  205. buffer.Write(number)
  206. buffer.Write([]byte{0x00, 0x01})
  207. buffer.Write(gbinary.BeEncodeUint16(uint16(value * 100)))
  208. } else if act == 2 || act == 4 {
  209. buffer.Write([]byte{0x00, 0x00})
  210. }
  211. var mCrc crc
  212. checkSum := mCrc.reset().pushBytes(buffer.Bytes()).value()
  213. buffer.Write([]byte{byte(checkSum), byte(checkSum >> 8)})
  214. //fmt.Printf("%2X", buffer.Bytes())
  215. c.sendChan <- buffer.Bytes()
  216. return nil
  217. }
  218. func dataBlock(value float32) []byte {
  219. buffer := &bytes.Buffer{}
  220. var a uint16
  221. if value >= 0 {
  222. a = uint16(value*100) | 0x8000
  223. } else {
  224. a = uint16(math.Abs(float64(value))*100) | 0x0000
  225. }
  226. buffer.Write(gbinary.BeEncodeUint16(a))
  227. return buffer.Bytes()
  228. }
  229. func (c *Client) GetOffset() {
  230. c.sendChan <- []byte{0x01, 0x03, 0x00, 0x50, 0x00, 0x04, 0x44, 0x18}
  231. }
  232. func (c *Client) GetSendByte() {
  233. for {
  234. c.sendChan <- []byte{0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B}
  235. time.Sleep(10 * time.Second)
  236. }
  237. }
  238. func (c *Client) send(buf []byte) error {
  239. if c.conn == nil {
  240. return nil
  241. }
  242. glog.Debugf("----->%2X", buf)
  243. err := c.conn.Send(buf)
  244. if err != nil {
  245. glog.Error(c.srv.ctx, err)
  246. c.closeConnection()
  247. return err
  248. }
  249. return nil
  250. }