service.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package lampControl
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/valyala/bytebufferpool"
  6. "strconv"
  7. )
  8. func (o DataPack) GetLampTurnOnOffCommand() *bytebufferpool.ByteBuffer {
  9. //初始化成员
  10. o.Start = 0x68
  11. o.Addr = o.Addr
  12. o.Start2 = 0x68
  13. o.Ctl = 0x1E
  14. o.Data = append([]byte{0x00, 0x00, 0x60, 0x07, 0x01}, o.Data...) //按路开关灯
  15. o.DataLen = uint8(len(o.Data))
  16. o.End = 0x16
  17. //addr
  18. tmpAddr := EncodeAddr(o.Addr)
  19. if tmpAddr == nil {
  20. return nil
  21. }
  22. //序列化
  23. buf := bytebufferpool.Get()
  24. buf.WriteByte(o.Start)
  25. buf.Write(tmpAddr)
  26. buf.WriteByte(o.Start2)
  27. buf.WriteByte(o.Ctl)
  28. buf.WriteByte(o.DataLen)
  29. if o.DataLen > 0 {
  30. TmpData := make([]byte, o.DataLen)
  31. for i, b := range o.Data {
  32. TmpData[i] = b + 0x33
  33. }
  34. buf.Write(TmpData)
  35. }
  36. //计算校验码
  37. o.Cs = CheckSum(buf.Bytes())
  38. buf.WriteByte(o.Cs)
  39. buf.WriteByte(o.End)
  40. return buf
  41. }
  42. func (o DataPack) GetLampSetBrightCommand(brightness int) *bytebufferpool.ByteBuffer {
  43. //初始化成员
  44. o.Start = 0x68
  45. o.Addr = o.Addr
  46. o.Start2 = 0x68
  47. o.Ctl = 0x1E
  48. hexValue := fmt.Sprintf("%02x", brightness)
  49. decodeString, _ := hex.DecodeString(hexValue)
  50. o.Data = append([]byte{0x00, 0x00, 0x60, 0x09, 0x01}, decodeString...) //按路调光照度
  51. o.DataLen = uint8(len(o.Data))
  52. o.End = 0x16
  53. //addr
  54. tmpAddr := EncodeAddr(o.Addr)
  55. if tmpAddr == nil {
  56. return nil
  57. }
  58. //序列化
  59. buf := bytebufferpool.Get()
  60. buf.WriteByte(o.Start)
  61. buf.Write(tmpAddr)
  62. buf.WriteByte(o.Start2)
  63. buf.WriteByte(o.Ctl)
  64. buf.WriteByte(o.DataLen)
  65. if o.DataLen > 0 {
  66. TmpData := make([]byte, o.DataLen)
  67. for i, b := range o.Data {
  68. TmpData[i] = b + 0x33
  69. }
  70. buf.Write(TmpData)
  71. }
  72. //计算校验码
  73. o.Cs = CheckSum(buf.Bytes())
  74. buf.WriteByte(o.Cs)
  75. buf.WriteByte(o.End)
  76. return buf
  77. }
  78. func CheckSum(data []byte) uint8 {
  79. var sum uint64
  80. for _, c := range data {
  81. sum += uint64(c)
  82. }
  83. return uint8(sum % 256)
  84. }
  85. func EncodeAddr(Addr string) []byte {
  86. var bytes []byte
  87. for i := 0; i < len(Addr); i += 2 {
  88. // 直接解析并添加到字节数组中
  89. if b, err := strconv.ParseUint(Addr[i:i+2], 16, 8); err == nil {
  90. bytes = append(bytes, byte(b))
  91. }
  92. }
  93. // 反转字节顺序
  94. for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
  95. bytes[i], bytes[j] = bytes[j], bytes[i]
  96. }
  97. return bytes
  98. }