pack_setpid.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package zigbee
  2. import (
  3. "encoding/binary"
  4. "github.com/valyala/bytebufferpool"
  5. )
  6. type PackSetPid struct {
  7. M1Flag uint16 //固定为F1F1
  8. M1Leng uint16 //包体1长度
  9. M1Cmd uint8 //1字节
  10. Body1 PidFreq
  11. M1Crc uint16 //整包CRC
  12. }
  13. func (o *PackSetPid) SetData(pid uint16, freq byte) {
  14. o.Body1.PID = pid
  15. o.Body1.Frequency = freq
  16. }
  17. func (o *PackSetPid) EnCode() (*bytebufferpool.ByteBuffer, error) {
  18. bytebuf, err := o.Body1.EnCode()
  19. defer func() {
  20. if bytebuf != nil {
  21. bytebufferpool.Put(bytebuf)
  22. }
  23. }()
  24. if err != nil {
  25. return nil, err
  26. }
  27. buff := bytebufferpool.Get()
  28. buff.Write([]byte{0xF1, 0xF1}) //M1Flag uint16 //固定为F1F1
  29. tmp := make([]byte, 2)
  30. binary.BigEndian.PutUint16(tmp, uint16(bytebuf.Len()))
  31. buff.Write(tmp) //M1Leng uint16 //包体1长度
  32. buff.WriteByte(CmdSetPid) //M1Cmd uint8 //1字节
  33. buff.Write(bytebuf.B) //包体1
  34. //crc1
  35. crc16 := CRC16(buff.B)
  36. tmp2 := make([]byte, 2)
  37. binary.BigEndian.PutUint16(tmp2, crc16)
  38. buff.Write(tmp2) //外层CRC16
  39. return buff, nil
  40. }
  41. func (o *PackSetPid) DeCode(Data []byte) error {
  42. if len(Data) < 7 {
  43. return ErrorProtocol
  44. }
  45. if Data[0] != 0xF1 || Data[1] != 0xF1 {
  46. return ErrorProtocol
  47. }
  48. o.M1Flag = binary.BigEndian.Uint16(Data[0:2])
  49. o.M1Leng = binary.BigEndian.Uint16(Data[2:4])
  50. o.M1Cmd = Data[4]
  51. o.M1Crc = binary.BigEndian.Uint16(Data[o.M1Leng+5 : o.M1Leng+7])
  52. //校验CRC1
  53. crc := CRC16(Data[0 : o.M1Leng+5])
  54. if o.M1Crc != crc {
  55. return ErrorInvalidCrc1
  56. }
  57. if o.M1Leng > 0 {
  58. return o.Body1.DeCode(Data[5 : o.M1Leng+5])
  59. }
  60. return ErrorProtocol
  61. }
  62. type PidFreq struct {
  63. PID uint16
  64. Frequency byte
  65. }
  66. func (o *PidFreq) EnCode() (*bytebufferpool.ByteBuffer, error) {
  67. buff := bytebufferpool.Get()
  68. tmp := make([]byte, 2)
  69. binary.BigEndian.PutUint16(tmp, o.PID)
  70. buff.Write(tmp)
  71. buff.WriteByte(o.Frequency)
  72. return buff, nil
  73. }
  74. func (o *PidFreq) DeCode(Data []byte) error {
  75. if len(Data) >= 3 {
  76. o.PID = binary.BigEndian.Uint16(Data)
  77. o.Frequency = Data[2]
  78. return nil
  79. }
  80. return ErrorProtocol
  81. }