pack_senddata.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package zigbee
  2. import (
  3. "encoding/binary"
  4. "github.com/valyala/bytebufferpool"
  5. )
  6. type PackSendData struct {
  7. M1Flag uint16 //固定为F1F1
  8. M1Leng uint16 //包体1长度
  9. M1Cmd uint8 //1字节
  10. Body1 SendData //n字节
  11. M1Crc uint16 //整包CRC
  12. }
  13. func (o *PackSendData) EnCode() (*bytebufferpool.ByteBuffer, error) {
  14. bytebuf, err := o.Body1.EnCode()
  15. defer func() {
  16. if bytebuf != nil {
  17. bytebufferpool.Put(bytebuf)
  18. }
  19. }()
  20. if err != nil {
  21. return nil, err
  22. }
  23. buff := bytebufferpool.Get()
  24. buff.Write([]byte{0xF1, 0xF1}) //M1Flag uint16 //固定为F1F1
  25. tmp := make([]byte, 2)
  26. binary.BigEndian.PutUint16(tmp, uint16(bytebuf.Len()))
  27. buff.Write(tmp) //M1Leng uint16 //包体1长度
  28. buff.WriteByte(CmdSendData) //M1Cmd uint8 //1字节
  29. buff.Write(bytebuf.B)
  30. crc16 := CRC16(buff.B)
  31. tmp2 := make([]byte, 2)
  32. binary.BigEndian.PutUint16(tmp2, crc16)
  33. buff.Write(tmp2) //计算内层CRC16
  34. return buff, nil
  35. }
  36. func (o *PackSendData) DeCode(Data []byte) error {
  37. if len(Data) < 7 {
  38. return ErrorProtocol
  39. }
  40. if Data[0] != 0xF1 || Data[1] != 0xF1 {
  41. return ErrorProtocol
  42. }
  43. o.M1Flag = 0xF1F1
  44. o.M1Leng = binary.BigEndian.Uint16(Data[2:4])
  45. o.M1Cmd = Data[4]
  46. o.M1Crc = binary.BigEndian.Uint16(Data[o.M1Leng+5 : o.M1Leng+7])
  47. //校验CRC1
  48. crc := CRC16(Data[0 : o.M1Leng+5])
  49. if o.M1Crc != crc {
  50. return ErrorInvalidCrc1
  51. }
  52. if o.M1Leng > 0 {
  53. return o.Body1.DeCode(Data[5 : o.M1Leng+5])
  54. }
  55. return ErrorProtocol
  56. }
  57. type SendData struct {
  58. Flag uint8 //值为1
  59. Datalen uint16 //Header2的长度
  60. Data MsgHeader2 //参见Header2
  61. }
  62. func (o *SendData) EnCode() (*bytebufferpool.ByteBuffer, error) {
  63. bytebuf, err := o.Data.EnCode() //Body2 Pack //包体内容,普通功能协议或升级功能协议
  64. defer func() {
  65. if bytebuf != nil {
  66. bytebufferpool.Put(bytebuf)
  67. }
  68. }()
  69. if err != nil {
  70. return nil, err
  71. }
  72. buff := bytebufferpool.Get()
  73. buff.WriteByte(0x1) //Flag uint8 //值为1
  74. tmp := make([]byte, 2)
  75. binary.BigEndian.PutUint16(tmp, uint16(bytebuf.Len()))
  76. buff.Write(tmp) //Datalen uint16 //Header2的长度
  77. buff.Write(bytebuf.B) //MsgHeader2 MsgHeader2 //参见Header2
  78. return buff, nil
  79. }
  80. func (o *SendData) DeCode(Data []byte) error {
  81. if len(Data) > 3 {
  82. o.Flag = Data[0]
  83. o.Datalen = binary.BigEndian.Uint16(Data[1:3])
  84. return o.Data.DeCode(Data[3:])
  85. }
  86. return ErrorProtocol
  87. }